在nodejs中将文件压缩后传输到前端

需求:将一些数据写入到json文件中将这些数据与对应的素材压缩后传到前端
1. 在数据库中查询到相应数据
const data = await this.models.data.findAll({
  where: {
    id: parseInt(id),
  },
});
2. 构建目录
const promiseDirSync = function(dir = './test', mode) {
  if (fs.existsSync(dir)) return;
  promiseDirSync(path.dirname(dir), mode);
  fs.mkdirSync(dir, mode);
};
// 构建压缩文件夹
await exportForImport({data});
3. 构建压缩文件夹
async exportForImport(params) {
  // 设置各种路径
  const testPath1 = path.join('./xx1/', 'xx/xx1'); // 需要压缩的目录
  const testPath2 = path.join('./xx2/', 'xx/xx2'); // 素材目录
  const testPath3 = path.join('./xx3/', 'xx/xx3'); // 
  // ...

  // 定义文件复制函数
  const copyDirSync = function(dir, target) {
    // 如果目标目录不存在,创建
    if (!fs.existsSync(target)) {
      fs.mkdirSync(target);
    }
    const files = fs.readdirSync(dir); // 同步拿到文件目录下的所有文件名
    files.forEach(function(item) {
      const itemPath = path.join(dir, item);
      const targetPath = path.join(target, item);
      const stat = fs.statSync(itemPath);
      if (stat.isFile()) {
        fs.copyFileSync(itemPath, targetPath);
      } else {
        copyDirSync(itemPath, targetPath);
      }
    });
  };

  // 复制文件
  rmDirSync(testPath1);
  if (fs.existsSync(testPath2)) copyDirSync(testPath2, testPath1);
  else promiseDirSync(testPath1);
  
  // 写入数据
  const configPath = path.join(testPath1, 'config.json');
  fs.writeFileSync(configPath, JSON.stringify(params, undefined, 2));
}
压缩文件并传给前端
const distPath = path.join('xx/');
const filePath = path.join(xx/xx.xx);
await tar.c(
  {
    gzip: true,
    file: filePath,
    cwd: distPath,
  },
  fs.readdirSync(distPath)
);
ctx.attachment(`xx.xx`);
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值