Skip to content

Instantly share code, notes, and snippets.

@zRains
Created February 27, 2023 06:46
Show Gist options
  • Save zRains/1e10754a8a93b580cb7b6d82a9a18e64 to your computer and use it in GitHub Desktop.
Save zRains/1e10754a8a93b580cb7b6d82a9a18e64 to your computer and use it in GitHub Desktop.
Get files in a dir by ext.
const fs = require('node:fs')
const path = require('node:path')
/**
* Traverse files in a dir
* @param {string} dirPath Dir path
* @param {string[]} ext
* @param {number} [deep]
* @param {any[]} [collection]
*/
function traverseFile(dirPath, ext, deep = Infinity, collection = []) {
if (deep <= 0) return collection
const pathArr = fs.readdirSync(dirPath)
pathArr.forEach((itemName) => {
const currentItemPath = path.resolve(dirPath, itemName)
const currentItemStat = fs.statSync(currentItemPath)
if (currentItemStat.isDirectory()) {
traverseFile(currentItemPath, ext, deep - 1, collection)
} else {
const itemExt = path.extname(itemName)
ext.includes(itemExt) &&
collection.push({
path: path.resolve(__dirname, itemName),
name: itemName,
ext: itemExt,
})
}
})
return collection
}
console.log(traverseFile(path.resolve(__dirname, '../percs/data'), ['.md', '.mdx']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment