Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an environment variable in javascript

How can I set an environment variable in WSH jscript file that calls another program? Here's the reduced test case:

envtest.js
----------
var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST_ENV_VAR") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);    

envtest.bat
-----------
set
pause

I expect to see TEST_ ENV _VAR in the list of variables, but it's not there. What's wrong?

edit:

If someone can produce a working code sample, I'll mark that as the correct answer. :)

like image 545
John Smith Avatar asked Apr 20 '09 14:04

John Smith


People also ask

What is an environment variable in JavaScript?

Environment variables store variables, as the name implies. The values or things that get assigned to these variables could be API keys that you need to perform certain requests or operations. To create an environment variable, all you need to do is create a new file called .

Can JavaScript access environment variables?

All values assigned to environment variables are represented as strings when they are accessed in JavaScript code. That means a variable assigned as MY_VARIABLE=true will have the value of true be the string 'true' in JavaScript.


2 Answers

The problem is not in your code, but it is in execution of the process. The complete system variables are assigned to the process which is executed. so, your child process also had the same set of variables.

Your code-sample works good. It adds the variable to the SYSTEM environment.

So, you need to set the variable not only for your system but also for your process.

Here's the code.

var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST1") = "TEST_VALUE";
var oSysEnv = oShell.Environment("PROCESS");
oSysEnv("TEST1") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);  

Once you created the system variable.

It will assign the newly created variable for the current process. So, your child process can get that variable while the "SET" command executed.

Sorry for my bad-english.

like image 147
Srinivasan__ Avatar answered Oct 22 '22 13:10

Srinivasan__


There are 4 "collections" (System, User, Volatile, and Process) you probably want Process if you just need a child process to see the variable

like image 38
Anders Avatar answered Oct 22 '22 14:10

Anders