Skip to content

Instantly share code, notes, and snippets.

@hustshawn
Last active December 5, 2016 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hustshawn/29d8e5ac0703f3f23d793a43f3751ca8 to your computer and use it in GitHub Desktop.
Save hustshawn/29d8e5ac0703f3f23d793a43f3751ca8 to your computer and use it in GitHub Desktop.
/*
A directory tree like below.
A
/ \
B C
/ \ \
D E F
The access order of deep first and pre-order traversal algorithm should be :
A -> B -> D -> E -> C -> F
*/
var fs = require('fs');
function travel(dir, callback) {
fs.readdirSync(dir).forEach(function (file) {
var pathname = path.join(dir, file);
if (fs.statSync(pathname).isDirectory()) {
travel(pathname, callback);
} else {
callback(pathname);
}
});
}
// Async traverse
function travel (dir, callback, finish) {
fs.readdir(dir, function (err, files) {
(function next(i) {
if (i < files.length) {
var pathname = path.join(dir, files[i]);
fs.stat(pathname, function(err, stats) {
if (stats.isDirectory()) {
travel(pathname, callback, function () {
next(i + 1);
});
} else {
callback(pathname, function () {
next(i + 1);
});
}
});
} else {
finish && finish();
}
}(0));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment