Javascript 从文件中读取并查找特定行

Javascript 从文件中读取并查找特定行,javascript,node.js,file,split,Javascript,Node.js,File,Split,我需要根据某些关键字在设置文件中获取信息(我无法更改格式)。文件如下所示: username=myusername address=156a1355e3486f4 data=function(i){if (i!=0) return true; else return false;} 系统是=\n。值部分中可以有=、空格或其他字符,但不能有换行符。键是唯一的(在“键部分”中,它们可以显示在值中,但对于每个键,\nkey=在文件中只显示一次) 使用shell脚本,我发现我的值如下: usernam

我需要根据某些关键字在设置文件中获取信息(我无法更改格式)。文件如下所示:

username=myusername
address=156a1355e3486f4
data=function(i){if (i!=0) return true; else return false;}
系统是
=
\n
。值部分中可以有
=
、空格或其他字符,但不能有换行符。键是唯一的(在“键部分”中,它们可以显示在值中,但对于每个键,
\nkey=
在文件中只显示一次)

使用shell脚本,我发现我的值如下:

username=`grep ^username file.txt | sed "s/^username=//"`
Grep将返回
username=someusername
,sed将键和
=
替换为空,只留下值

// @text is the text read from the file.
// @key is the key to find its value
function getValueByKey(text, key){
    var regex = new RegExp("^" + key + "=(.*)$", "m");
    var match = regex.exec(text);
    if(match)
        return match[1];
    else
        return null;
}
在node.js中,我想访问文件中的一些数据。例如,我想要地址和数据的值

如何在node.js中执行此操作?在
fs.readFile(file.txt)
之后,我不知道该怎么办。我想我将不得不使用
split
,但是使用
\n
似乎不是最好的选择,也许regex能帮上忙

理想的做法是“找到一个子字符串,以
\nkey=
开头,以第一个
\n
结尾”,然后我可以轻松地拆分以找到值

// @text is the text read from the file.
// @key is the key to find its value
function getValueByKey(text, key){
    var regex = new RegExp("^" + key + "=(.*)$", "m");
    var match = regex.exec(text);
    if(match)
        return match[1];
    else
        return null;
}
示例:

//应使用fs.readFile获取文本。。。
var text=“username=myusername\naddress=156a1355e3486f4\nda=function(i){if(i!=0)返回true;否则返回false;}”;
函数getValueByKey(文本,键){
var regex=new RegExp(“^”+key+”=(.*)$”,“m”);
var match=regex.exec(文本);
如果(匹配)
返回匹配[1];
其他的
返回null;
}
日志(“地址:”,getValueByKey(文本,“地址”);
log(“用户名:”,getValueByKey(文本,“用户名”);

log(“foo(不存在):”,getValueByKey(文本,“foo”)使用
split
reduce
,您可以执行以下操作:

fs.readFile('file.txt', { encoding : 'utf8' }, data => {
  const settings = data
    .split('\n')
    .reduce((obj, line) => {
      const splits = line.split('=');
      const key = splits[0];
      if (splits.length > 1) {
        obj[key] = splits.slice(1).join('=');
      }
      return obj;
    }, {});
  // ...
});

您的设置将作为键/值存储在
设置
对象中。

是否将其解析为对象?那很容易,谢谢!我知道regex是最好的选择。写我的问题帮助我找到了一个解决方案(不像你的那么干净和适应性强),使用
text.match(regex)
,写“理想的东西”部分给了我regex。