Skip to content

Instantly share code, notes, and snippets.

@shanewholloway
Last active December 16, 2015 08:48
Show Gist options
  • Save shanewholloway/5408089 to your computer and use it in GitHub Desktop.
Save shanewholloway/5408089 to your computer and use it in GitHub Desktop.
Quick recursive directory walker modeled after python's `os.walk`
var fs=require('fs'), path=require('path')
var walkTree = (function() {
function WalkNode(path) {
this.path=path; this.dirs=[]; this.files=[]; }
WalkNode.prototype.dirPaths = function() {
return this.dirs.map(function(ea) {
return path.join(this.path, ea) }, this) }
WalkNode.prototype.filePaths = function() {
return this.files.map(function(ea) {
return path.join(this.path, ea) }, this) }
WalkNode.prototype.list = function(entries, callback) {
var n=entries.length, self=this;
if (n === 0) { callback(this); return }
Object.defineProperty(this, 'stats', {value:{}})
entries.forEach(function(ea) {
fs.stat(path.join(self.path, ea), function(err, stat) {
if (stat != null) {
self.stats[ea] = stat;
if (stat.isDirectory())
self.dirs.push(ea);
else self.files.push(ea);
}
if (--n === 0) callback(self)
}) }) }
function walkTree(root, callback) {
return walkDir(root)
function walkDir(dir) {
return fs.readdir(dir, function(err, entries) {
var node = new WalkNode(dir)
node.list(entries, function(node) {
callback(node)
node.dirPaths().forEach(walkDir) }) }) } }
return walkTree })()
if (require.main === module)
walkTree('..', function(node){ console.log('walk', node) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment