Matt Andrews Matt Andrews - 3 months ago 11
Node.js Question

Loading a node_module from above the current directory

I'm building an app with multiple sub-apps. The file structure is like this:

├── app1
│   ├── app.js
│   ├── node_modules
│   └── package.json
├── shared
│   └── foo.js


In
app.js
, I'm loading
foo.js
like this:

require('../shared/foo');


And in
foo.js
I try to use an
npm
module,
body-parser
, like this:

var bodyParser = require('body-parser');


This thorws a "cannot find module error" –
body-parser
is installed in the
app1/node_modules
directory, but
foo.js
is obviously looking in its own directory and not finding it.

Is there a way to tell a
require()
call to use the working directory of the file it's called from rather than its own directory? Or do I need to have a second
package.json
inside
/shared
to allow for this behaviour?

Answer

I ended up using an approach found via this Gist:

In foo.js I changed my require() calls to look like this:

var bodyParser = require(__base + 'body-parser');

And in app.js (which loads foo.js), I added this to the top:

global.__base = __dirname + '/node_modules/';

It's not beautiful, but it works.