Last active
December 16, 2015 08:48
-
-
Save shanewholloway/5408089 to your computer and use it in GitHub Desktop.
Quick recursive directory walker modeled after python's `os.walk`
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'), 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