referencing node modules from a local folder

Problem

Due to proxy restrictions on my office system, for installation of node and its modules I depended on a outside PC. I have node.exe and npm.cmd in my external system and I was able to download modules there

npm install express

I copied the node_modules folder from my external PC and placed it in my node installed path in my office PC, but still I was not able to do

require ('express')

It says module express not found.* So then I thought node is not considering this module as installed so I copied the module folder near my project and in one of my js file I introduced a path variable.

var path = 'D:/sw/nodejs/'; // here i copied the express folder for the time being var express = require(path+'express'), app = express.createServer();

Here while running I get module 'connect' not found.

Where should I place these dependent modules, to have them work correctly and can't we install modules of node by pasting them in node_modules ?

Problem courtesy of: sij

Solution

You have to set NODE_PATH variable in your environment

set NODE_PATH=D:/sw/nodejs/node_modules

Then you can use all modules inside D:/sw/nodejs/node_modules. express requires connect module which it cannot find with require('connect'), unlike express which you call by require(path+'express').

You can also specify multiple paths in NODE_PATH delimited by ';'

set NODE_PATH=C:/path/1;C:/path/2;

It would be better to set one than type it every time on console. Go to :
My Computer > Right-click > Properties > Advanced System Settings > Environment Variables > New
and set the variable NODE_PATH there. You will have to restart to see the changes.

Solution courtesy of: user568109

Discussion

Either:

  • Put the downloaded packages into a node_modules folders on the root (from where you call node) of you project / source code.
  • Set up a proxy for npm. (Example)
Discussion courtesy of: TheHippo

This recipe can be found in it's original form on Stack Over Flow.