从文件中读取并find特定的行
我需要根据某些关键字在设置文件(我无法更改格式)中获取信息。 该文件是这样的:
username=myusername address=156a1355e3486f4 data=function(i){if (i!=0) return true; else return false;}
系统是<key>
=
<value>
\n
。 值部分可以有=
,空格或其他字符,但不能换行。 密钥是唯一的(在“关键部分”中,它们可以出现在值中,但是\nkey=
在每个密钥的文件中只出现一次)。
用一个shell脚本,我发现我的值是这样的:
username=`grep ^username file.txt | sed "s/^username=//"`
grep将会返回username=someusername
,sedreplacekey和=
,只剩下值。
在node.js中,我想访问文件中的一些数据。 例如,我想要地址和数据的值。
我怎么能在node.js中做到这一点? fs.readFile(file.txt)
我不知道该怎么做。 我想我将不得不使用split
,但使用\n
似乎不是最好的select,也许正则expression式可以帮助?
理想的情况是“find一个以\nkey=
开头的子string,并以第一个\nkey=
结尾”,然后我可以很容易地分割来find这个值。
// @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; }
例:
// text should be obtained using fs.readFile... var text = "username=myusername\naddress=156a1355e3486f4\ndata=function(i){if (i!=0) return true; else return false;}"; function getValueByKey(text, key){ var regex = new RegExp("^" + key + "=(.*)$", "m"); var match = regex.exec(text); if(match) return match[1]; else return null; } console.log("adress: ", getValueByKey(text, "address")); console.log("username: ", getValueByKey(text, "username")); console.log("foo (non exist): ", getValueByKey(text, "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; }, {}); // ... });
您的设置将作为键/值存储在settings
对象中。