Refer to the code here below:
var fs = require('fs');
var file = 'test.js';
var search = new RegExp("\n", "g");
function printLineNum(err, fileContents) {
if (err) return console.error(err.message);
console.log("Total line(s) of document: %d", fileContents.match(search).length + 1);
}
fs.readFile(file, 'utf8', printLineNum);
// output: Total line(s) of document: 10
This is a working piece of code. But before I made the changes, line 7 looks like:
console.log("Total line(s) of document: " + fileContents.match(search).length + 1);
// output: 91
The unexpected error also can be solve by adding parenthesis to the numbers:
console.log("Total line(s) of document: " + (fileContents.match(search).length + 1));
// output: 10
I know how to avoid the error but I can't figure out what's wrong exactly. Is this a JavaScript thing or something to do with console.log?