Skip to content

Instantly share code, notes, and snippets.

@Yago
Created December 12, 2017 09:34
Show Gist options
  • Save Yago/f4d46d4b25ded7d939328c237d54aff0 to your computer and use it in GitHub Desktop.
Save Yago/f4d46d4b25ded7d939328c237d54aff0 to your computer and use it in GitHub Desktop.
Recursive directory tree maker using only Node.js
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