Node.js unset environment variable

时间:2017-04-10 02:36:10

标签: node.js

How do you unset an environment variable in Node.js?

I've tried:

process.env.MYVAR = undefined

But that doesn't unset it, it appears as follows:

console.log('xx' + process.env.MYVAR + 'xx');

Output is:

xxundefinedxx

I want:

xxxx

How do I make this work?

3 个答案:

答案 0 :(得分:6)

还有另一个不直观的方面:分配环境变量时,Node.js将undefined转换为字符串“ undefined”:

> process.env.MYVAR = undefined
undefined
> typeof process.env.MYVAR
'string'

您可以使用delete解决此问题:

> delete process.env.MYVAR
true
> typeof process.env.MYVAR
'undefined'

使用Node.js 13.5、12.14和10.18进行了测试。

由于这个原因,(process.env.MYVAR || '')无效,因为它的值为('undefined' || '')

答案 1 :(得分:5)

The problem is that:

console.log('xx' + process.env.MYVAR + 'xx');

Is actually incorrect. The value of an undefined property is undefined. process.env.MYVAR = undefined is the same as delete process.env.MYVAR in so far as the value of the property is the same. But properties also have a presence that delete removes, in that the key will not show up in the Array returned by Object.keys.

If you want the empty string, instead you must write:

console.log('xx' + (process.env.MYVAR || '') + 'xx');

答案 2 :(得分:2)

Make sure you understand that undefined !== ""

Use this: process.env.MYVAR = "" if you want an empty string. undefined means there is nothing there. An empty string means there is the text of nothing to make it easy to understand.