node module.paths confusion
Issue: required node modules do not use my global module.paths even though I add the global path to the array in my main.js application.
Example:
mymain.js
//global modules path
module.paths.push('C:\Users\xuser\AppData\Roaming\npm');
// finds ws in global modules path. Works!
wsmain=require('ws')
// Now load a 3rd party module, which also requires('ws')
C = require('cmod.js');
cmod.js
ws=require('ws'); // fails to find global path
q: How do I make sure that module global is also passed on to the require modules. Is there a way to pass it as a parameter or something?
I'm not sure there is a "global" path. The node.js documentation suggests a default require
takes place relative to the file requiring it, and searches for a node_modules
directory up the directory chain. From the docs:
For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then node would look in the following locations, in this order:
- /home/ry/projects/node_modules/bar.js
- /home/ry/node_modules/bar.js
- /home/node_modules/bar.js
- /node_modules/bar.js
It looks like you can use NODE_PATH
env var to give a list of places to look for modules:
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
Based on the documentation, the following might work:
NODE_PATH=/path/to/node_modules/where/ws/lives node mymain.js