I have a number of bash/shell variables in a file, I would like to read them into a node.js script (or javascript I guess) to eval them and set javascript variables.
e.g. the file contains:
gateway_ip=192.168.1.1
mask=255.255.255.0
port=8080
I've tried the following:
function readConfigFile() {
var filename="/home/pi/.data-test";
fs.readFile(filename, 'utf8', function(err, data) {
var lines = data.split('\n');
for(var i = 0; i < lines.length-1; i++) {
console.log(lines[i]);
eval(lines[i]);
console.log(gateway_ip);
}
});
}
and it spits out the lines as text, but I doesn't seem to be able to make the javascript variable. The error is:
undefined:1 default_gateway=192.168.1.1
Is there something obvious I've missed here?
2 Answers 2
What you're doing here is eval('gateway_ip=192.168.1.1').
192.168.1.1 is not valid javascript. It should have quotation marks. Try this instead:
var lines = data.split('\n');
var options = {};
for(var i = 0; i < lines.length-1; i++) {
var parts = lines[i].split('=');
options[parts[0].trim()] = parts.slice(1).join('=').trim();
}
// You now have everything in options.
You can use global instead of options to set those variables on the global scope.
This is not very JavaScript-ish. An easier way to do it is to use JSON for your config file. For example, use this config.json:
{
"gateway_ip": "192.168.1.1",
"mask": "255.255.255.0",
"port": "8080"
}
Then you can simply require it:
var config = require('./config.json');
console.log(config);
An additional bonus is that this will also catch formatting errors in the JSON file.
requireas Object