Skip to content

Instantly share code, notes, and snippets.

@jade-itworkswhy
Created February 1, 2024 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jade-itworkswhy/209dcf6321fe523f1b99e180cc3c6cfe to your computer and use it in GitHub Desktop.
Save jade-itworkswhy/209dcf6321fe523f1b99e180cc3c6cfe to your computer and use it in GitHub Desktop.
node_fs_helpers
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