Node.js unset environment variable
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');
There is another unintuitive aspect to it: Node.js converts undefined
to the string "undefined" when assigning an environment variable:
> process.env.MYVAR = undefined
undefined
> typeof process.env.MYVAR
'string'
You can work around this using delete
:
> delete process.env.MYVAR
true
> typeof process.env.MYVAR
'undefined'
Tested with Node.js 10.18, 12.14, 13.5 and 16.15.
For this reason (process.env.MYVAR || '')
does not help, as it evaluates to ('undefined' || '')
.