Node. js folder directory structure creation instance code

  • 2021-07-02 22:59:46
  • OfStack

The first time I touched NodeJS's file system, I was confused by its asynchronous response. Later, I found that NodeJS still has synchronous methods to judge whether a folder exists and create a folder, but I still want to try to use asynchronous methods to achieve it.

Methods used:

fs.exists(path, callback);

fs.mkdir(path, [mode], callback);

The creation code to realize the folder directory structure is as follows:


// Create a 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 folder! ');
        }else{
          console.log(currentDir+' Folder - Successful creation! ');
          mkdir(pos+1,dirArray,_callback);
        }
      });
    }else{
      console.log(currentDir+' Folder - Already exists! ');
      mkdir(pos+1,dirArray,_callback);
    }
  });
}

// Create a 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 finished ! Prepare to write to file !');
        _callback();
      });
    }else{
      console.log(' Folder already exists ! Prepare to write to file !');
      _callback();
    }
  });
}

First need to create a directory structure stored in an array, and then mainly use the idea of deep search to achieve (depth for the length of the array).


Related articles: