fs.rmdirSync(path)
Remove
a directory synchronously.
var fs = require('fs'); var directory_to_remove = 'testDir'; if (fs.existsSync(directory_to_remove)) { console.log(`Removing the file ${directory_to_remove}`); fs.rmdirSync(directory_to_remove); } else { console.log(`file ${directory_to_remove} not exists`); }
If
the directory has some content inside it, then this method do not delete the
directory,
Find
the below working application.
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`); }
No comments:
Post a Comment