node js 打包文件

node js 、 依赖包JSZIP

打包 压缩

fileCompression: (folderPath) ->
    zip = new JSZip()
    zipPath = pathM.join folderPath,'..',pathM.basename(folderPath)+'.zip'
    flag = "root"
    # 递归函数 当遇到文件或者文件夹里面没有文件时结束
    compressionZip= (node,filePath,isroot) =>
      # windows 和 linux 文件路径兼容处理
      stats = fs.statSync(filePath)
      # 1、将 windows 文件路径的 \ 转为 linux 文件路径的 /
      str1=node.replace(/\\/g,"/")
      # 2、切割路径
      strs=str1.split("/")
      tmp = zip
      if strs[0] is "."
        isroot = true
      # 3、以 tmp 保存当前 最外层文件夹
      getLast = (filePath) =>
        tmp = tmp.folder(filePath)
      if strs isnt null and strs.length isnt 0
        getLast fileItem for fileItem in strs
      # 4、保存文件夹或者文件
      if stats.isFile()
        fileName = pathM.basename(filePath)
        if isroot
          zip.file(fileName,fs.readFileSync(filePath))
        else
          tmp.file(fileName,fs.readFileSync(filePath))
      else
        if flag is "root"
          flag = "children"
          folderZipPath = node
        else
          folderZipPath = pathM.join node,pathM.basename(filePath)
          if isroot
            zip.folder(pathM.basename(filePath))
          else
            tmp.folder(pathM.basename(filePath))
        fileList = fs.readdirSync(filePath)
        if fileList isnt null and fileList.length isnt 0
          compressionZip folderZipPath,pathM.join(filePath,filePathItem),false for  filePathItem in fileList
    compressionZip ".",folderPath,true
    # 5、保存 zip
    content = zip.generate({type:"nodebuffer",compression:"DEFLATE"})
    fs.writeFileSync(zipPath,content)
    console.log "打包完了"


解压包

UnCompressFile: (zipPath, success) ->
    unzipPath = pathM.join zipPath,".."
    cb = (err, data) =>
      if err
        throw err
      object = new JSZip(data)
      readAndwrite = (zipObject) ->
        savePath = pathM.join unzipPath,zipObject.name
        if zipObject.dir
          if fs.existsSync(savePath)
            console.log "文件夹已存在,文件夹中的相同文件将被覆盖"
          else
            fs.mkdirSync(savePath)
        else
          tmp = savePath.substring(savePath.lastIndexOf('.'))
          tmp = tmp.toUpperCase()
          # 当文件问 图片时 使用 zipObject.asNodeBuffer() 其他的使用zipObject.asText()
          if tmp is '.PNG' or tmp is '.GIF' or tmp is '.JPG' or tmp is '.JPEG' or tmp is '.BMP'
            fs.writeFileSync(pathM.join(unzipPath,"icon3.png"),zipObject.asNodeBuffer())
          else
            fs.writeFileSync(savePath,zipObject.asText())
      readAndwrite zipObject for fileName , zipObject of object.files
      if typeof success isnt "undefined"
        success()
    fs.readFile(zipPath,cb)








转载于:https://my.oschina.net/swchenyuzhe/blog/476441

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值