[Front-end Js] How to read system environment variables (user variables/system variables) in Js/Node.js in the simplest version

Problem Description

The project needs to read system environment variables through JS. You can read user variables/system variables in the system environment variables.


solution:

I’ve seen a lot of very complicated methods, but in fact, just one line of code is enough.

var Key = process.env.系统变量名称;
console.log(Key)

detailed:

Create a new system variable TEST1
Please add image description

Please add image description

Create a new js file test.js


var Key = process.env.TEST1; 

console.log(Key)

Just execute it in the terminal
Please add image description

But there is a small problem that needs to be noted.
After changing the system variables, the terminal needs to be restarted and then executed to read the variables before they can be changed.
If you use VSCODE, you need to restart VSCODE so that the variables read can be changed.


Replenish:

If there are more complex requirements. You can take a look at this npm library. it is also fine.
https://snyk.io/advisor/npm-package/@humanwhocodes/env

Guess you like

Origin blog.csdn.net/anjue1997/article/details/128656159