微信小程序云函数node.js实现多个文件打包成压缩包并上传到云存储

陈增
2023-12-01
// 云函数入口文件
const archiver = require('archiver')
const cloud = require('wx-server-sdk')
const fs = require('fs')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
// event中传入文件的fileID列表
exports.main = async (event, context) => {
  let output = fs.createWriteStream('/tmp'+ '/dist.zip')
  // 设置压缩级别
  const archiveObject = archiver('zip', {
    zlib: {
      level: 9
    } // Sets the compression level.
  })

  // 捕捉警告
  archiveObject.on('warning', function (err) {
    if (err.code === 'ENOENT') {
      // log warning
    } else {
      // throw error
      throw err
    }
  })

  // 明确捕获此错误
  archiveObject.on('error', function (err) {
    throw err
  })

  

  // 将数据归档到流文件中
  archiveObject.pipe(output)
  
  const wxContext = cloud.getWXContext()
  const fileIDList = event.fileIDList
  for (var item in fileIDList) {
    var res = await cloud.downloadFile({
      fileID: fileIDList[item],
    })
    var buffer = res.fileContent
    var string = fileIDList[item].split('/')
    archiveObject.append(buffer, {
      name: string[4]
    })
  }
  await archiveObject.finalize()
  //return "success"
  //上传到云存储并返回fileID
  var num = Math.round(Math.random()*100000000000)
  const fileStream = fs.createReadStream('/tmp'+ '/dist.zip')
  return await cloud.uploadFile({
    cloudPath: './作业合并的压缩包/dist'+num+'.zip',
    fileContent: fileStream,
  })
  
}
 类似资料: