Set global environment variable out of Node.js

user3984802 picture user3984802 · Sep 11, 2015 · Viewed 9.7k times · Source

I am trying to set a global environment variable out of my node.js app.

The goals are:

  1. When restarting the APP, the environment variable should still be set
  2. When opening a new shell, it should be usable
  3. If possible: When rebooting, same as 1.
  4. It should work on Linux, Mac OS X (and needs an alternate SET command for windows)

Here is what I did:

var setEnv = require('child_process')
        .spawn('export GLOBALVARNAME='+my.value,{
          stdio: 'inherit',
          env: process.env
        });

But this causes in

{ [Error: spawn export GLOBALVARNAME=foobar ENOENT]
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn export GLOBALVARNAME=foobar',
  path: 'export GLOBALVARNAME=foobar',
  spawnargs: [] }

I didn't test this on Windows, but on Mac OS X (and Linux) the right command on bash is export GLOBALVARNAME=value. For Windows the right command should be SET GLOBALVARNAME=value - isn't it ?

So the main question is: Whats going wrong with the manual working export GLOBALVARNAME=foobar ?

Answer

chicks picture chicks · Sep 11, 2015

As other answers have pointed out, shelling out and changing an environment variable is basically a NO-OP. Either you want to change the environment for your current process and its children or you want to change it for new processes. Editing /etc/profile will make the change for any new processes as @Hmlth says.

If you want to change the environment for your current process this is straight forward:

process.env.YOUR_VAR = 'your_value';