英文:
Configuring process.env object with a Nodejs script
问题
Yes, it is possible to add an environment variable using a Nodejs CLI script to the process.env
object and have it available in a JavaScript environment.
In Chinese:
可以使用Nodejs CLI脚本将环境变量添加到process.env
对象中,并在JavaScript环境中使用。
Regarding your code example:
node index.js --env --NEW_VARIABLE=1
// index.js
console.log('process.env["NEW_VARIABLE"]:', process.env["NEW_VARIABLE"]);
// logs 1
If it is, can it be done with strings, and how?
In Chinese:
如果可以的话,是否可以使用字符串实现,具体如何实现呢?
One more thing, assuming all of this can be done...can it be done with a Jest script as well?
In Chinese:
还有一件事,假设所有这些都可以实现...是否也可以在Jest脚本中实现?
英文:
Is it possible to add an environment variable using a Nodejs CLI script to the process.env object and have it available in a javascript environment?
Something like this
node index.js --env --NEW_VARIABLE=1
// index.js
console.log('process.env["NEW_VARIABLE"]:', process.env["NEW_VARIABLE"]);
// logs 1
If it is, can it be done with strings, and how?
One more thing, assuming all of this can be done...can it be done with a Jest script as well?
答案1
得分: 0
有一个叫做 "argv" 的属性存在于进程对象上。它是一个字符串数组。你可以通过在 CLI 脚本的末尾添加它们作为标志来将参数推送到 argv 数组中。
例如:
node index.js -"new variable"
// index.js
console.log('process.argv:', process.argv);
/*
process.argv: [
'/Users/user/.nvm/versions/node/v16.14.0/bin/node',
'/Users/user/.nvm/versions/node/v16.14.0/bin/jest',
'__tests__/api.test.js',
'-new variable' // <-
]
*/
这将适用于 Node 和 Jest 脚本。
来源:https://www.digitalocean.com/community/tutorials/nodejs-command-line-arguments-node-scripts
英文:
There's another property on the process object called "argv". It's an array of strings. You can push arguments into the argv array by added them as flags at the end of a CLI script.
ex:
node index.js -"new variable"
// index.js
console.log('process.argv:', process.argv);
/*
process.argv: [
'/Users/user/.nvm/versions/node/v16.14.0/bin/node',
'/Users/user/.nvm/versions/node/v16.14.0/bin/jest',
'__tests__/api.test.js',
'-new variable' // <-
]
*/
This will work with both node and jest scripts
source: https://www.digitalocean.com/community/tutorials/nodejs-command-line-arguments-node-scripts
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论