npm软件安装包
When you install using npm
a package into your node_modules
folder, or also globally, how do you use it in your Node code?
当您使用npm
将软件包安装到node_modules
文件夹中或全局安装时,如何在Node代码中使用它?
Say you install lodash
, the popular JavaScript utility library, using
假设您使用以下命令安装了流行JavaScript实用程序库lodash
npm install lodash
This is going to install the package in the local node_modules
folder.
这将把软件包安装在本地的node_modules
文件夹中。
To use it in your code, you just need to import it into your program using require
:
要在代码中使用它,您只需要使用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.
在这种情况下,它将把可执行文件放在node_modules/.bin/
文件夹下。
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 🦊).
Cowsay软件包提供了一个命令行程序,可以执行该程序以使母牛说出某些东西(以及其他动物也可以说话)。
When you install the package using npm install cowsay
, it will install itself and a few dependencies in the node_modules folder:
当您使用npm install cowsay
安装软件包时,它将安装自身以及node_modules文件夹中的一些依赖项:

There is a hidden .bin folder, which contains symbolic links to the cowsay binaries:
有一个隐藏的.bin文件夹,其中包含指向Cowsay二进制文件的符号链接:

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:
你当然可以键入./node_modules/.bin/cowsay
来运行它,和它的作品,但NPX ,包括在最近的NPM的版本(因为5.2),是一个更好的选择。 您只需运行:
npx cowsay
and npx will find the package location.
然后npx将找到程序包的位置。

npm软件安装包