0

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?

1
  • you can write config in JSON file, and simply require as Object Commented Dec 19, 2015 at 23:22

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

good answer. 2 minor suggestions: 1. trim() the line and both sides. 2. replace parts[1] with parts.slice(1).join("=") to not throw away parts of a value with an = in it
Thanks, I will use this. (I was hoping there was a simple one-liner though).
1

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.

1 Comment

Thanks, yes I know, the reason it is done like this is because it is used to configure the network settings on a Raspberry Pi upon boot. The options are presented as defaults as last used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.