Skip to content

How to empty a folder in Node.js

How to remove all files from a directory in Node.js

I had the need to remove all files from a directory in a Node.js script.

I searched for the best solution and the one that worked was using the fs-extra library.

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)

→ Here's my latest YouTube video

→ Get my Node.js Handbook

→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list