一个JavaScript脚本正在调试和/或运行通过VSCode使用Node.js知道哪个启动配置是用来启动它?
类似:
var myLaunchConfigName = somehow_get_my_config()
console.log( 'I was launched by ' + myLaunchConfigName )
我一直在寻找,但找不到方法。
根据rioV8的建议,以下是完整的答案:
-
安装包"本地:
npm install dotenv
-
设置环境变量值的位置。
-
在VSCode启动配置。Json或settings.json):
{ "name": "node launch $ file", "type": "node", "request": "launch", "program": "${file}", "env": {"LAUNCH_CONFIG": "node launch $ file"} //<--ENVIRONMENT VARIABLE }
-
和/或创建一个名为".env"在项目根目录中添加值:
FROM_FILE="value from file"
这是。env的默认位置,但它可以放在其他地方。
-
和/或在命令行中将它们传递给node,如下所示。
- "require"包裹被压坏了。一些替代方案是:
-
在脚本开头添加以下行:
require('dotenv').config()
-
和/或者我们可以在命令行中使用选项"- & ":
node -r dotenv/config script.js
-
。Env可以位于另一个目录:
node -r dotenv/config script.js dotenv_config_path=/custom-path-to-env/.env
-
在命令行中传递变量:
CLINE="cline" node script.js CLINE="cline" node -r dotenv/config script.js dotenv_config_path=/custom-path-to-env/.env
5。最后,在脚本中,我们可以使用process.env读取它们的值。VARIABLE_NAME,即:
var foo = process.env.LAUNCH_CONFIG
require('dotenv').config()
function notDefined(value) {
return ((value === undefined) || (value === null))
}
function checkVars(varName, value) {
if (varName === 'LAUNCH_CONFIG')
console.log( notDefined(value) ?
`I came from command line, or variable ${varName} is missing.` :
`I came from VScode with configuration named '${value}'.` )
else
console.log( notDefined(value) ?
`variable ${varName} is missing.` :
`variable ${varName} = "${value}"` )
}
console.log('')
checkVars('LAUNCH_CONFIG', process.env.LAUNCH_CONFIG)
checkVars('FROM_FILE', process.env.FROM_FILE)
checkVars('CLINE', process.env.CLINE)
结果:
从Visual Studio代码启动:
I came from VScode with configuration named 'node launch $ file'.
variable FROM_FILE is missing.
variable CLINE is missing.
默认.env文件中的变量:
node envar.js
I came from command line, or variable LAUNCH_CONFIG is missing.
variable FROM_FILE = "from default .env"
variable CLINE is missing.
命令行和其他文件中的变量:
CLINE="cline" node -r dotenv/config envar.js dotenv_config_path=/C/DEVELOP/JS/another_file
I came from command line, or variable LAUNCH_CONFIG is missing.
variable FROM_FILE = "from another file"
variable CLINE = "cline"
来自其他目录的变量:
node -r dotenv/config envar.js dotenv_config_path=/C/DEVELOP/JS/ANOTHER_DIR/.env
I came from command line, or variable LAUNCH_CONFIG is missing.
variable FROM_FILE = "from another directory"
variable CLINE is missing.