Friday 19 October 2018

Node.js: Recursively remove a directory


var fs = require('fs');

var directory_to_remove = 'testDir';


/*Remove directory contents recursively */
function removeDirectory(dirToRemove) {

    fs.readdirSync(dirToRemove).forEach(function(fileName) {
        var filePath = dirToRemove + "/" + fileName;
        var stats = fs.statSync(filePath);

        if (stats.isDirectory()) {
            removeDirectory(filePath);
            fs.rmdirSync(filePath);
        } else {
            fs.unlinkSync(filePath);
        }

    });
}



if (fs.existsSync(directory_to_remove)) {
    console.log(`Removing the file ${directory_to_remove}`);
    removeDirectory(directory_to_remove);
    fs.rmdirSync(directory_to_remove);
} else {
    console.log(`file ${directory_to_remove} not exists`);
}

Previous                                                 Next                                                 Home

No comments:

Post a Comment