Last active
December 5, 2016 08:02
-
-
Save hustshawn/29d8e5ac0703f3f23d793a43f3751ca8 to your computer and use it in GitHub Desktop.
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
/* | |
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