Set global environment variable from Node.js

I am trying to set a global environment variable from my node.js. application

Objectives:

  • When restarting APP, the environment variable should still be set
  • When opening a new shell, you should use it.
  • If possible: upon reboot, as 1.
  • It should work on Linux, Mac OS X (and requires an alternative 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 it causes in

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

I have not tested this on Windows, but on Mac OS X (and Linux) the correct bash command is export GLOBALVARNAME=value . For Windows, the correct command should be SET GLOBALVARNAME=value - right?

So, the main question: what happens to manual work export GLOBALVARNAME=foobar ?

+5
source share
3 answers

export not a standalone command, but an inline shell that sets the environment variable for the current shell process and its children that were dug up after it was installed.

You cannot set an environment variable for processes that are not descendants of the current process. And under Linux there is no such variable as a system environment variable.

On Linux, your variable must be set in an init script that launches your application or in unitd. If you want it to be available in interactive user shells, it must be installed in /etc/profile or /etc/profile.d

.

+3
source

As other answers pointed out, traversing and changing an environment variable is basically 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 changes for any new processes, as @Hmlth says.

If you want to change the environment for your current process, this is straightforward:

 process.env.YOUR_VAR = 'your_value'; 
+3
source

Try:

https://www.npmjs.com/package/shelljs

I do not think that a child process can change the parent environment of a process. Therefore, I do not think that child_process can be used.

Code example:

 var shell = require('shelljs'); shell.exec('export ENV_VARIABLE=ABRACADABRA'); 
+2
source

All Articles