Skip to content

Instantly share code, notes, and snippets.

@bjacobel
Created January 11, 2019 15:27
Show Gist options
  • Save bjacobel/78cfbc00d1583994a88f8ac1466944e4 to your computer and use it in GitHub Desktop.
Save bjacobel/78cfbc00d1583994a88f8ac1466944e4 to your computer and use it in GitHub Desktop.
Recursively turn a folder into a JS object, where the directories are subtrees and the files are Buffers
const fs = require("fs");
/**
* Recursively turn a folder into an object, where directories are sub-objects and files are Buffers.
* Works nicely with github.com/tschaub/mock-fs
* Requires Node >= 8.6
* @param {string} dirpath
* @param {bool} full - pass this as true at the start to make the top level dir an absolute path
*/
const rreaddir = async function(dirpath, full = false) {
return new Promise((resolve, reject) => {
fs.readdir(dirpath, (err, items) => {
if (err) reject(err);
resolve(
items.reduce(async (prev, shortName) => {
let contents;
const fullName = path.join(dirpath, shortName);
if (fs.lstatSync(fullName).isDirectory()) {
const subfolder = await rreaddir(fullName);
contents = { [full ? fullName : shortName]: subfolder };
} else {
contents = {
[shortName]: await new Promise((resolve) =>
fs.readFile(fullName, "utf8", (err, data) => resolve(data)),
),
};
}
return {
...(await prev),
...contents,
};
}, {}),
);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment