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)