Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access the NODE_ENV environment variable properly, is this a bug with node.js?

I'm accessing the NODE_ENV environment variable to turn on some debug features in a node.js server. It used to work like a charm, but now I'm facing some very weird stuff. Here's what I'm doing:

// check if the env var is OK
console.log(process.env.NODE_ENV);

// WTF???
if (process.env.NODE_ENV == "development") {
    console.log("ok");
}
else {
    console.log("nope");
}

// sanity check
var str = "development";
if (str == "development") {
    console.log("ok");
}
else {
    console.log("nope");
}

And here is what I get:

development
nope
ok

How is that possible? Am I facing a bug in node.js? If not, what am I doing wrong?

EDIT

Following Pointy's comment below, here's what I get if I change my initial log to console.log("[" + process.env.NODE_ENV + "]");:

]development
nope
ok

So, a known issue maybe?

like image 316
Laurent Couvidou Avatar asked Sep 03 '12 17:09

Laurent Couvidou


People also ask

What is NODE_ENV in node JS?

NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).

Can you override NODE_ENV?

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

Do we need to set environment variables for node JS?

You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.

What is .env file in node JS?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables.


1 Answers

Looks like your environment variable has some funny characters, possibly due to the way it's being set outside of Node.js. You could try this:

if (process.env.NODE_ENV.replace(/\W/g, '') == 'development') {
  console.log('ok');
}
like image 99
Pointy Avatar answered Sep 22 '22 23:09

Pointy