How to Use or Execute a Package Installed Using npm
Learn how to include and use a package that you have installed using npm into your Node.js code.
When you install a package using npm, it gets saved into your node_modules folder. But how do you actually use it in your code?
Let’s say you have installed the popular JavaScript utility library lodash using the following command:
1 | npm install lodash |
This command will install the lodash package in your local node_modules folder.
To use the package in your code, simply import it using the require statement:
1 | const _ = require('lodash'); |
But what if the package you have installed is an executable? In that case, the executable file will be located under the node_modules/.bin/ folder.
Let’s take the example of the cowsay package, which provides a command-line program that makes a cow say something (and other animals too 🦊).
When you install the cowsay package using npm install cowsay, it will not only install the package itself, but also a few dependencies in your node_modules folder.
Here’s a snapshot of the contents of the node_modules folder after installing cowsay:

As you can see, there is a hidden .bin folder that contains symbolic links to the cowsay binaries:

So, how do you execute these binaries?
You can certainly use the direct path ./node_modules/.bin/cowsay to run it, and it will work. However, a better option is to use npx, which is included in the recent versions of npm (since 5.2). Simply run the following command:
1 | npx cowsay |
npx will automatically find the location of the package and execute it.
And there you have it! Now you know how to include and use a package installed using npm in your Node.js code.
tags: [“npm”, “node.js”, “package installation”, “executable”, “npx”]