Reputation:
I am trying to set a global environment variable out of my node.js app.
The goals are:
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
?
Upvotes: 14
Views: 20176
Reputation: 2463
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';
Upvotes: 4
Reputation: 666
Give this a try:
https://www.npmjs.com/package/shelljs
I don't think it is possible for a child process to change the parent's process environment. So I don't really think it is possible to use child_process
.
Sample code:
var shell = require('shelljs');
shell.exec('export ENV_VARIABLE=ABRACADABRA');
Upvotes: 2
Reputation: 31
export
is not a standalone command but a shell builtin that sets the environment variable for the current shell process and its children forked after it is set.
You can't set an environment variable for processes that are not descendants of the current process. And under Linux, there is no such thing as system environment variable.
Under Linux, your variable should be set in the init script that spawns your app or in the systemd unit. If you want it to be available in interactive user shells, it should be set in /etc/profile
or /etc/profile.d
.
Upvotes: 3