Skip to content

Instantly share code, notes, and snippets.

@iximiuz
Created March 13, 2019 13:43
Show Gist options
  • Save iximiuz/a13601063078e9041406974c8207e3c5 to your computer and use it in GitHub Desktop.
Save iximiuz/a13601063078e9041406974c8207e3c5 to your computer and use it in GitHub Desktop.
Tiny recursive walkdir (aka readdir) in JavaScript
const fs = require('fs');
const path = require('path');
async function *walkdir(dir) {
const stack = [dir];
while (stack.length) {
const filename = stack.pop();
const stat = await fs.promises.stat(filename);
if (stat.isDirectory()) {
const files = (await fs.promises.readdir(filename))
.map(ch => path.join(filename, ch));
stack.push(...files.sort().reverse());
} else {
yield filename;
}
}
}
(async function(dir) {
for await (const filename of walkdir(dir)) {
console.log(filename);
}
})(process.argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment