Skip to content

Instantly share code, notes, and snippets.

@trozdol
Created January 16, 2021 20:40
Show Gist options
  • Select an option

  • Save trozdol/196b6e47803a6d034fa7aad9fa24ad8a to your computer and use it in GitHub Desktop.

Select an option

Save trozdol/196b6e47803a6d034fa7aad9fa24ad8a to your computer and use it in GitHub Desktop.
const { readdirSync, statSync } = require('fs');
const { resolve, parse } = require('path');
async function tree(path = '.', opts = {}) {
path = resolve(path);
opts = Object.assign({ toArray: false, depth: 1, maxDepth: 5 }, opts);
const list = opts.toArray ? [] : new Map();
const currentDepth = opts.depth;
const maxDepthReached = (opts.depth >= opts.maxDepth);
opts.depth++;
try {
var index = 0;
const files = await readdirSync(path);
for (const file of files) {
const full = resolve(path, file);
const stats = await statSync(full);
const isDir = stats.isDirectory();
const children = isDir && !maxDepthReached ? await tree(full, opts) : null;
const meta = Object.assign(
stats,
parse(full),
{
index: index++,
depth: currentDepth,
type: isDir ? 'directory' : 'file',
pathname: full,
},
(isDir ? {
total: children ? (children.size || children.length) : 0,
files: children
} : {})
);
if (opts.toArray) {
list.push(meta);
} else {
list.set(file, meta);
}
}
} catch(e) {
console.error('Error:', e.message);
}
return list;
}
// output as a Map
tree('.', {
toArray: false,
maxDepth: 2
}).then(map => {
console.log(map);
});
// output to array
tree('.', {
toArray: true,
maxDepth: 4
}).then(arr => {
console.log(JSON.stringify(arr, null, 4))
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment