Have you ever come across a tutorial with instructions like the following?
npm install knex, then run
knex migrate:make migration_name
That's great that you can run the npm package you just installed (knex, in this case) from the command line, but what's usually left out is how you actually go about doing that.
One day to do this is to add your node_modules binary folder to your PATH, using something like PATH=$(npm bin). But sometimes adding more stuff to the PATH can be annoying, and doesn't always play well with relative/absolute paths.
And depending on which version of npm or nvm you're using and if you've already made any changes to your $PATH, if you install the package globally, you can then run it from the command line. But this then pollutes your global modules. If you don't need a package installed globally, why do it?
Another way is to run the package from the command line by specifying the full path for the module. Imagine this is a locally installed package we're trying to run - from the command line it would be:
$ projects/my-db-project/node_modules/knex/cli.js migrate:make migration_name
But having to type that out for each node module you want to run from the command line? And having to remember all their paths? That's even more annoying than adding to the $PATH variable...
npx to the rescue
If you're using a npm version >= 5.2.0, it comes with a great tool called
npx. npx lets you run commands from a local node_modules/.bin. And it's really easy to use - our
knex command from above would simply be:
npx knex migrate:make migration_name
Testing out packages
npx also lets us install "temporary" (not installed globally) packages if they don't already exist.
For example, if you don't have
create-react-app installed but want to test it out, you can do
npx create-react-app my-app (passing options just like you would if it was already installed) and npx will install the package then run the command for you.
So next time you need to run a npm package from the command line and want a dead simple solution, use npx!
If you found this post helpful, be sure to subscribe below to get all my future posts (and cheatsheets, example projects, etc.) delivered directly to your inbox without having to remember to check back here!
Subscribe for new posts!
No spam ever. Unsubscribe any time.