我需要根据某些关键字获取设置文件中的信息(我无法更改格式)。该文件是这样的:
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
sed 替换密钥并=
什么都没有,只留下价值。
在node.js中,我想访问some文件中的数据。例如,我想要地址和数据的值。
我怎样才能在node.js 中做到这一点?后fs.readFile(file.txt)
我不知道该怎么办。我想我必须使用split
,但是使用\n
似乎不是最好的选择,也许正则表达式可以提供帮助?
理想的情况是“找到一个以\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;
}
EXAMPLE:
// 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"));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)