Skip to content

How to use or execute a package installed using npm

New Course Coming Soon:

Get Really Good at Git

How to include and use in your code a package installed in your node_modules folder

When you install using npm a package into your node_modules folder, or also globally, how do you use it in your Node code?

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')

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

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: