I'm looking for a way to basically do what manipulating require.paths used to let you do; edit the paths require will search for modules in from within a running program.
The setup (that I can't change, or workaround for various reasons) is that I have a project containing a main JS file within a child directory, which in turn should be able to just require('module')
, with 'module' being a file inside of another directory off in another specific directory within the project folder.
Unfortunately, moving the folder into say node_modules temporarily isn't a desirable solution (if it would even work?). I've tried editing the NODE_PATH environment variable in two ways:
NODE_PATH='$NODE_PATH:/home/garmur/moduledir'
which works, but is not desirable as an actual solution.process.env.NODE_PATH += '/home/garmur/moduledir';
from within the program, which doesn't seem to have any effect?Any help with this is appreciated. I know using node_modules etc. is the desirable solution here, but my hands are tied as to the project layout on this one.
Maybe you can try to use relative path for module load, It isn't exactly what are you asking for but could be an option if you need to load modules out of "node_modules" directory:
For instance, with this structure:
$APP_DIR/server.js
$APP_DIR/mymodules/handlers.js
$APP_DIR/mymodules/utils.js
$APP_DIR/node_modules/...
Inside server.js you can use:
var h = require('./mymodules/handlers'),
u = require('./mymodules/utils');
And inside handlers.js you could use:
var u = require('./utils')
This is hacky because it uses a 'private' method call, but it works. I'm doing this to make the paths sane in my Mocha tests.
process.env.NODE_PATH += ':src'; //append custom path to NODE_PATH
require('module').Module._initPaths();
Just run that as part of some app startup or bootstrap execution. Then you can just require things relative to src anywhere after that code executes.