day0ops
day0ops

Reputation: 7482

Using npm3 within a module unable to get parent node_modules

Not sure if this is a known issue with npm3 but because of the npm3's flat module structure, from within a module, I cant locate node_modules using,

var node_modules = fs.readdirSync('node_modules'); 

Instead I have to use,

var node_modules = fs.readdirSync('../../node_modules');

to traverse up to find it. This obviously doesn't happen with npm2+ since the node_modules are nested within the packages.

Is there a way around this ? I searched every where for a better solution.

Upvotes: 1

Views: 77

Answers (1)

Tomas Kulich
Tomas Kulich

Reputation: 15638

This is probably a bad design. I'm not sure why do you need to locate node_modules manually; if you know that something was installed for sure, use require.resolve() builtin, that locates the package for you. Note you can require.resolve() not only .js files but also package.json of a desired package which is helpful for locating the root of the installed package.

Edit:

If you are trying to use webpack to bundle server code, you can define externals manually:

var nodeModules = {};
fs.readdirSync('node_modules') // this always exists
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  })

and then in webpack config:

externals: nodeModules,

Upvotes: 1

Related Questions