Created
March 26, 2023 12:45
-
-
Save 3ru/2ff560e7611c44e495cae998c1a33314 to your computer and use it in GitHub Desktop.
Function to create files and directories simultaneously using the fs package.
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
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