Environment variables are noting to do with your node application! The only role of the process.env is to provide the system environment variables to your application. In case you need to add environment variables, you should add it in your docker/vm/vagrant configuration file not in the start script of your application.
If you are going to pass an argument to node instance, the best and only way is to use node process.argv instead of rocess.env.
The only case you need to use process.env is that your cloud provider enforces some configurations with which your app must comply, even in that case, they set the environment variables not you.
Here is how to pass arguments to your app. You've probably known already.
node app.js port=5000 profile=admin
Then,
/**
* Get the passed node argument by key.
* @param key of node argument
* @returns {string}
*/
export function getArg(key: string): string {
return process.argv
.map(e => e.split('=')) // [ [a b] , [c d]]
.filter(e => e.length == 2) //[[a b], [c d]]
.map(e => ({ [e[0]]: e[1] })) // [{a:b}, {c:d}]
.reduce((p, c) => ({ ...p, ...c }))[key]
}
Example Scenario:
- App has multiple profiles "admin" , "public", and "subscriber".
- App runs only upon user request, (for example, admin wants to run the app, then you run the app on admin profile)
package.json
{
"start:admin":"node app.js profile=admin port=5000",
"start:public":"node app.js profile=public port=5001",
"start:subscriber":"node app.js profile=subscriber port=5002",
}
Just tried to explain the nuance between process.env and process.argv.
Take it Easy!