node.js delete directory & file system
delete a not empty directory
fs.rmdir(path[, options], callback)
fs.rmdirSync(path[, options])
recursive: true
In a Node.js application, you can use the fs.rmdir()
method to delete a directory.
This method works asynchronously to remove the directory.
If the directory is not empty, you can pass an optional recursive
flag to delete all nested files and folders recursively.
const fs = require('fs');
// directory path
const dir = 'temp';
// delete directory recursively
fs.rmdir(dir, { recursive: true }, (err) => {
if (err) {
throw err;
}
console.log(`${dir} is deleted!`);
});
const fs = require('fs');
// directory path
const dir = 'temp';
// delete directory recursively
try {
fs.rmdirSync(dir, { recursive: true });
console.log(`${dir} is deleted!`);
} catch (err) {
console.error(`Error while deleting ${dir}.`);
}
del
https://www.npmjs.com/package/del
$ npm i -D del
https://github.com/sindresorhus/del/blob/master/index.js
trash
https://github.com/sindresorhus/trash/blob/master/index.js
rimraf
https://www.npmjs.com/package/rimraf
$ npm i -D rimraf
https://github.com/isaacs/rimraf/blob/master/rimraf.js
refs
https://attacomsian.com/blog/nodejs-delete-directory
https://geedew.com/remove-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);
}
};
unlink
https://stackoverflow.com/questions/39963966/can-fs-unlink-delete-a-empty-or-non-empty-folder
https://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty/32197381
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!