Last active
September 6, 2016 14:14
-
-
Save hgwood/51fab6b45ad263896859d5ab73db4e0d to your computer and use it in GitHub Desktop.
Walking a directory tree synchronously with Node.js 6+
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'); | |
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