Given this code which counts the files in the given directory and subdirectories, how do I go about indicating that the operation is done?
function walkDirs(dirPath) {
var fs = require('fs'),
path = require('path'),
events = require('events'),
count = 0,
emitter = new events.EventEmitter();
function walkDir(dirPath) {
function readDirCallback(err, entries) {
for (var idx in entries) {
var fullPath = path.join(dirPath, entries[idx]);
(function statHandler(fullPath) {
fs.stat(fullPath, function statEach(err, stats) {
if (stats) {
if (stats.isDirectory()) {
walkDir(fullPath);
} else if (stats.isFile()) {
count += 1;
emitter.emit('counted', count, fullPath);
}
}
});
})(fullPath);
}
}
fs.readdir(dirPath, readDirCallback);
}
walkDir(dirPath);
return emitter;
}
var walker = walkDirs('C:');
I've tried specifically,
- firing an event to indicate "doneness" at a place I thought appropriate, specifically after
fs.readdir(dirPath, readDirCallback)call. - modifying
statHandler()to return the count added. (I realized that this is effectively no different from incrementingcountinside that function.
Both of these failed, because when checked, the value of count is 0. I've determined that I'm not waiting until the operation (counting the files) is done. Obviously, I need to fire a callback or event when done to get the right count.
I know the code is successfully counting, because when attaching a debugger, the count value is as expected.
At this point, I've fairly certainly determined that I have no idea how to further proceed. Specically -
How do I implement indicating "doneness" in an asynchronous operation?
Aucun commentaire:
Enregistrer un commentaire