Last active
December 2, 2015 03:16
-
-
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
This file contains hidden or 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
/* | |
* 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