Originally published at coreycleary.me. This is a cross-post from my content blog. I publish new content every week or two, and you can sign up to my newsletter if you'd like to receive my articles directly to your inbox! I also regularly send cheatsheets and other freebies.
Have you ever come across a tutorial with instructions like the following?
Run `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!
And if you found this post helpful, here's that link again to subscribe to my newsletter!