node.js: cannot find module 'request'

Sonic Soul picture Sonic Soul · May 10, 2013 · Viewed 170.7k times · Source

I installed request module, and getting the error:

module.js:340
    throw err;
          ^
Error: Cannot find module 'request'

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 install request -g

should this install it in /usr/loca/bin ? because i don't see it there.

and

sudo npm link

/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.

update

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.

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.

Answer

glukki picture glukki · May 10, 2013

Go to directory of your project

mkdir TestProject
cd TestProject

Make this directory a root of your project (this will create a default package.json file)

npm init --yes

Install required npm module and save it as a project dependency (it will appear in package.json)

npm install request --save

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