Created
December 12, 2017 09:34
-
-
Save Yago/f4d46d4b25ded7d939328c237d54aff0 to your computer and use it in GitHub Desktop.
Recursive directory tree maker using only Node.js
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
const fs = require('fs'); | |
const path = require('path'); | |
// Valid file extensions | |
const valideExts = ['.md', '.html']; | |
// Recursive directory parser | |
const treeMaker = (dir) => { | |
return new Promise((resolve, reject) => { | |
const children = {}; | |
fs.readdir(dir, async (err, list) => { | |
if (err) reject(); | |
// Init children files container | |
children.f = []; | |
for (let child of list) { | |
const childPath = `${dir}/${child}`; | |
const isDir = fs.lstatSync(childPath).isDirectory(); | |
if (isDir) { | |
// Parse sub-directory and record subtree | |
const subtree = await treeMaker(childPath); | |
children[child] = subtree; | |
} else { | |
// Validate and record files | |
const fileExt = path.extname(child); | |
if (valideExts.includes(fileExt)) children.f.push(child); | |
} | |
}; | |
resolve(children); | |
}); | |
}); | |
}; | |
module.exports = async (rootPath) => { | |
const tree = await treeMaker(rootPath); | |
return tree; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment