I'm trying to implement a test where my code works correctly in different Node.js environments, by changing and testing the value of variable NODE_ENV
.
What I'm stuck with, is trying to understand why the following code:
process.env.NODE_ENV = undefined;
var test = process.env.NODE_ENV || 'empty';
console.log(test);
outputs undefined
instead of empty
.
Is that some JavaScript or Node.js feature that I'm missing here?
Tested under Node.js versions: 0.10.47, 4.6.1 and 6.9.1
As a work-around for this specific case I had to do the following:
delete process.env.NODE_ENV; // now it is undefined
If NODE_ENV is not set explicitly for the environment and accessed using process. env then it will be undefined. It is a bad idea to set NODE_ENV from within an application.
You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.
It's very subtle: According to the documentation:
Assigning a property on process.env will implicitly convert the value to a string.
So you're getting back "undefined"
from process.env.NODE_ENV
, not undefined
. "undefined"
is truthy, so "undefined" || "empty"
is "undefined"
.
You can see that if you modify your script a bit:
'use strict'; process.env.NODE_ENV = undefined; console.log("process.env.NODE_ENV", typeof process.env.NODE_ENV, process.env.NODE_ENV); var test = process.env.NODE_ENV || 'empty'; console.log("test", typeof test, test); console.log("process.env.NODE_ENV", typeof process.env.NODE_ENV, process.env.NODE_ENV);
...which outputs:
process.env.NODE_ENV string undefined test string undefined process.env.NODE_ENV string undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With