I can not read the environment variable in my Node.js application

I am on Ubuntu 12.04 and I am only learning environment variables. I am trying to read a user variable from my application, but it always displays as undefined . Here is the code for my test application:

 // app.js console.log('Value: ' + process.env.NODE_ENV); 

If I execute the following commands, you will see that the variable has a value:

 $ NODE_ENV=production $ echo $NODE_ENV production 

I can echo $NODE_ENV all day and it will continue to show me "production", but when I execute process.env.NODE_ENV in my Node application, it always displays "undefined".

 $ node app.js Value: undefined 

Here's the weird part, though, if I show another environment variable that, as I know, already exists, say process.env.PATH , then it will work.

 $ node app.js Value: /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games 

Another oddity is that the printenv list command does not contain my custom variable NODE_ENV despite the fact that echo $NODE_ENV shows me the correct value. printenv NODE_ENV does not show anything, but printenv PATH shows the correct value in the same way as when I accessed PATH in my node application.

+11
bash terminal ubuntu environment-variables
source share
4 answers

You need to export shell variables in order to make them available to processes that you run in your shell.

Compare the output of this command:

 FOO=bar; bash -c 'echo $FOO' 

with the output of this:

 export FOO=bar; bash -c 'echo $FOO' 
+22
source share

I found my way here out of something stupid.

I just added new exported variables, but my node process still did not see them. Then I realized that this was not enough to restart the node process - I had to open a new terminal (for example, a bash instance)). As soon as I did this, it worked fine :)

+6
source share

You might want to use the library to control the configuration of the application.

For example, nconf helps manage configuration through

  • argumets command line
  • Environment Variables
  • files
  • etc..

And looking at the source is a good way to find out https://github.com/flatiron/nconf

0
source share

Restart your bash (source ~ / .bashrc). This will take into account your system environment.

0
source share

All Articles