2

Is there a way to set the NODE_PATH env variable after node has started?

if I do this:

async.series([
        function export_NODE_PATH(cb){
          cp.exec('export NODE_PATH=$(npm root -g):$NODE_PATH',cb);
        },...

it won't work, but if I set NODE_PATH before starting node, it will work as expected

export NODE_PATH=$(npm root -g):$NODE_PATH && node index --transpile test

is there a way to set the environment variable in the node.js runtime, without the need to set it at the command line before executing? Is it as simple as setting process.env.NODE_PATH during runtime?

For example, this seems to work:

    cp.exec('echo $(npm root -g)', function (err, stdout, stderr) {
    if (err || String(stdout).match(/error/i) || String(stderr).match(/error/i)) {
        cb(err || stdout || stderr);  // my funky way of handling this
    }
    else {
        process.env.NODE_PATH += stdout;
        cb(null);
     }
    });

but I don't know how kosher that is, and it does not actually seem to work, after further testing.

2 Answers 2

1

One way to achieve this is by creating an .env file and using a npm library called dotenv to load the .env files variables into your process.env automatically. Steps include the following:

Step 1: Create an .env file in your project directory $ touch .env

Step 2: place the following text in your .env file "NODE_ENV=yourvaluehere" (without quotes)

Step 3: Install dotenv $ npm install dotenv --save

Step 3: In the js file you run to start the server, add the following require('dotenv').config();

Viola, you are now setting environment variables in your node process via an env file. Your process.env will have all key value pairs stored in your .env file!

Sign up to request clarification or add additional context in comments.

Comments

1

Setting process.env.NODE_PATH (or any other env var) is perfectly "legal" - in fact that's how libraries such as dotenv and yenv do their magic.

3 Comments

given some testing I have just done, reassigning process.env.NODE_PATH during runtime does not seem to work, I am looking at the source code of the libs you mentioned to figure out how they do it, if you know, however please augment your answer thx!
Make sure you assign it before its being used - not sure if NODE_PATH is special though
I have the same problem as Alexander Mills. In my case NODE_PATH is certainly set to ./ but it does not affect the module resolution, unless it had this value from the very beginning (from CLI)! create-react-app is using this differently then just setting process.env.NODE_PATH on the fly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.