Environment variables is a functionality provided by the operating system (e.g. Linux).
You can set then in terminal or shell scripts using:
name=value
Or in Node using:
process.env.name = value;
You can access them in shell using:
echo $name
Or in Node using:
console.log(process.env.name);
The scope of the environment variables is the process when they are defined and the sub-processes that it executes.
For example write a Node program called envtest.js:
console.log('Node program:', process.env.test);
process.env.test = 'new value';
console.log('Node program:', process.env.test);
And a shell script called envtest1.sh:
test=value
echo "Shell script: $test"
node envtest.js
echo "Shell script: $test"
Running sh envtest1.sh wil print:
Shell script: value
Node program: undefined
Node program: new value
Shell script: value
As yu can see the Node program doesn't get the value because it wasn't exported. It can set the value and use the new value but it will not be changed in the shell script.
Now, write a different shell script:
test=value
export test
echo "Shell script: $test"
node envtest.js
echo "Shell script: $test"
This time running sh envtest2.sh will print:
Shell script: value
Node program: value
Node program: new value
Shell script: value
It means that the Node program got the value because it was exported this time, it can still change it and use the new value but it works on its own copy, it is not changed in the original shell script that called this Node program.
Instead of:
test=value
export test
You can write:
export test=value
as a shorthand.
A more complicated example, write envtest3.sh:
export test=value
echo "Shell script: $test"
node envtest.js
echo "Shell script: $test"
test=value2 node envtest.js
echo "Shell script: $test"
This time it will print:
Shell script: value
Node program: value
Node program: new value
Shell script: value
Node program: value2
Node program: new value
Shell script: value
Which shows that running test=value2 node envtest.js sets the value of test variable to value2 but only to this invocation of the Node program - the value in the rest of the shell script is still value as it was before.
Those are the 3 kinds of scope of environemnt variables - normally a variable in a shell script is not exported and the programs that you run can't see it. When it is exported then the programs that you run can see it and can modify it but they work on their own copy and it isn't changed in the shell script.
When you run name=value command then the environment variable will be set just for that command but the old value will remain in the rest of the script.
Those are the basics of environment variables and how you can use them in Node.