Attached code, comments have been added (note: to write in synchronous mode, because the number of folders is uncertain, so all files need to be deleted before deleting folders, personal experience, because of this small problem, the whole process took a long time)
const fs = require('fs');
// Encapsulates an immediate function that returns an object
let delDir = (() = > {
return {
// the entry function
init: function (url) {
this.del(url);
},
// Delete function, pass the current folder as an argument, note: use synchronization, otherwise error (because the folder cannot be deleted if the number of items in the folder is not 0)
del: function (url) {
// Create an array to store the traversed files or folders in the same layer
var files = [];
files = fs.readdirSync(url);
for (var i = 0; i < files.length; i++) {
var path = url + '/' + files[i];
If it is a file, delete it. If it is a folder, recursively delete the folder again (do not operate on the folder until all files are deleted (because synchronization is used)).
if (fs.statSync(path).isFile()) {
fs.unlinkSync(path);
} else {
this.del(path);
}
}
fs.rmdirSync(url);
}
};
})();
// Throws a module object
module.exports = delDir;
Copy the code