Skip to content

Instantly share code, notes, and snippets.

@luveti
Created July 10, 2018 21:11
Show Gist options
  • Save luveti/3c67af040285f1119cef4bd2ca6b50c8 to your computer and use it in GitHub Desktop.
Save luveti/3c67af040285f1119cef4bd2ca6b50c8 to your computer and use it in GitHub Desktop.
Walk Sync - Stack Based
async function walkSync(rootDir) {
const fs = require('fs')
const path = require('path')
function readdir(path) {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, files) => err ? reject(err) : resolve(files))
})
}
function stat(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => err ? reject(err) : resolve(stats))
})
}
async function pushStack(baseDir) {
stack.push({ baseDir, files: await readdir(baseDir) })
}
const results = []
const stack = []
await pushStack(rootDir)
while (stack.length > 0) {
let { baseDir, files } = stack.pop()
for (let file of files) {
let relativeFilePath = path.join(baseDir, file)
if ((await stat(relativeFilePath)).isDirectory()) {
await pushStack(relativeFilePath)
}
else {
results.push(relativeFilePath)
}
}
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment