Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting NODE_PATH from within NodeJS application

Tags:

node.js

We have a node project that does not require our own submodules from a relative path, but instead needs the NODE_PATH environment variable be set to lib to find all submodules.

I wanted to handle this standard case within the program source code but it seems like it is impossible by now.

I found several solutions which all do not work as expected.

module.paths.push("./lib");

Was suggested in another stackoverflow article but this causes an error message in the newer Node versions and refers the developer to using NODE_PATH.

Instead I tried to do the following as the very first line of my program.

process.env['NODE_PATH']="./lib";

This does not cause an error message but it does not work either. I think that this variable is read on the application start and not read lateron when requiering stuff.

like image 509
MaxM Avatar asked Jul 25 '14 10:07

MaxM


1 Answers

All information you can find out from the source: module.js

... NODE_PATH error is thrown only when accessing via require.paths.

Search for _nodeModulePaths function: Module instance has generic Array object paths, with all lookup paths in it.

module.paths.unshift('./foo-baz');
var x = require('some-lib-name');
console.log(x);

So now, if you have the required module under ./foo-baz/some-lib-name/ it would be properly picked up.

What node version and what system you have?

like image 192
tenbits Avatar answered Nov 09 '22 14:11

tenbits