4

I have an npm script like this that executes two node files:

package.json

{
  "scripts": {
    "my-target": "node setup.js && node run.js"
  }
}

Ideally, I can set environment variables in setup.js that can then be accessed in run.js.

setup.js

process.env.HELLO_WORLD=1

run.js

// Ideally prints `1`, instead prints undefined.
console.log(process.env.HELLO_WORLD);

Is something like this possible? Ideally the result of setting the environment variables in setup.js would be persistent, so that if I run

$ echo $HELLO_WORLD

from bash, that reference would still be there.

3
  • 1
    Why would you not just run HELLO_WORLD=1 node setup.js && node run.js? Commented Sep 23, 2021 at 1:20
  • 3
    because in reality the situation is more complex, I simplified it here to demonstrate what is needed. That is, I do not know what the value of the environment variable should be - it is dynamically determined by the setup script. Commented Sep 23, 2021 at 2:26
  • What you're attempting is impossible. Env vars are private to each process. When a process starts it inherits env vars from its parent. A process cannot modify the env of a different process. Commented Sep 23, 2021 at 16:42

1 Answer 1

1

You can set env vars when you run the main program:

HELLO_WORLD=hello npm run my-target

package.json:

  "scripts": {
    "my-target": "node setup.js && node run.js"
  },

setup.js:

console.info('setup', process.env.HELLO_WORLD);

run.js:

console.info('run', process.env.HELLO_WORLD);

Output will be

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

3 Comments

This is not what I am looking for. I do not actually know what the value of the environment variable should be - it is dynamically determined by the setup script.
This is not a really standard way of doing things, is there a reason the two scripts need to be separate like this?
Ideally, you would run setup.js which would determine your dynamic values/set env vars and you then require/import run.js and execute its functions as needed.

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.