Skip to content

Instantly share code, notes, and snippets.

@sigmasoldi3r
Last active March 17, 2020 12:40
Show Gist options
  • Save sigmasoldi3r/d982ef5c19bd3f0b066108ee6c2e6cc3 to your computer and use it in GitHub Desktop.
Save sigmasoldi3r/d982ef5c19bd3f0b066108ee6c2e6cc3 to your computer and use it in GitHub Desktop.
Asynchronous directory tree builder
'use strict';
const fs = require('fs');
module.exports = (path, solver) => {
fs.readdir(path, (err, childs) => {
let prom = childs.map((child) => {
return new Promise((r, j) => {
fs.stat(`${path}/${child}`, (err, stats) => {
if (stats.isDirectory()){
walk(`${path}/${child}`, (sub) => {
if (sub.length == 0)
r({path: `${path}/${child}`});
else
r({path: `${path}/${child}`, childs: sub});
});
} else {
r({path: `${path}/${child}`});
}
});//End stat
});//End promise
});//End map
Promise.all(prom).then((childs) => {
solver(childs);
});
});//End readdir
};
@sigmasoldi3r
Copy link
Author

sigmasoldi3r commented Mar 13, 2017

Example of usage

To use this simple snippet, require it in your nodejs project.

const dirTree = require('./dir-tree.js');

dirTree('./myDir/here', (tree) => {
  //Do your things with the tree
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment