Skip to content

How to remove a directory that is not empty in Node.js

The  FS  module provides an API for interacting with the file system, folders. We can use it to remove files, folder.

But if your node.js version is lower than 12.10.0 , it doesn’t support to remove a directory recursively.

There are a few ways to do it:

  • Write an recursive function to remove all files in the directory
const fs = require('fs');
const path = require('path');

const deleteFolderRecursive = function(folderPath) {
    if (fs.existsSync(folderPath)) {
        const files = fs.readdirSync(folderPath);
        if (!Array.isArray(files) || !files.length) {
            return;
        }
        files.map(file => {
            const currentPath = path.join(folderPath, file);
            if (fs.lstatSync(currentPath).isDirectory()) { // recurse
                deleteFolderRecursive(currentPath);
            } else { // delete file
                fs.unlinkSync(currentPath);
            }
        })
        fs.rmdirSync(folderPath);
    }
};
deleteFolderRecursive(__dirname + '/storage/temp/cbd1b7eb-c368-45b5-b414-e8c8508e885c');
const rimraf = require('rimraf');
rimraf('/path/to/directory', function () {
    console.log('--removed successfully');
});
// or
rimraf.sync('/path/to/directory');
const fs = require('fs-extra');
fs.remove('/path/to/directory', function () {
    console.log('--removed successfully');
});
// or
fs.removeSync('/path/to/directory'); 

If your node.js version is >= 12.10.0, you might want to use this:

const fs = require('fs');
fs.rmdir('/path/to/directory', { recursive: true }, function () {
    console.log('--removed successfully');
});
// or
fs.rmdirSync('/path/to/directory', { recursive: true });

Notes: the rmdir function with option: {recursive: true}, it is still an experimental feature

So, the best way is: using fs-extra or rimraf

Published inUncategorized

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *