我尝试使用命令
安装@hapi/joialok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ sudo npm install @hapi/joi -g
+ @hapi/joi@16.1.7
updated 1 package in 2.833s
我可以在@hapi/joi
看到安装的/usr/local/lib/node_modules
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js/tmp$ npm root -g
/usr/local/lib/node_modules
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js/tmp$ npm list -g @hapi/joi
/usr/local/lib
`-- @hapi/joi@16.1.7
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ tree /usr/local/lib/node_modules/@hapi/joi/ -L 1
/usr/local/lib/node_modules/@hapi/joi/
├── CHANGELOG.md
├── dist
├── lib
├── LICENSE.md
├── node_modules
├── package.json
└── README.md
3 directories, 4 files
但是我无法访问它
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ node
> var Joi = require('@hapi/joi'); // this is not working
{ Error: Cannot find module '@hapi/joi'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18) code: 'MODULE_NOT_FOUND' }
>
>
> var Joi = require('/usr/local/lib/node_modules/@hapi/joi') // This is working
undefined
我的node
和npm
是
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ which node
/usr/bin/node
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ node -v
v10.15.2
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ npm -v
6.11.3
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ echo $NODE_PATH # this shows nothing
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ node
> process['env']['PATH']
'/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
>
为什么我得到Error: Cannot find module '@hapi/joi'
?如何解决这个问题?
答案 0 :(得分:1)
将/usr/local/lib/node_modules
添加到NODE_PATH
使其有效
# Add this line in yuor ~/.bashrc
export NODE_PATH="/usr/local/lib/node_modules:$NODE_PATH"
或
# Add this line in yuor ~/.bashrc
export NODE_PATH="`npm root -g`:$NODE_PATH"
或
// Add this line at top in your node.js script
module.paths.push('/usr/local/lib/node_modules/')
在Ubuntu 20.04上进行了测试,该功能也应在其他Linux distributions上运行。
答案 1 :(得分:0)
您检查过用户文件夹了吗?我在这里node_module
有一个/Users/<username>/node_modules
文件夹。
您可能必须更改$PATH
。
答案 2 :(得分:0)
您应该使用npm init它将生成package.json,然后您可以运行js文件。