node.js 模块路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13465829/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:41:01  来源:igfitidea点击:

node.js modules path

node.jsnpm

提问by Mario

I realised that when I did a global installation of a node.js module (with the -g flag) node couldn't use that module unless I wrote the entire path.

我意识到,当我对 node.js 模块(带有 -g 标志)进行全局安装时,除非我写了整个路径,否则节点无法使用该模块。

I mean, this doesn't work if the module has been globally installed:

我的意思是,如果模块已全局安装,这将不起作用:

cheerio = require('cheerio'),

I have to write that:

我必须这样写:

cheerio = require('/usr/lib/node_modules/cheerio'),

How can I say to node that it has to look for the modules in the right path?

我怎么能告诉节点它必须在正确的路径中寻找模块?

Thank you.

谢谢你。

回答by inki

In general, I would suggest letting npm give you the path and set that as mentioned above:

一般来说,我建议让 npm 为您提供路径并按照上述方式进行设置:

$ echo 'export NODE_PATH="'$(npm root -g)'"' >> ~/.bash_profile && . ~/.bash_profile

回答by Vikram Tiwari

For those in Windows platform add this to your PATH in system variables:

对于 Windows 平台上的用户,将其添加到系统变量中的 PATH 中:

C:\Users\<username>\AppData\Roaming\npm

PS: Tested on Windows 8.1

PS:在 Windows 8.1 上测试

回答by Errol Fitzgerald

You can add the following to ~/.bash_profile:

您可以将以下内容添加到 ~/.bash_profile:

export NODE_PATH=/usr/lib/node_modules:$NODE_PATH

回答by Daniel Gerber

For people with ZSH installed:

对于安装了 ZSH 的人:

echo 'export NODE_PATH="'$(npm root -g)'"' >> ~/.zshrc && . ~/.zshrc

echo 'export NODE_PATH="'$(npm root -g)'"' >> ~/.zshrc && . ~/.zshrc

回答by allen yang

The better way is to set the modules path in your js file.

更好的方法是在 js 文件中设置模块路径。

In my case, i ran npm install mysqlat /usr/etc, mysql will shown in "/usr/etc/node_modules", so this is the right path:

就我而言,我npm install mysql在 /usr/etc 运行,mysql 将显示在“/usr/etc/node_modules”中,所以这是正确的路径:

var mysql = require('/usr/etc/node_modules/mysql');