Created
May 12, 2012 21:47
-
-
Save Raynos/2669295 to your computer and use it in GitHub Desktop.
Iterate all the files
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 iterateFiles = require("iterateFiles"), | |
path = require("path") | |
// Load all files in the test folder or any of their sub folders | |
iterateFile(path.join(process.cwd(), "./test"), function (fileName) { | |
// run code for each recursively found js file | |
}, function (err) { | |
// run code when all files have been found recursively | |
}) |
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"), | |
isJsFile = /.js$/ | |
function iterateFiles(uri, callback, done) { | |
var counter = 1 | |
fs.readdir(uri, errorProxy(done, readFiles)) | |
function readFiles(err, files) { | |
counter += files.length | |
files.forEach(isDirOrFile) | |
next() | |
} | |
function isDirOrFile(fileName) { | |
fileName = path.join(uri, fileName) | |
fs.stat(fileName, errorProxy(done, readOrRecurse)) | |
function readOrRecurse(err, stat) { | |
if (stat.isDirectory()) { | |
iterateFiles(fileName, callback, errorProxy(done, next)) | |
} else if (stat.isFile() && isJsFile.test(fileName)) { | |
callback(fileName) | |
next() | |
} else { | |
next() | |
} | |
} | |
} | |
function next() { | |
if (--counter === 0) { | |
done(null) | |
} | |
} | |
} | |
function errorProxy(errorHandler, callback) { | |
return proxy | |
function proxy(err) { | |
if (err) { | |
return errorHandler(err) | |
} | |
return callback.apply(this, arguments) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In that case you should rename
iterateFiles
toiterateJSFiles
or whatever? Actually a much better argument is that people may want to iterate over non-js files, such as .txt files or whatever.