Skip to content

Instantly share code, notes, and snippets.

@jniac
Last active June 11, 2020 12:58
Show Gist options
  • Save jniac/718f7180d3fa01543d85f8f7735d7521 to your computer and use it in GitHub Desktop.
Save jniac/718f7180d3fa01543d85f8f7735d7521 to your computer and use it in GitHub Desktop.
walk.js
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)
}
}
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
}
}
}
@jniac
Copy link
Author

jniac commented May 9, 2020

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