Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created October 19, 2012 05:06
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ashblue/3916348 to your computer and use it in GitHub Desktop.
Save ashblue/3916348 to your computer and use it in GitHub Desktop.
NodeJS recursive directory listing without a module package
/**
* Goes through the given directory to return all files and folders recursively
* @author Ash Blue ash@blueashes.com
* @example getFilesRecursive('./folder/sub-folder');
* @requires Must include the file system module native to NodeJS, ex. var fs = require('fs');
* @param {string} folder Folder location to search through
* @returns {object} Nested tree of the found files
*/
// var fs = require('fs');
function getFilesRecursive (folder) {
var fileContents = fs.readdirSync(folder),
fileTree = [],
stats;
fileContents.forEach(function (fileName) {
stats = fs.lstatSync(folder + '/' + fileName);
if (stats.isDirectory()) {
fileTree.push({
name: fileName,
children: getFilesRecursive(folder + '/' + fileName)
});
} else {
fileTree.push({
name: fileName
});
}
});
return fileTree;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment