Module FS, as one of node's core modules, supports the interface of local file operations, providing both synchronous and asynchronous scenarios for almost all operations. For example, create folders with mkdir and Mkdirsync. Regardless of mkdir or mkdirsync, you need to be aware that you can create a folder only if the parent folder exists. For example, to create a dir1/dir2/dir3 under the current working directory, create a dir1, DIR2 before you can create DIR3.
Let's use the synchronous Mkdirsync method first.
1 varFs=require (' FS ');2 varPath= ' Dir1/dir2/dir3 ';3 createdir (path);4 functionCreatedir (path) {5 varPathary=path.split ('/');6 for(vari=0;i<pathary.length;i++){7 varCurpath=pathary.slice (0,i+1). Join ('/');8 varIsexist =Fs.existssync (curpath);9!isexist?fs.mkdirsync (Curpath):NULL;Ten } One}
Async method:
1 varFs=require (' FS ');2 varPath= ' Dir1/dir2/dir3 ';3 createdir (path);4 functionCreatedir (path) {5 varPathary=path.split ('/');6 for(vari=0;i<pathary.length;i++){7 varCurpath=pathary.slice (0,i+1). Join ('/');8Fs.exists (Curpath,function(exists) {9 if(!exists) {TenFs.mkdir (Curpath,function(){ OneConsole.log (curpath+ ' is created! '); A }); - } - }) the } -}
However, the second method cannot create any folders. Where is the problem? It's in the fs.exists. It is asynchronous, and when its callback function is executed, the outer loop is executed and Curpath becomes dir1/dir2/dir3. At this time, Fs.mkdir (CURPATH,CB) cannot create a folder because of the reasons mentioned above. At this point, we can use closures (self-executing functions) to solve this problem.
1 varFs=require (' FS ');2 varPath= ' Dir1/dir2/dir3 ';3 createdir (path);4 functionCreatedir (path) {5 varPathary=path.split ('/');6 for(vari=0;i<pathary.length;i++){7 varCurpath=pathary.slice (0,i+1). Join ('/');8(function(Curpath) {//Curpath incoming closures9Fs.exists (Curpath,function(exists) {Ten if(!exists) { OneFs.mkdir (Curpath,function(){ AConsole.log (curpath+ ' is created! '); - }); - } the }) - }) (Curpath); - } -}
The current path Curpath is private to the closure, and mkdir accesses the curpath of the current scope.
How to create a folder asynchronously (node)