Created
November 20, 2020 17:58
-
-
Save jimmylab/dcc47856fcc1f3dfc782cc431b52f160 to your computer and use it in GitHub Desktop.
Asynchronous folder traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var path = require('path'); | |
var desc = function(onfinish, counter) { | |
if (--counter[0] < 0) { | |
if ("function" === typeof onfinish) { | |
onfinish(); | |
} | |
} | |
} | |
var dirTraversalRecursive = function(dir, callback, onfinish, counter) { | |
fs.readdir(dir, (err, files) => { | |
if (!err && "undefined" !== typeof files && files instanceof Array) { | |
files.forEach(filename => { | |
var fullpath = path.join(dir, filename); | |
counter[0]++; | |
fs.stat(fullpath, (err, stat) => { | |
if (err) | |
desc(onfinish, counter); | |
if (stat.isDirectory()) { | |
dirTraversalRecursive(fullpath, callback, onfinish, counter); | |
} else { | |
setTimeout(() => { | |
callback(filename, dir, fullpath); | |
desc(onfinish, counter); | |
}, 0); | |
} | |
}); | |
}); | |
} | |
desc(onfinish, counter); | |
}); | |
}; | |
/** | |
* Traverse in target directory | |
* @param {string} dir | |
* @param {(filename:string, dir:string, fullpath:string)=> number} callback | |
* @param {function} onfinish | |
*/ | |
var dirTraversal = function(dir, callback, onfinish) { | |
// A counter as a number shall not be passed reference. | |
var counter = [0]; | |
dirTraversalRecursive(dir, callback, onfinish, counter); | |
}; | |
exports.dirTraversal = dirTraversal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment