NodeJS: Environment variables and process module

Setting env to debug modules

Setting NODE_DEBUG="http" will output debug info to the console for Node’s http module. Use a comma seperated list to debug more modules at the same time. You can adjust NODE_PATH to tell Node where to look for modules.

Setting and reading custom env

You can define custom env variables in two ways:

Firstly, in one line before running node:

> VAL1=10 VAL2=20 node myfiles.js

Or secondly 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 Contact me

I am Mathias, born 38 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 14 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.