http://blog.163.com/hule_sky/blog/static/2091622452015112821829773/
Node file system FS provides us with a number of ways to read and write files and folders, and so on. The following section describes commands for deleting all content under Folders and subfolders (both synchronous and asynchronous methods) 1, Fs.stat && Fs.statsync provides access to file property Information 2, Fs.readdir && Fs.readdirsync provides read file directory information 3, Fs.unlink && unlinksync to delete file operations, not You can delete folders 4, Fs.rmdir && Fs.rmdirsync to delete a folder operation, but the folder must be an empty folder next to the folder Delete work First step: Delete all the files ( Clear all folders) Part II: Delete all empty folders complete the above two steps, you can achieve our goal, below to see the specific code implementation
Router.get ('/removefile ',function(req,res,next) {
var rootfile = '.. // Make Money ';// the folder URL to delete
Delete all Files ( leave all folders blank )
var emptydir = function(FILEURL) {
var files = Fs.readdirsync (FILEURL);//Read the folder
Files.foreach (function(file) {
var stats = fs.statsync (fileurl+ '/' +file);
if (Stats.isdirectory ()) {
Emptydir (fileurl+ '/' +file);
}Else{
Fs.unlinksync (fileurl+ '/' +file);
Console.log (" Delete file " +fileurl+ '/' +file+ " success ");
}
});
}
Delete all empty folders
var rmemptydir = function (FILEURL) {
var files = Fs.readdirsync (FILEURL);
if (files.length>0) {
var tempfile = 0;
Files.foreach (function (fileName)
{
tempfile++;
Rmemptydir (fileurl+ '/' +filename);
});
if (tempfile==files.length) {//delete all empty folders under the parent folder, the parent folder is also deleted
Fs.rmdirsync (FILEURL);
Console.log (' Delete empty folder ' +fileurl+ ' success ');
}
}else{
Fs.rmdirsync (FILEURL);
Console.log (' Delete empty folder ' +fileurl+ ' success ');
}
}
Emptydir (RootFile);
Rmemptydir (RootFile);
Res.send (' YES!!! ');
});
page Back YES!!! Just look at your file directory, it's not there, it's done ~
Code optimization: Empty folders and delete folders once
var DeleteFolder = module.exports.deletefolder= Function (path) {
var files = [];
if (Fs.existssync (path)) {
Files = fs.readdirsync (path);
Files.foreach (function (file,index) {
var Curpath = path + "/" + file;
if (Fs.statsync (Curpath). Isdirectory ()) {//Recurse
DeleteFolder (Curpath);
} else {//delete file
Fs.unlinksync (Curpath);
}
});
Fs.rmdirsync (path);
}
};
Note File.foreach (function (file,index) {
Note that the file inside may not be a document or a directory.
});
Nodejs file System (FS) Delete all content under folders and subfolders