Created
February 14, 2011 07:15
-
-
Save AndrewRayCode/825583 to your computer and use it in GitHub Desktop.
recursive read directory in node.js returning flattened list of files and directories
This file contains hidden or 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
function readDir(start, callback) { | |
// Use lstat to resolve symlink if we are passed a symlink | |
fs.lstat(start, function(err, stat) { | |
if(err) { | |
return callback(err); | |
} | |
var found = {dirs: [], files: []}, | |
total = 0, | |
processed = 0; | |
function isDir(abspath) { | |
fs.stat(abspath, function(err, stat) { | |
if(stat.isDirectory()) { | |
found.dirs.push(abspath); | |
// If we found a directory, recurse! | |
readDir(abspath, function(err, data) { | |
found.dirs = found.dirs.concat(data.dirs); | |
found.files = found.files.concat(data.files); | |
if(++processed == total) { | |
callback(null, found); | |
} | |
}); | |
} else { | |
found.files.push(abspath); | |
if(++processed == total) { | |
callback(null, found); | |
} | |
} | |
}); | |
} | |
// Read through all the files in this directory | |
if(stat.isDirectory()) { | |
fs.readdir(start, function (err, files) { | |
total = files.length; | |
for(var x=0, l=files.length; x<l; x++) { | |
isDir(path.join(start, files[x])); | |
} | |
}); | |
} else { | |
return callback(new Error("path: " + start + " is not a directory")); | |
} | |
}); | |
}; |
You have my direct permission to use this code in whatever project you want, regardless of license.
Useful code, but it 'hangs' (never calls callback) if it reaches an empty directory. To fix this, put:
if (total === 0) {
callback(null, found);
}
.. on line 36.
This repo contains small bugs and is unmaintained. Please see forks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
do you have any objections if this code is used in a BSD licensed open-source project? just asking because there's no mention of a license, so strictly speaking i can't use this...