Skip to content

Instantly share code, notes, and snippets.

@intrnl
Created December 15, 2019 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/834c9042dcb01aa045005690e792afe8 to your computer and use it in GitHub Desktop.
Save intrnl/834c9042dcb01aa045005690e792afe8 to your computer and use it in GitHub Desktop.
import fs from 'fs';
import path from 'path';
const fsp = fs.promises;
/**
* Creates a directory tree
* @param {string} dirname Path to directory to read
* @returns {object} A directory tree
*/
async function readdirTree (dirname) {
const baseDir = {};
const queue = [{ base: baseDir, dir: dirname }];
while (queue.length) {
const { base, dir } = queue.shift();
const listing = fsp.readdir(dir, { withFileTypes: true });
for (const item of listing) {
if (item.isDirectory()) {
const tree = {};
const fullDir = path.join(dir, item.name);
base[item.name] = tree;
queue.push({ base: tree, dir: fullDir });
} else {
base[item.name] = true;
}
}
}
return baseDir;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment