nodejs递归创建/删除目录,解压

 

//创建目录
FileService.mkdirs = function (dirpath) {
  if (!fs.existsSync(path.dirname(dirpath))) {
    FileService.mkdirs(path.dirname(dirpath));
  }
  if (!fs.existsSync(dirpath)) {
    fs.mkdirSync(dirpath);
  }
}


//删除目录

FileService.deleteFolder = function (path, waitTime) {
  let _waitTime = waitTime || 0;
  setTimeout(function () {
    console.log("start delete tmp folder", path);
    deleteFolder(path)
  }, _waitTime);
};

function deleteFolder(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function (file, index) {
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) { // recurse
        deleteFolder(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

//解压zip
FileService.prototype.unzip = function (zipFilePath, unzipPath) {
  return new Promise(function (accept, reject) {
    yauzl.open(zipFilePath, {lazyEntries: true}, function (err, zipfile) {
      if (err) {
        reject(err);
      }
      let counter = 0;
      zipfile.readEntry();
      zipfile.on("entry", function (entry) {
        counter++;
        if (/\/$/.test(entry.fileName)) {
          zipfile.readEntry();
        } else {
          zipfile.openReadStream(entry, function (err, readStream) {
            if (err) {
              reject(err);
            }
            let unzipPath_deep = path.normalize(unzipPath + "/" + entry.fileName);
            FileService.mkdirs(path.normalize(unzipPath_deep.substring(0, unzipPath_deep.lastIndexOf(path.normalize("/"))) + "/"));
            readStream.on("end", function () {
              zipfile.readEntry();
            });
            let writeStream = fs.createWriteStream(unzipPath_deep);
            readStream.pipe(writeStream);
            writeStream.on('error', (error) => {
              reject(error)
            });
            readStream.on('error', (error) => {
              reject(error)
            });
          });
        }
      });
      zipfile.on("end", function (entry) {
        if (counter === zipfile.entryCount) {
          accept('end');
        }
      });
      zipfile.on("error", function (err) {
        reject(err)
      });
    });
  });
};

 

你可能感兴趣的:(nodejs)