Last active
June 11, 2020 12:58
-
-
Save jniac/718f7180d3fa01543d85f8f7735d7521 to your computer and use it in GitHub Desktop.
walk.js
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
function* walk(object, currentPath = []) { | |
for (let [key, value] of Object.entries(object)) { | |
const path = [...currentPath, key] | |
yield [key, value, path] | |
if (value && typeof(value) === 'object') | |
yield* walk(value, path) | |
} | |
} |
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').promises | |
const Path = require('path') | |
module.exports = async function* walkDir(dir, options = {}) { | |
const { | |
ignoreDotFiles = true, | |
recursive = true, | |
skipFolder = true, | |
skip = null, // RegExp of Function | |
filter = null, // RegExp of Function | |
} = options | |
const files = await Promise.all( | |
(await fs.readdir(dir)) | |
.map(async name => { | |
const path = Path.join(dir, name) | |
const stat = await fs.stat(path) | |
return { name, path, stat } | |
}) | |
) | |
for (const file of files) { | |
const { name, path, stat } = file | |
if (stat.isDirectory()) { | |
if (!skipFolder) | |
yield file | |
if (recursive) | |
yield* walk(path, options) | |
} else { | |
if (ignoreDotFiles && name.startsWith('.')) | |
continue | |
if (skip) { | |
if (skip instanceof RegExp && skip.test(name)) | |
continue | |
if (skip instanceof Function && skip(file)) | |
continue | |
} | |
if (filter) { | |
if (filter instanceof RegExp && !filter.test(name)) | |
continue | |
if (filter instanceof Function && !filter(file)) | |
continue | |
} | |
yield file | |
} | |
} | |
} |
walkDir.js usage:
Print all js file in lib
const main = async () => {
const filter = /.js$/
for await (const { name, path, stat } of walkDir('my/path/to/something', { filter })) {
console.log(path)
}
}
main()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
walk.js usage: