node. js file copying creating folders and other related operations

  • 2021-10-25 06:02:40
  • OfStack

nodeJS copy of files:

1 Generally, the copy operation of small files uses the pipeline transportation operation of flow.

First you need to load the imported file: var fs = require ('fs');

1. Create folders synchronously


fs.mkdirSync(yourfileDirPath);

Create folders asynchronously


fs.mkdir(yourfileDirPath);

2. Determine whether the folder exists-synchronize


fs.existsSync(dirpath);

Asynchronous


fs.exists(dirpath);

Using the above related operations, we can directly write out a method to judge the creation of folders.


function mkdir(dirpath,dirname) {
  // Judgement number 2 Parameters may not be passed in 
  // Judgement number 2 Whether the parameters are normal or not, so as to avoid passing in wrong parameters when calling  
  if (dirname !== path.dirname(dirpath)) {
   mkdir(dirpath);
   return;
  }
  if (fs.existsSync(dirname)) {
   fs.mkdirSync(dirpath)
  } else {
   mkdir(dirname, path.dirname(dirname));
   fs.mkdirSync(dirpath);
  }
}

Pay attention to synchronous asynchronous creation, reading and other problems, otherwise the folder does not exist when copying. It is recommended to use synchronous creation of Sync. Method 1 is generally in the form of fs. xxxSync

Summarize


Related articles: