我尝试全局安装,然后像这样使用forever和forever-monitor:
NPM install -g forever forever-monitor
我看到通常的输出,也复制文件到全局路径的操作,但如果我尝试要求(“永远”);我得到一个错误,说模块没有找到。
我正在使用最新版本的node和npm,我已经知道了npm在全局vs本地安装中所做的改变,但我真的不想在每个项目上安装本地,我正在一个不支持链接的平台上工作,所以npm链接后的全局安装对我来说是不可能的。
我的问题是:为什么我不能要求全局安装包?这是一个功能还是一个漏洞?还是我做错了什么?
PS:只是让它非常清楚:我不想在本地安装。
根据文档,Node.js将默认搜索以下位置:
Path specified in the NODE_PATH environment variable.
Note: NODE_PATH environment variable is set to a colon-delimited list of absolute paths.
Current node_modules folder. (local)
$HOME/.node_modules (global)
Note: $HOME is the user's home directory.
$HOME/.node_libraries (global)
$PREFIX/lib/node (global)
Note: $PREFIX is Node.js's configured node_prefix.
To check the current value of node_prefix, run:
node -p process.config.variables.node_prefix
Note: Prefix corresponds to --prefix param during build and it's relative to process.execPath. Not to confuse with value from the npm config get prefix command.source
如果找不到给定的模块,这意味着它不在上述位置之一。
安装模块的全局根文件夹的位置可以通过:npm root -g打印(默认情况下,路径是在运行时计算的,除非在npmrc文件中被覆盖)。
解决方案
您可以尝试以下变通方法:
Specify your global module location in NODE_PATH environment variable. E.g.
echo 'require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node
To test and print the value of NODE_PATH, run:
echo 'console.log(process.env.NODE_PATH); require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node
For more permanent solution, link your $HOME/.node_modules global user folder to point to the root folder, by running this command:
ln -vs "$(npm root -g)" "$HOME"/.node_modules
Then re-test it via: echo 'require("forever")' | node command.
Temporary change the current folder to where the extension has been installed globally, before invoking the script. E.g.
npm install -g forever
cd "$(npm root -g)"
echo 'require("forever")' | node
cd -
Configure global installation destination in npm userconfig file (see: npm help 5 npmrc) or by userconfig param (--prefix).
To display the current config, run: npm config list.
To edit the current config, run: npm config edit.
Specify the full path of node modules location when calling require(). E.g.
require("/path/to/sub/module")
Install the package to custom location, e.g.
npm install forever -g --prefix "$HOME"/.node_modules
However, the installation will go under ~/.node_modules/lib/node_modules/, so the location still needs to be added.
See: npm local install package to custom location
Create a symlink in the current folder from the location of the global package. E.g.
npm link forever