How to empty a folder in Node.js
By Flavio Copes
Learn how to empty a folder in Node.js and remove all files from a directory using the fs-extra library and its emptyDirSync() method.
To empty a folder in Node.js, the cleanest way I found is the emptyDirSync() method from the fs-extra library. I had the need to remove all files from a directory in a Node.js script, and after searching for the best solution, this is the one that worked: fs-extra.
Why a library? The standard fs module has no “empty this folder” method. You can delete the whole folder with fs.rmSync(folder, { recursive: true }), but that removes the folder itself, so you have to recreate it after. Or you can read the directory and delete each entry one by one. fs-extra wraps all of that into a single call.
Install it:
npm install fs-extra
Then import the library
import fsExtra from 'fs-extra'
And use the emptyDirSync() method in this way:
const folder = './public/images'
fsExtra.emptyDirSync(folder)
The method deletes everything inside the folder, files and subfolders alike, but keeps the folder itself. As a bonus, if the folder doesn’t exist yet, it creates it. That makes it great for build scripts: you can call it on every run without checking whether it’s the first one.
The async version
emptyDirSync() blocks until it’s done. In a small script that’s fine. Inside a server, or anywhere you want to stay async, use emptyDir(), which returns a promise:
import fsExtra from 'fs-extra'
await fsExtra.emptyDir('./public/images')
console.log('folder emptied')
The pitfall: relative paths
A path like ./public/images is resolved against the current working directory, the folder you run the script from. Not the folder where the script file lives.
Run the script from somewhere else, and it will empty (or create!) a public/images folder in an unexpected place. Since we’re deleting files with no confirmation and no undo, that’s a real risk.
The fix is to anchor the path to the script’s own location:
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import fsExtra from 'fs-extra'
const dir = path.dirname(fileURLToPath(import.meta.url))
const folder = path.join(dir, 'public', 'images')
fsExtra.emptyDirSync(folder)
Now the path is the same no matter where you launch the script from.
My advice: before running a script that empties a folder, console.log() the resolved path once and read it. It’s a two-second check that can save you from deleting the wrong directory.
Related posts about node: