node.js:找不到模块“请求" [英] node.js: cannot find module 'request'
问题描述
我安装了请求模块,并收到错误消息:
I installed request module, and getting the error:
module.js:340
throw err;
^
Error: Cannot find module 'request'
我已经阅读了有关此错误的所有文章,并了解到这是因为模块请求未在全球范围内找到,但是我已经尝试了2条建议
i've read all the posts about this error, and understand that this is because module requests is not globally found, but i've already tried the 2 suggestions
npm安装请求-g
npm install request -g
该将其安装在/usr/loca/bin中吗?因为我在那里看不到.
should this install it in /usr/loca/bin ? because i don't see it there.
和
sudo npm链接
sudo npm link
/usr/local/lib/node_modules/request->/Users/soulsonic/dev/sandbox/node_test/request
/usr/local/lib/node_modules/request -> /Users/soulsonic/dev/sandbox/node_test/request
我在每条命令后重新启动终端,但始终收到找不到模块的错误.
i restarted terminal after each command, but keep getting the cannot find module error.
更新
我的初始目录中肯定存在某种冲突,因为"npm install request"没有在node_modules下添加"request"(那里还有10个). 切换到新目录后,它就可以正常工作了.
there must have been some sort of conflict in my initial directory, because "npm install request" was not adding "request" under node_modules (there 10 others in there) .. after switching to a new directory it just worked.
如果我使用-g开关运行它,我确实看到它已安装到/usr/local/lib/node_modules/request.
if i run it with -g switch, i do see it bing installed to /usr/local/lib/node_modules/request.
似乎我只需要更新我的个人资料,即可自动添加以上路径.
it seems that i just need to update my profile so that above path is automatically added.
推荐答案
转到项目目录
mkdir TestProject
cd TestProject
将此目录设为项目的根目录(这将创建一个默认的package.json
文件)
Make this directory a root of your project (this will create a default package.json
file)
npm init --yes
安装所需的npm模块并将其另存为项目依赖项(它将出现在package.json
中)
Install required npm module and save it as a project dependency (it will appear in package.json
)
npm install request --save
使用包示例中的代码在项目目录中创建test.js
文件
Create a test.js
file in project directory with code from package example
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the google web page.
}
});
您的项目目录应如下所示
Your project directory should look like this
TestProject/
- node_modules/
- package.json
- test.js
现在只需在项目目录中运行节点
Now just run node inside your project directory
node test.js
这篇关于node.js:找不到模块“请求"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!