Practicing I/O in nodejs, I tried to process a text file that contains lines of:
{ date: 2018-02-16T16:55:35.296Z, _id: 5a870d074dfade27c4c0ce35, id: '5546721
I chose the npm package line-by-line, and I initially had my code:
let numbers = '';
const lr = new LineByLineReader('./resources/4501-ids.txt');
lr.on('line', function (line) {
let x = line.lastIndexOf("'");
let y = line.substring(x+1);
numbers += y + ', ';
console.log(y);
count++;
});
lr.on('end', function () {
numbers = numbers.substring(0, numbers.lastIndexOf(', '));
res.send(numbers);
});
and I was expected to get
2345, 23465, 66435,
but I had:
2345, , 23465, , 66435,
I suspected that it is a carriage return somehow in, so I tried to extract it by going like if(y=== "\r\n") and no luck, finally changing one line to:
if(y)
numbers += y + ', ';
did it. I have it done but what is that y there that doubles the line and perhaps plays a carriage return role?
Your text file content is little unclear, (incomplete content + output not matching to line you have mentioned). But with output that you expect, you can change code to
let numbers = [];
const lr = new LineByLineReader('./resources/4501-ids.txt');
lr.on('line', function (line) {
let x = line.lastIndexOf("'");
let y = line.substring(x+1);
numbers.push(y);
console.log(y);
//count++; //this is not needed numbers.length will give you this
});
lr.on('end', function () {
// numbers = numbers.substring(0, numbers.lastIndexOf(', '));
res.send(numbers.toString());
});
Apart from this, if the content of resource file is json, you can simply import/require it and you will get json object and wouldn't need to process it line by line.