mistaecko
mistaecko

Reputation: 2685

How to provide module dependencies for required script in a sibling directory

I am running a node.js script (foo.js) that requires a helper script that is located in a sibling directory.

//foo.js:
var magic = require('../util/magic');

magic.js uses a npm module express. However, the main directory of the 'program' (holding package.json and node_modules) is the folder where foo.js is located.

/program  
  /node_modules  
     /express
     ..
  /foo.js  
  /package.json  
/util  
  /magic.js  

When running the program, the statement require('express') in magic.js fails - the module cannot be found.

Is there a way to make node.js load the express module from the program/node_modules directory?

I would like to avoid any of the following:

Appreciate your help!

Upvotes: 3

Views: 2443

Answers (1)

hexacyanide
hexacyanide

Reputation: 91619

You could supply a relative path instead the module name, because this is how Node.js is going to check for the modules folder if you don't specify a path:

/util/node_modules
/node_modules

Since you know where the module already exists, just do this instead:

var express = require('../program/node_modules/express');

However, you should place any files related to the module within the module itself when developing modules. If you don't, they don't get packaged with the module either when it is published, and you have this inconvenience of not being able to access dependencies specified in the package file.

Upvotes: 3

Related Questions