Nodejs 压缩文件、jszip
发布于 2 个月前 作者 vuexx 469 次浏览 来自 分享

jszip

nodejs 压缩文件使用的是``jszip`

const JSZIP = require('jszip')
const zip = new JSZIP()

// 构建本地Zip文件
function buildZip() {
  pushZip(zip, path.resolve(__dirname, './dist'));
  zip.generateAsync({
    type: 'nodebuffer',
    compression: 'DEFLATE',
    compressionOptions: {
      level: 9
    }
  }).then(function (content) {
    fs.writeFile(path.resolve(__dirname, './dist.zip'), content, err => {
      if (err) throw err;
      console.log('文件已被保存');
    });
  });
}

function pushZip(floder, pPath) {
  const files = fs.readdirSync(pPath, { withFileTypes: true });
  files.forEach((dirent, index) => {
    let filePath = `${pPath}/${dirent.name}`;
    if (dirent.isDirectory()) {
      let zipFloder = zip.folder(filePath.replace(`${__dirname}\\prod/`, ''));
      pushZip(zipFloder, filePath);
    } else {
      floder.file(dirent.name, fs.readFileSync(filePath));
    }
  });
}

buildZip()
回到顶部