Before I start pulling my hair out, I thought I should ask for help first:
I'm trying to read data from a file (line by line) and count how often the first two characters in each line occur. The results are supposed to be written to a text file.
If a line starts with **
, a counter is increased (recordCount
) and printed to console. It does print increasing numbers to the console. If I access this or another variable below the lineReader.on()
block however, they all have their initial values. How is this possible?
"use strict";
// ...
function processFile(filePath, outFile) {
let inFile = fs.createReadStream(filePath).pipe(new bomstrip());
let lineReader = readline.createInterface({
input: inFile
});
let tagCounts = {};
let recordCount = 0;
lineReader.on("line", function(line) {
let tag = line.slice(0, 2);
tag.trim();
if (!tag) {
return;
}
else if (tag == "**") {
recordCount++;
console.log(recordCount); // prints increasing numbers to console
} else {
let val = tagCounts[tag];
if (val === undefined) {
tagCounts[tag] = 1;
} else {
tagCounts[tag]++;
}
}
});
console.log(recordCount); // prints 0, but why?!
// ...
}
I'm using Node v5.7.0 on Windows 8.1 64bit. I also tried var
instead of let
, but same result.