Question

well I'd like to add an environmental varible during the execution of a js file using node.js.

Something like: process.env['VARIABLE'] = 'value';

I'm using the terminal to run the js file using a module, I can set the variable and then use it in during the js file execution, but I'd like to set the variable using "process.env", and then when the execution ends, I'd like to use it in the terminal, or in another js process as well.

I know that it's possible using the child_process.exec, and use SET (Windows) or EXPORT (Mac & Linux), but just asking how it can be possible it can be possible, or using which design or process to add it, just using "process.env".

Thanks in advance, folks.

Was it helpful?

Solution

The unix permissions model will not allow a child process (your node.js app) to change the environment of its parent process (the shell running inside your terminal). Same applies to current working directory, effective uid, effective gid, and several other per-process parameters. AFAIK there's no direct way to do what you are asking. You could do things like print the command to set it to stdout so the user can easily copy/paste that shell command into their terminal, but your best bet is to explain the broader problem you are trying to solve in a separate question and let folks tell you viable ways to get that done as opposed to trying to change the parent process's environment.

One possible workaround would be something is simple as running your node program from the terminal like this:

export SOME_ENV_VAR="$(node app.js)"

and have app.js just print the desired value via process.stdout.write.

Second hack would be a wrapper shell script along these lines:

app.sh

#!/bin/bash
echo app.sh running with SOME_ENV_VAR=${SOME_ENV_VAR}
echo "app.sh running app.js"
export SOME_ENV_VAR="$(node app.js)"
exec /bin/bash

app.js

console.log("Some Value at " + Date());

Running this in an interactive shell in your terminal

echo $SOME_ENV_VAR

exec ./app.sh
app.sh running with SOME_ENV_VAR=
app.sh running app.js

echo $SOME_ENV_VAR 
Some Value at Thu Mar 27 2014 08:13:01 GMT-0600 (MDT)

Maybe these will give you some ideas to work with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top