Skip to content

Instantly share code, notes, and snippets.

@NoahDragon
Last active June 16, 2016 19:35
Show Gist options
  • Save NoahDragon/242fef0b3476cfed50c0cbae272c6d24 to your computer and use it in GitHub Desktop.
Save NoahDragon/242fef0b3476cfed50c0cbae272c6d24 to your computer and use it in GitHub Desktop.
Loop through a directory.
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