I'm trying to read an .env file that Foreman is using to read env variables that you might want to have when starting the node server.
I'm using:
var path = require("path"),
_ = require("underscore"),
fs = require("fs"),
variables = fs.readFileSync(path.resolve(__dirname, ".env"), "utf8");
At this point I have a string containing something like this:
NODE_ENV=development
PORT=8080
I would like to convert that string into an object so I can read it like this:
{
NODE_ENV: "development",
PORT: 8080
}
I'm not sure how I could do it. I was thinking of Regex but I have no clue how to read line by line. Or how about the type of the variable ? Can I detect if it's a string or number ( I was just thinking to see if there are numbers only it means it's a number ? ) ?
String.replace is a primary means for simple parsing:
var env = {}
variables.replace(/(\w+)=(.+)/g, function($0, $1, $2) { env[$1] = $2 })
To convert numeric values like 8080 to Numbers,
variables.replace(/(\w+)=((\d+)|.+)/g, function($0, $1, $2, $3) {
env[$1] = $3 ? Number($3) : $2;
});