Skip to content

Instantly share code, notes, and snippets.

@3ru
Created March 26, 2023 12:45
Show Gist options
  • Save 3ru/2ff560e7611c44e495cae998c1a33314 to your computer and use it in GitHub Desktop.
Save 3ru/2ff560e7611c44e495cae998c1a33314 to your computer and use it in GitHub Desktop.
Function to create files and directories simultaneously using the fs package.
import fs from 'fs/promises'
/**
* Create files recursively if no directory.
*/
export const createFile = async (
data: string,
filePath: string,
): Promise<void> => {
try {
await fs.writeFile(filePath, data)
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
await fs.mkdir(path.dirname(filePath), { recursive: true })
await createFile(data, filePath)
} else {
throw err
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment