Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process.env variables are undefined even after export

I'm writing a Node.js express app and want to use environment variables for setting the port on which the server should run.

However, I can't seem to get process.env.PORT to read my PORT environment variable.

I've defined the PORT environment variable using export like so: export PORT=1234 I've also added this line to the ~/.bash_profile file, but process.env.PORT remains undefined.

When I run echo $PORT in terminal, it displays the value (1234) correctly.

I'm running Node V0.12.7 and OSX El Capitan 10.11.1 and really can't find any extra clues on what might be causing this.

Thanks!

EDIT: Here's the code executed before trying to assign process.env.port to the port variable

var app = require('../app');
var proxy = require("../proxy");
var http = require('http');
var nconf = require('nconf');
nconf.file(__dirname + "/appConf.json");
var appSettings = require('../appSettings');

var port = normalizePort(process.env.PORT || 8080);
like image 721
Niekert Avatar asked Sep 26 '22 04:09

Niekert


1 Answers

There's a great npm package called dotenv, that will auto-load any environment variables from a file called .env in the same directory as your nodeJS application. This could give you a differentPORT variable project to project, instead of globally defining one PORT across all terminals.

As far as everything else, it sounds like PORT should be there (you even said it was properly echo-ing from command line). Did you run node out of the same terminal as you used echo? The only other issues I can think of are if you didn't restart the terminal you're running your server out of after you modified your ~/.bash_profile, or maybe a simple typo somewhere.

I would have posted this as a comment, but I don't have the score for it.

like image 135
Austin Ezell Avatar answered Oct 11 '22 16:10

Austin Ezell