rsnext/packages/next/server/lib/recursive-readdir-sync.ts

30 lines
800 B
TypeScript
Raw Normal View History

2019-05-03 18:57:47 +02:00
import fs from 'fs'
import { join } from 'path'
/**
* Recursively read directory
* @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 Array holding all relative paths
*/
export function recursiveReadDirSync(
dir: string,
arr: string[] = [],
rootDir = dir
): string[] {
2019-05-03 18:57:47 +02:00
const result = fs.readdirSync(dir)
result.forEach((part: string) => {
const absolutePath = join(dir, part)
const pathStat = fs.statSync(absolutePath)
if (pathStat.isDirectory()) {
recursiveReadDirSync(absolutePath, arr, rootDir)
return
}
arr.push(absolutePath.replace(rootDir, ''))
})
return arr
}