Last active
May 12, 2021 20:46
-
-
Save souporserious/617e78afed54fb02526cfdac0b5b5af1 to your computer and use it in GitHub Desktop.
File walker for Node
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 ignoredExtensions = ['tsx', 'mdx']; | |
const ignoredDirectories = ['components', 'assets', 'hooks']; | |
export async function getStaticProps() { | |
const routes = await walkFiles( | |
path.resolve(process.cwd(), 'src/pages'), | |
({ filePath, files, name, extension, isDirectory, children }) => { | |
const slug = `${path.dirname(filePath)}/${name}`.split('pages')[1]; | |
const containsIndex = files.some((file) => file.name.startsWith('index')); | |
const isIndexFile = name === 'index'; | |
const isPrivateFile = name[0] === '_'; | |
const isIgnoredFile = | |
!isDirectory && !ignoredExtensions.includes(extension); | |
const isIgnoredDirectory = | |
isDirectory && !containsIndex && ignoredDirectories.includes(name); | |
if (isIndexFile || isPrivateFile || isIgnoredFile || isIgnoredDirectory) { | |
return null; | |
} | |
return { | |
name, | |
slug, | |
children, | |
}; | |
} | |
); | |
return { props: { routes } }; | |
} |
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
async function walkFiles(filePath, format, isDirectory = null) { | |
const extension = path.extname(filePath).slice(1); | |
const name = path.basename(filePath, `.${extension}`); | |
let children = []; | |
if (isDirectory !== false) { | |
const files = await fs.readdir(filePath, { withFileTypes: true }); | |
children = await Promise.all( | |
files.map((file) => | |
walkFiles(`${filePath}/${file.name}`, format, file.isDirectory()) | |
) | |
); | |
children = children.filter(Boolean); | |
} | |
if (isDirectory === null) { | |
return children; | |
} | |
return format({ | |
name, | |
filePath, | |
extension: extension === '' ? null : extension, | |
isDirectory, | |
children, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment