I want to read a file which has an kye and value.
I am using 'readline' to read line by line and store it to map object.
But it is not working and only shows that 'undefined'.
Do you guys have any ideas on how to fix it?
Thanks a lot in advance
#!/usr/bin/env node
const fs = require('fs');
const readline = require('readline');
const hg = require('./js/funtions.js');
if (require.main === module) {
const args = process.argv
var propertiesPath;
if(args.length >= 3){
propertiesPath = args[2];
}else {
console.log("No properties path");
process.exit(1);
}
if (propertiesPath.includes("-p")) {
propertiesPath = propertiesPath.replace("-p","");
}
const file = readline.createInterface({
input: fs.createReadStream(propertiesPath),
output: process.stdout,
terminal: false
});
var map = new Map();
var tokens,key,value;
file.on('line', (line) => {
tokens = line.split("=")
key = tokens[0];
value = tokens[1];
map.set(key,value);
});
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
}
using async/await with readline.on function
You don't use await
/async
in you code.
Besides that file.on('line', …)
registers a callback to be called for each line
the stream encounters and this happens asynchronously. Due to these two lines of code are executed before any line in the file was found by readline
:
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
If you want to execute those two lines of code after all lines have been read by the stream you need to do that at the close
event:
file.on('close', () => {
var jsonPath = map.get("jsonPath");
console.log(jsonPath);
});