Created
July 10, 2018 21:11
-
-
Save luveti/3c67af040285f1119cef4bd2ca6b50c8 to your computer and use it in GitHub Desktop.
Walk Sync - Stack Based
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
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