Env vars, process and globals in NodeJS

Setting and reading custom env

You can define custom env variables in two ways:

Option 1: In one line before running node:

> VAL1=10 VAL2=20 node myfiles.js

Option 2: By exporting them one by one:

> export VAL1=100
> export VAL2=200
> node myfiles.js

After that you can read the env variables in your script:

console.log(process.env.VAL1);
console.log(process.env.VAL2);

By the way, process needs no import/require.

OS user environment variables

process.env contains a copy of the user environment (equivalent to env in Linux and set in Windows).

process.env.USER = 'you' // does not modify ENV.USER

process.argv contains all arguments that were used when a node script was called.

node -p "process.argv" x 42

will output an array containing the path to node executable as first element, the script name (if any) as second element and then any passed arguments, in this case 'x' and '42'. Note that they are all of type string, even if you enter a number.

Other property on process are stdout, stderr and stdin which let node communicate with your OS console. In fact console.log("Hi") is the same as process.stdout.write("Hi\n");.

std-properties are streams and as such you can listen to their events like:

process.stdin.on('readable', () => {
  const chunk = process.stdin.read();
  if(chunk !== null) {
    process.stdout.write(chunk);
  }
});

// or
// process.stdin.pipe(process.stdout);

Another example:

setTimeout(() => process.exit(), 2000);

process.on('exit', () => {
  // do one final synchronous operation before node terminates
  console.log('Bye!');
});

process.once('uncaughtException', (err) => {
  // do cleanup but you should exit anyway
  // someCleanup()
  process.exit(1);
});

Note, that we are using on and once here.

Global values

You should avoid changing or creating them, but they exist also in node. In Browsers it is window, in Node it is global. setTimeout(…) is actually global.setTimeout(…).

You could (but should not) add your own global variables:

global.myGlobalVar = 42;

And then invoke it in any module:

console.log(myGlobalVar);

Let’s list the first level of the global variable:

console.dir(global, {depth: 0});

About Author

Mathias Bothe To my job profile

I am Mathias from Heidelberg, Germany. I am a passionate IT freelancer with 15+ years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I create Bosycom and initiated several software projects.