I have a program that counts the number of lines in a text file and it works fine. What I am trying to do is count the number of lines in 2 different files and calculate their difference but I’m getting NaN
I parsed them to integers why is it not a number? How can I calculate their difference? Thanks in advance.
JavaScript
x
11
11
1
filePath = process.argv[2];
2
fileBuffer = fs.readFileSync('filePath');
3
to_string = fileBuffer.toString();
4
split_lines = to_string.split("n");
5
filePath2 = process.argv[2];
6
fileBuffer2 = fs.readFileSync('filePath2');
7
to_string2 = fileBuffer2.toString();
8
split_lines2 = to_string2.split("n");
9
10
//logging NaN
11
console.log("Calc :" + parseInt(split_lines2.length) - parseInt(split_lines.length))
Advertisement
Answer
Lets take a close look at this line
JavaScript
1
2
1
console.log("Calc :" + parseInt(split_lines2.length) - parseInt(split_lines.length))
2
Since I don’t have those var’s, lets replace them with some demo numbers:
JavaScript
1
1
1
console.log("Calc :" + 10 - 5);
This will still return NaN
because "Calc :10" - 5
fails.
If you enclose the sum in some brackets, there evaluated before adding to the string so it becomes "Calc :" + 5
. Since JS will convert the 5
to a string, it producing the expected output:
JavaScript
1
1
1
console.log("Calc :" + (10 - 5));
So you’re console.log
should look something like:
JavaScript
1
2
1
console.log("Calc :" + (parseInt(split_lines2.length) - parseInt(split_lines.length)))
2