Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set NODE_ENV to undefined?

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


update

As a work-around for this specific case I had to do the following:

delete process.env.NODE_ENV; // now it is undefined
like image 963
vitaly-t Avatar asked Oct 23 '16 14:10

vitaly-t


People also ask

Can process env be 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.

Can you override NODE_ENV?

You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.


1 Answers

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 
like image 100
T.J. Crowder Avatar answered Sep 20 '22 10:09

T.J. Crowder