fs.rmdir(path,
callback)
This
method removes a directory asynchronously. On execution of mkdir function,
callback is called. Callback function takes one argument ‘err’, it contains
error stack trace on failure cases.
var fs = require('fs'); var directory_to_remove = 'testDir'; fs.rmdir(directory_to_remove, (err) => { if(err){ console.log(err); }else{ console.log(`Directory ${directory_to_remove} removed`) } });
This
method does not delete the contents of the directory, if directory has some
data inside it.
Below
application remove the contents of the directory recursively.
HelloWorld.js
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; console.log(filePath); var stats = fs.statSync(filePath); if (stats.isDirectory()) { removeDirectory(filePath); fs.rmdirSync(filePath); } else { fs.unlinkSync(filePath); } }); } removeDirectory(directory_to_remove); fs.rmdir(directory_to_remove, (err) => { if (err) { console.log(err); } else { console.log(`Directory ${directory_to_remove} removed`) } });
No comments:
Post a Comment