Skip to content

Instantly share code, notes, and snippets.

@geedew
Last active February 3, 2021 12:36
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save geedew/cf66b81b0bcdab1f334b to your computer and use it in GitHub Desktop.
Save geedew/cf66b81b0bcdab1f334b to your computer and use it in GitHub Desktop.
Removing a directory that is not empty in NodeJS
var fs = require('fs');
var deleteFolderRecursive = function(path) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
@peq42
Copy link

peq42 commented Jul 2, 2018

doesn't work. Says that the directory is not empty

@peq42
Copy link

peq42 commented Jul 2, 2018

Also this code would be a minified version of yours:

function rmdir(d) {
    var self = arguments.callee
    if (fs.existsSync(d)) {
        fs.readdirSync(d).forEach(function(file) {
            var C = d + '/' + file
            if (fs.statSync(C).isDirectory()) self(C)
            else fs.unlinkSync(C)
        })
        fs.rmdirSync(d)
    }
}

If you could fix that(or yours) it would help me a lot

@laazebislam
Copy link

@Maycon-Santos
Copy link

Maycon-Santos commented May 26, 2020

const { execSync } = require('child_process')
const path = require('path')

const DIR = path.resolve(__dirname, '../directory-to-delete')

if (process.platform === 'win32') {
  execSync(`del /f /s ${DIR}`)
} else {
  execSync(`rm -rf ${DIR}`)
}

This works for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment