How to use or execute a package installed using npm

By

Learn how to use an npm package you installed, importing a library like lodash with require(), and running an executable like cowsay with npx.

~~~

When you install a package using npm into your node_modules folder, or also globally, you use it in one of two ways: you import it in your code if it’s a library, or you run it with npx if it’s an executable. Let’s see both.

How do you use a library package?

Say you install lodash, the popular JavaScript utility library, using

npm install lodash

This is going to install the package in the local node_modules folder.

To use it in your code, you just need to import it into your program using require:

const _ = require('lodash')

From this point on, everything the package exports is available through that variable:

const people = ['Flavio', 'Syd', 'Roger']
_.shuffle(people) //['Syd', 'Roger', 'Flavio']

If your project uses ES modules (you have "type": "module" in the package.json file), you use import instead:

import _ from 'lodash'

One common error at this stage is Cannot find module 'lodash'. It means Node can’t find the package. Node looks for a node_modules folder starting from the folder of your file, then walks up the parent folders. Run npm install lodash inside your project folder, and the error goes away.

How do you run an executable package?

What if your package is an executable?

In this case, it will put the executable file under the node_modules/.bin/ folder.

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 node_modules folder:

The node_modules folder content

There is a hidden .bin folder, which contains symbolic links to the cowsay binaries:

The binary files

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:

npx cowsay

and npx will find the package location.

Cow says something

There’s a third option: package.json scripts. Inside a script you can call cowsay directly, because npm adds node_modules/.bin to the path when it runs scripts:

{
  "scripts": {
    "cow": "cowsay hello"
  }
}

Now npm run cow prints the cow. This is the way to go when the command is part of your daily workflow, like a build or test tool.

Tagged: Node.js · All topics
~~~

Related posts about node: