简体   繁体   English

使用node.js从文件读取环境变量

[英]Reading environment variables from file with node.js

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. 我在文件中有许多bash / shell变量,我想将它们读入node.js脚本(或者我猜为javascript)来评估它们并设置javascript变量。

eg the file contains: 例如,文件包含:

gateway_ip=192.168.1.1 gateway_ip = 192.168.1.1

mask=255.255.255.0 遮罩= 255.255.255.0

port=8080 端口= 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. 并且将行作为文本吐出来,但是我似乎无法制作javascript变量。 The error is: 错误是:

undefined:1 default_gateway=192.168.1.1 未定义:1 default_gateway = 192.168.1.1

Is there something obvious I've missed here? 我在这里错过了什么明显的东西吗?

What you're doing here is eval('gateway_ip=192.168.1.1') . 您在这里所做的是eval('gateway_ip=192.168.1.1')

192.168.1.1 is not valid javascript. 192.168.1.1无效的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. 您可以使用global而不是options来在全局范围内设置这些变量。

This is not very JavaScript-ish. 这不是JavaScript式的。 An easier way to do it is to use JSON for your config file. 一种更简单的方法是对配置文件使用JSON。 For example, use this config.json : 例如,使用以下config.json

{
    "gateway_ip": "192.168.1.1",
    "mask": "255.255.255.0",
    "port": "8080"
}

Then you can simply require it: 然后,您可以简单地require它:

var config = require('./config.json');
console.log(config);

An additional bonus is that this will also catch formatting errors in the JSON file. 另一个好处是,这还将捕获JSON文件中的格式错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM