I'm trying to learn async programming and was struggling with lesson 4 of nodeschool.io with the implementation of an async io with callbacks.
Basically, I'm trying to use fs.readFile to count the number of newlines within a file using a callback.
Here's my code:
var fs = require('fs');
var pathToFile = process.argv[2];
function counter(callback) {
var buffer = fs.readFile(pathToFile, function (err, data) {
var bufferString = buffer.toString();
var bufferStringSplit = bufferString.split('\n');
});
callback();
}
function logMyNumber() {
console.log(bufferStringSplit.length-1);
}
counter(logMyNumber);
I understand that callbacks are executed once the line of code is finished executing, so shouldn't the
var bufferString = buffer.toString();
var bufferStringSplit = bufferString.split('\n');
be called after fs.readFile() finishes reading the file from disk?
Then finally the callback() calls logMyNumber, which should just output the number of lines the file has.
Same problem for me. This is my solution.
You have several issues going on and I'll try to outline them all as best as possible
Problem 1: Variable scope
Solution:
Declare the variables in the module's scope:
Problem 2: Callbacks
Problem 3: fs.readFile API
fs.readFile
doesn't return anything, so yourbuffer
variable below isnull
Solution:
Finally, the code should look like:
Trying to treat errors as well. Not sure, if it is better to propagate the error in the last callback. I think the functionality is quite basic, but anyway I am propagating errors.
I would also say is more correct to delegate the split in the last callback rather than passing it through an argument or similar.