Last active
June 16, 2016 19:35
-
-
Save NoahDragon/242fef0b3476cfed50c0cbae272c6d24 to your computer and use it in GitHub Desktop.
Loop through a directory.
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"); | |
// General function | |
var dive = function (dir, action) { | |
// Assert that it's a function | |
if (typeof action !== "function") | |
action = function (error, file, path) { }; | |
// Read the directory | |
fs.readdir(dir, function (err, list) { | |
// Return the error if something went wrong | |
if (err) | |
return action(err); | |
// For every file in the list | |
list.forEach(function (file) { | |
// Full path of that file | |
var path = dir + "/" + file; | |
// Get the file's stats | |
fs.stat(path, function (err, stat) { | |
//console.log(stat); | |
// If the file is a directory | |
if (stat && stat.isDirectory()) | |
// Dive into the directory | |
dive(path, action); | |
else | |
// Call the action | |
action(null, file, path); | |
}); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment