为什么我可以 运行 按名称全局安装节点模块?

Why can I run globally installed node modules by name?

我全局安装了一个节点模块,比方说 grunt 模块。我通过以下方式安装它:

npm install -g grunt

安装在 %APPDATA%\npm\node_modules\grunt

然后我可以在命令行中运行它,比如grunt --version。这是怎么发生的?我的意思是,为什么我可以直接使用grunt作为命令?

顺便说一句,我正在使用 Windows。我通过 .msi 安装程序安装 NodeJS。

您并没有真正从命令中 运行 将 grunt 包作为一个整体。

此设置从与包同名的 grunt's package.json. In that, it's specified a bin script 开始。

"bin": {
  "grunt": "bin/grunt"
},

当你 install the package globally 时,npm 会为每个 bin 脚本(每个包可以有多个)添加一个可执行文件到系统路径中的一个目录,允许命令行在你输入命令。

当您 运行 grunt 时,它是从安装目录到 运行ning node bin/grunt 的快捷方式,传递您在其后提供的任何参数.