node.js modules path

2019-01-30 14:47发布

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.

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.

标签: node.js npm
5条回答
孤傲高冷的网名
2楼-- · 2019-01-30 15:10

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

$ echo 'export NODE_PATH="'$(npm root -g)'"' >> ~/.bash_profile && . ~/.bash_profile
查看更多
混吃等死
3楼-- · 2019-01-30 15:13

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

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

PS: Tested on Windows 8.1

查看更多
\"骚年 ilove
4楼-- · 2019-01-30 15:14

You can add the following to ~/.bash_profile:

export NODE_PATH=/usr/lib/node_modules:$NODE_PATH
查看更多
Ridiculous、
5楼-- · 2019-01-30 15:14

For people with ZSH installed:

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

查看更多
甜甜的少女心
6楼-- · 2019-01-30 15:23

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

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

var mysql = require('/usr/etc/node_modules/mysql');
查看更多
登录 后发表回答