Created
September 27, 2018 09:09
-
-
Save lunaroyster/fa29ddfad2e1fea008c27661b0fe7ff4 to your computer and use it in GitHub Desktop.
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'); | |
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