How to use or execute packages installed with npm

How to include and use the packages installed in the node_modules folder in the code

Install when you usenpmA package to yoursnode_modulesFolder, or in the global scope, how to use it in node code?

Say installlodash, A popular JavaScript utility library, using

npm install lodash

This will install the package locallynode_modulesfolder.

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

const _ = require('lodash')

What if your package is an executable file?

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

An easy way to prove this isCowsay.

The Cowsay package provides a command line program that can be executed to make the cow say something (and other animals can also speak).

When installing the package using the following methodnpm install cowsay, It will install itself and install some dependencies in the node_modules folder:

The node_modules folder content

There is a hidden .bin folder that contains a symbolic link to the Cowsay binary file:

The binary files

How do you perform this?

Of course you can enter./node_modules/.bin/cowsayRun it and it works, butPixel, Included in the latest version of npm (since version 5.2), is a better choice. You just need to run:

npx cowsay

Then npx will find the location of the package.

Cow says something

Download mine for freeNode.js manual

More node tutorials: