配置 process.env 对象的 Node.js 脚本。

huangapple go评论111阅读模式
英文:

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 -&quot;new variable&quot;
// index.js

console.log(&#39;process.argv:&#39;, process.argv);

/*
process.argv: [
      &#39;/Users/user/.nvm/versions/node/v16.14.0/bin/node&#39;,
      &#39;/Users/user/.nvm/versions/node/v16.14.0/bin/jest&#39;,
      &#39;__tests__/api.test.js&#39;,
      &#39;-new variable&#39; // &lt;- 
    ]
*/

This will work with both node and jest scripts

source: https://www.digitalocean.com/community/tutorials/nodejs-command-line-arguments-node-scripts

huangapple
  • 本文由 发表于 2023年5月7日 11:16:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定