Reputation: 467
I need to fetch information in settings a file (I can't change the format) according to certain keywords. The file goes like this:
username=myusername
address=156a1355e3486f4
data=function(i){if (i!=0) return true; else return false;}
The system is <key>
=
<value>
\n
. There can be =
, spaces or other characters in the value part, but never line breaks. Keys are unique (in the "key part", they can appear in values, but \nkey=
appears only once in the file for every key).
With a shell script, I find my values like this:
username=`grep ^username file.txt | sed "s/^username=//"`
Grep will return username=someusername
and sed replaces the key and =
with nothing, leaving only the value.
In node.js, I would like to access some of the data in the file. For example, I want the value for address and data.
How could I do this in node.js ? After fs.readFile(file.txt)
I don't know what to do. I guess I will have to use split
, but using \n
doesn't seem to be the best option, maybe regex can help ?
The ideal thing would be to "find a substring starting with \nkey=
and ending with the first \n
", then I could easily split to find the value.
Upvotes: 2
Views: 5545
Reputation: 706
Using split
and reduce
, you can do something like that :
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;
}, {});
// ...
});
Your settings will be stored as key/value in the settings
object.
Upvotes: 0
Reputation: 31712
// @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"));
Upvotes: 5