How to use or execute a package installed using npm
When you install a package into your
node_modules folder using
npm , or also globally, how do you use it in your Node.js code?
Say you install
BASHnpm install lodash
This is going to install the package in the local
To use it in your code, you just need to import it into your program using
JSconst _ = require('lodash');
What if your package is an executable?
In this case, it will put the executable file under the
One easy way to demonstrate this is cowsay.
The cowsay package provides a command line program that can be executed to make a cow say something (and other animals as well 🦊).
When you install the package using
npm install cowsay, it will install itself and a few dependencies in the
There is a hidden
.bin folder, which contains symbolic links to the cowsay binaries:
How do you execute those?
You can of course type
./node_modules/.bin/cowsay to run it, and it works, but
npx, included in the recent versions of
npm (since 5.2), is a much better option. You just run:
BASHnpx cowsay take me out of here
npx will find the executable location.