Skip to content

Instantly share code, notes, and snippets.

@lunaroyster
Created September 27, 2018 09:09
Show Gist options
  • Save lunaroyster/fa29ddfad2e1fea008c27661b0fe7ff4 to your computer and use it in GitHub Desktop.
Save lunaroyster/fa29ddfad2e1fea008c27661b0fe7ff4 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
async function walk(dir) {
return new Promise((resolve, reject) => {
fs.readdir(dir, (error, files) => {
if (error) return reject(error);
Promise.all(files.map((file) => {
return new Promise((resolve, reject) => {
const filepath = path.join(dir, file);
fs.stat(filepath, (error, stats) => {
if (error) return reject(error);
if (stats.isDirectory()) {
walk(filepath).then(resolve);
} else if (stats.isFile()) {
resolve(filepath);
}
});
});
}))
.then((foldersContents) => {
resolve(foldersContents.reduce((all, folderContents) => all.concat(folderContents), []));
});
});
});
}
async function getDirectoryMap(dir) {
let files = await walk(dir);
let directory = {};
files.forEach(f => {
let fragments = f.split('/');
let component = directory;
for (let i = 0; i<fragments.length; i++) {
let frag = fragments[i];
if(i==fragments.length-1) {
if(!component.files) component.files = [];
component.files.push(frag);
return;
}
if(!component[frag]) component[frag] = {};
component = component[frag];
}
});
return directory;
}
module.exports = getDirectoryMap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment