Skip to content

Instantly share code, notes, and snippets.

@hgwood
Last active September 6, 2016 14:14
Show Gist options
  • Save hgwood/51fab6b45ad263896859d5ab73db4e0d to your computer and use it in GitHub Desktop.
Save hgwood/51fab6b45ad263896859d5ab73db4e0d to your computer and use it in GitHub Desktop.
Walking a directory tree synchronously with Node.js 6+
const fs = require('fs');
function walk(root) {
const files = [];
const dirs = [root];
while (dirs.length) {
const dir = dirs.shift();
const dircontent = fs.readdirSync(dir).map(file => path.join(dir, file));
const [newDirs, newFiles] = partition(dircontent, file => fs.statSync(file).isDirectory());
files.push(...newFiles);
dirs.push(...newDirs);
}
return files;
// can be replaced by _.partition
function partition(items, predicate) {
return items.reduce((partitions, item) => {
const partitionIndex = +!predicate(item);
partitions[partitionIndex].push(item);
return partitions;
}, [[], []]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment