Skip to content

Instantly share code, notes, and snippets.

@TylerK
Last active December 2, 2015 03:16
Show Gist options
  • Save TylerK/9076a3287a4d0c1ce51c to your computer and use it in GitHub Desktop.
Save TylerK/9076a3287a4d0c1ce51c to your computer and use it in GitHub Desktop.
Quick function to walk a local directory and return a Javascript object of it's files\folder structure
/*
* Recursively walk a directory and return JSON.
* @param {string} dir - root dir to walk, must supply this.
* @param {object} structure - internal object to build, no need to supply this.
*/
let walkDir = (dir, structure = []) => {
let files = fs.readdirSync(dir);
files.forEach((node, i) => {
let here = path.join(dir, node);
let type = fs.statSync(here);
if (type.isDirectory()) {
structure[i] = {
type: 'folder',
folderName: node,
files: walkDir(here)
};
}
else if (type.isFile()) {
structure[i] = {
createdAt: type.birthtime || type.ctime,
fileName: node,
fileSize: type.size,
lastModified: type.mtime,
type: 'file' // TODO: Hook this up to actual file type.
};
}
});
return structure;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment