The first time I came into contact with NodeJS, I was stunned by its asynchronous response. Later I found that NodeJS has a synchronous method to determine whether a folder exists and create a folder, but I still want to try to use an asynchronous method to implement it.
Methods to use:
fs.exists(path, callback);
fs.mkdir(path, [mode], callback);
The creation code for implementing the folder directory structure is as follows:
//Create folder function mkdir(pos, dirArray,_callback){ var len = dirArray.length; console.log(len); if( pos >= len || pos > 10){ _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('Error creating a folder!'); }else{ console.log(currentDir+'Folder-created successfully!'); mkdir(pos+1,dirArray,_callback); } }); }else{ console.log(currentDir+'Folder-existed!'); 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 is created! Ready to write to the file!'); _callback(); }); }else{ console.log('Folder already exists! Ready to write to the file!'); _callback(); } });}First, store a directory structure that needs to be created in an array, and then mainly implement the idea of deep search (the depth is the length of the array).
The above Node.js folder directory structure creation example code is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.