Created
February 1, 2024 12:45
-
-
Save jade-itworkswhy/209dcf6321fe523f1b99e180cc3c6cfe to your computer and use it in GitHub Desktop.
node_fs_helpers
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 { existsSync, lstatSync, readdirSync, rmdirSync, unlinkSync } from 'fs' | |
import path from 'path' | |
/** | |
* Clears a directory by deleting all its files and sub-folders recursively. | |
* @param folderPath - The path of the directory to be cleared. | |
* @throws Error if the folder does not exist. | |
*/ | |
export function clearDir(folderPath: string) { | |
if (existsSync(folderPath)) { | |
const files = readdirSync(folderPath) | |
files.forEach((file: string) => { | |
const current = path.join(folderPath, file) | |
if (lstatSync(current).isDirectory()) { | |
// Recursively clear the sub-folder | |
clearDir(current) | |
rmdirSync(current) // Delete the sub-folder | |
} else { | |
// Delete the file | |
unlinkSync(current) | |
} | |
}) | |
} else { | |
throw new Error('Folder not found: ' + folderPath) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment