NodeJS 需要一个全局模块/包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15636367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS require a global module/package
提问by alexandernst
I'm trying to install globally and then use foreverand forever-monitorlike this:
我试图在全球范围内安装,然后使用forever和forever-monitor这样的:
npm install -g forever forever-monitor
npm install -g forever forever-monitor
I see the usual output and also the operations that copy the files to the global path, but then if I try to require("forever");I get an error saying that the module wasn't found.
我看到了通常的输出以及将文件复制到全局路径的操作,但是如果我尝试这样做,require("forever");我会收到一条错误消息,指出未找到该模块。
I'm using latest version of both node and npm and I already know about the change that npm made in global vs local install, but I really don't wantto install localy on every project and I'm working on a platform that doesn't support linkso npm linkafter a global install isn't possible for me.
我正在使用 node 和 npm 的最新版本,并且我已经知道 npm 在全局安装和本地安装中所做的更改,但我真的不想在每个项目上都安装 localy,而且我正在一个没有的平台上工作'不支持,link所以npm link在我无法进行全局安装之后。
My question is: why I can't require a globally installed package? Is that a feature or a bug? Or am I doing something wrong?
我的问题是:为什么我不能要求全局安装的软件包?这是一个功能还是一个错误?还是我做错了什么?
PS: Just to make it crystal clear: I don't want to install locally.
PS:只是为了清楚说明:我不想在本地安装。
回答by Daniel Uzunu
In Node.js, require doesn't look in the folder where global modules are installed.
在 Node.js 中,require 不会在安装全局模块的文件夹中查找。
You can fix this by setting the NODE_PATH environment variable. In Linux this will be:
您可以通过设置 NODE_PATH 环境变量来解决此问题。在 Linux 中,这将是:
export NODE_PATH=/usr/lib/node_modules
Note: This depend on where your global modules are actually installed.
注意:这取决于您的全局模块的实际安装位置。
See: Loading from the global folders.
请参阅:从全局文件夹加载。
回答by user568109
回答by Thomas Ingham
Apologies for the necromancy but I'm able to specify hard-coded paths to globally installed modules:
为死灵法术道歉,但我能够指定全局安装模块的硬编码路径:
var pg = require("/usr/local/lib/node_modules/pg");
This isn't perfect but considering that Unity3d tries to "compile" all javascript that is included in the project directory I really can't install any packages.
这并不完美,但考虑到 Unity3d 尝试“编译”项目目录中包含的所有 javascript,我真的无法安装任何软件包。
回答by Joe Skeen
I know this is an old question, but I ran into this when trying to do some version checking using semverin a preinstallscript in package.json. Since I knew I can't depend on any local modules installed, I used this to require semverfrom the global node_modulesfolder (as npmdepends on it I know it's there):
我知道这是一个老问题,但试图做使用一些版本检查时,我就遇到了这个semver在preinstall脚本中package.json。因为我知道我不能依赖安装的任何本地模块,所以我使用它semver从全局node_modules文件夹中要求(因为npm我知道它在那里):
function requireGlobal(packageName) {
var childProcess = require('child_process');
var path = require('path');
var fs = require('fs');
var globalNodeModules = childProcess.execSync('npm root -g').toString().trim();
var packageDir = path.join(globalNodeModules, packageName);
if (!fs.existsSync(packageDir))
packageDir = path.join(globalNodeModules, 'npm/node_modules', packageName); //find package required by old npm
if (!fs.existsSync(packageDir))
throw new Error('Cannot find global module \'' + packageName + '\'');
var packageMeta = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json')).toString());
var main = path.join(packageDir, packageMeta.main);
return require(main);
}
I like this approach because this doesn't require the install of any special modules in order to use.
我喜欢这种方法,因为这不需要安装任何特殊模块即可使用。
I didn't go with a NODE_PATHsolution like others have suggested since I wanted to get this to work on anyone's machine, without having to require additional configuration/setup before running npm installfor my project.
我没有采用NODE_PATH其他人建议的解决方案,因为我想让它在任何人的机器上运行,而无需在运行npm install我的项目之前进行额外的配置/设置。
The way this is coded, it is only guaranteed to find top-level modules (installed using npm install -g ...) or modules required by npm(listed as dependencieshere: https://github.com/npm/npm/blob/master/package.json). If you are using a newer version of NPM, it may find dependencies of other globally installed packages since there is a flatter structure for node_modulesfolders now.
这种编码方式,只能保证找到顶级模块(使用 安装npm install -g ...)或所需的模块npm(在dependencies此处列出:https: //github.com/npm/npm/blob/master/package.json)。如果您使用的是较新版本的 NPM,它可能会发现其他全局安装包的依赖项,因为node_modules现在文件夹的结构更加扁平。
Hope this is useful to someone.
希望这对某人有用。
回答by kenorb
As per documentation, Node.js will search in the following locations by default:
根据文档,Node.js 默认会在以下位置进行搜索:
Path specified in the
NODE_PATHenvironment variable.Note:
NODE_PATHenvironment variable is set to a colon-delimited list of absolute paths.Current
node_modulesfolder.(local)$HOME/.node_modules(global)Note:
$HOMEis the user's home directory.$HOME/.node_libraries(global)$PREFIX/lib/node(global)Note:
$PREFIXis Node.js's configurednode_prefix.To check the current value of
node_prefix, run:node -p process.config.variables.node_prefixNote: Prefix corresponds to
--prefixparam during build and it's relative toprocess.execPath. Not to confuse with value from thenpm config get prefixcommand.source
NODE_PATH环境变量中指定的路径。注意:
NODE_PATH环境变量设置为以冒号分隔的绝对路径列表。当前
node_modules文件夹。(当地的)$HOME/.node_modules(全球的)注意:
$HOME是用户的家目录。$HOME/.node_libraries(全球的)$PREFIX/lib/node(全球的)注意:
$PREFIX是 Node.js 的配置文件node_prefix。要检查 的当前值
node_prefix,请运行:node -p process.config.variables.node_prefix注意:Prefix
--prefix在构建过程中对应于param 并且它相对于process.execPath. 不要与npm config get prefix命令中的值混淆。来源
If the given module can't be found, that means it is not present in one of the above locations.
如果找不到给定的模块,则意味着它不存在于上述位置之一。
Location of global root folder where modules are installed can be printed by: npm root -g(by default the path is computed at run-time unless overridden in npmrcfile).
安装模块的全局根文件夹的位置可以通过以下方式打印:(npm root -g默认情况下,路径是在运行时计算的,除非在npmrcfile 中覆盖)。
Solution
解决方案
You can try the following workarounds:
您可以尝试以下解决方法:
Specify your global module location in
NODE_PATHenvironment variable. E.g.echo 'require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" nodeTo 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" nodeFor more permanent solution, link your
$HOME/.node_modulesglobal user folder to point to the root folder, by running this command:ln -vs "$(npm root -g)" "$HOME"/.node_modulesThen re-test it via:
echo 'require("forever")' | nodecommand.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
npmuserconfig file(see:npm help 5 npmrc) or byuserconfigparam (--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 locationwhen calling
require(). E.g.require("/path/to/sub/module")Install the package to custom location, e.g.
npm install forever -g --prefix "$HOME"/.node_modulesHowever, the installation will go under
~/.node_modules/lib/node_modules/, so the location still needs to be added.Create a symlinkin the current folder from the location of the global package. E.g.
npm link forever
在
NODE_PATH环境变量中指定全局模块位置。例如echo 'require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node要测试和打印 的值
NODE_PATH,请运行:echo 'console.log(process.env.NODE_PATH); require("forever")' | NODE_PATH="$(npm root -g):$NODE_PATH" node要获得更持久的解决方案,请
$HOME/.node_modules通过运行以下命令将全局用户文件夹链接到根文件夹:ln -vs "$(npm root -g)" "$HOME"/.node_modules然后通过:
echo 'require("forever")' | node命令重新测试它。在调用脚本之前,将当前文件夹临时更改为全局安装扩展的位置。例如
npm install -g forever cd "$(npm root -g)" echo 'require("forever")' | node cd -在
npmuserconfig 文件中配置全局安装目标(请参阅:)npm help 5 npmrc或通过userconfig参数(--prefix)。要显示当前配置,运行:
npm config list。编辑当前的配置,运行:
npm config edit。调用时指定节点模块位置的完整路径
require()。例如require("/path/to/sub/module")将包安装到自定义位置,例如
npm install forever -g --prefix "$HOME"/.node_modules但是,安装会在 下
~/.node_modules/lib/node_modules/,所以位置还需要添加。从全局包的位置在当前文件夹中创建符号链接。例如
npm link forever
回答by JP Richardson
You can use the package requiregto solve this problem:
你可以使用这个包requireg来解决这个问题:
var forever = require('requireg')('forever')
will do the trick.
会做的伎俩。
Also, there's another module, global-npm, while specific to just using the global npm, you can look at the short codeand see how the technique works.
此外,还有另一个模块 ,global-npm虽然特定于仅使用 global npm,但您可以查看短代码并了解该技术是如何工作的。
回答by Christophe Marois
For CLI utilities that depend on big modules, like puppeteer, I like to spawn a npm root -gand use it to require the global module.
对于依赖于大模块的 CLI 实用程序,例如puppeteer,我喜欢生成 anpm root -g并使用它来要求全局模块。
try {
const root = require('child_process').execSync('npm root -g').toString().trim()
var puppeteer = require(root + '/puppeteer')
} catch (err) {
console.error(`Install puppeteer globally first with: npm install -g puppeteer`)
process.exit(1)
}
回答by Luis Paulo
You can put this line in your .profilefile:
您可以将此行放在您的.profile文件中:
export NODE_PATH="$(npm config get prefix)/lib/node_modules"
export NODE_PATH="$(npm config get prefix)/lib/node_modules"
This will make nodeuse the global path.
这将node使用全局路径。

