rsnext/packages/next/lib/recursive-readdir.ts
Connor Davis 5514949df0 Remove glob package (#6415)
We don't use a lot of the features of `glob`, so let's remove it in favor of a leaner approach using regex.

It's failing on windows and I have no idea why and don't own a windows machine 🤦🏼‍♂️

(Ignore some of the commits in here, I forgot to create the new branch before I started working)
2019-02-24 22:08:35 +01:00

36 lines
1.1 KiB
TypeScript

import fs from 'fs'
import { join } from 'path'
import { promisify } from 'util'
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
/**
* Recursively read directory
* @param {string} dir Directory to read
* @param {RegExp} filter Filter for the file name, only the name part is considered, not the full path
* @param {string[]=[]} arr This doesn't have to be provided, it's used for the recursion
* @param {string=dir`} rootDir Used to replace the initial path, only the relative path is left, it's faster than path.relative.
* @returns Promise array holding all relative paths
*/
export async function recursiveReadDir(dir: string, filter: RegExp, arr: string[] = [], rootDir: string = dir): Promise<string[]> {
const result = await readdir(dir)
await Promise.all(result.map(async (part: string) => {
const absolutePath = join(dir, part)
const pathStat = await stat(absolutePath)
if (pathStat.isDirectory()) {
await recursiveReadDir(absolutePath, filter, arr, rootDir)
return
}
if (!filter.test(part)) {
return
}
arr.push(absolutePath.replace(rootDir, ''))
}))
return arr
}