The first contact with the Nodejs file system was confused by its asynchronous response, and later found that Nodejs to determine whether the folder exists and create a folder is still synchronized method, but still want to try to use the asynchronous method to implement.
Methods to use:
Fs.exists(path, callback);
Fs.mkdir(path, [mode], callback);
The creation code that implements the folder directory structure is implemented as follows:
Create Folder function mkdir (pos, dirarray,_callback) {var len = dirarray.length;
Console.log (len);
if (pos >= len | | pos >) {_callback ();
Return
} var currentdir = ';
for (var i= 0; I <=pos; i++) {if (i!=0) currentdir+= '/';
Currentdir + = Dirarray[i];
} fs.exists (Currentdir,function (exists) {if (!exists) {Fs.mkdir (Currentdir,function (Err) {if (err) { Console.log (' Create folder Error!
'); }else{console.log (currentdir+ ' folder-Create success!
');
mkdir (Pos+1,dirarray,_callback);
}
}); }else{console.log (currentdir+ ' folder)-already exists!
');
mkdir (Pos+1,dirarray,_callback);
}
});
}//Create directory structure function mkdirs (dirpath,_callback) {var dirarray = dirpath.split ('/'); Fs.exists (Dirpath, function (exists) {if (!exists) {mkdir (0, Dirarray,function () {Console.log (' folder creation completed!)
Write file! ');
_callback ();
});
}else{Console.log (' folder already exists! Ready to write to file! ');
_callback ();
}
});}
First, a directory structure that needs to be created is stored in an array, which is then implemented mainly by the thought of deep search (depth is the length of the array).
The above Node.js folder directory structure to create an instance code is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.