简体   繁体   中英

NodeJS: How to zip (local) files after done with JIMP

I'm trying to use NodeJS to automate some trivial procedures on my computer. Right now I'm able to convert some png files into jpg. I would like to bundle them all up in a zip.

const fs = require('fs')
const path = require('path')
const jimp = require('jimp')

const files = fs.readdirSync('./')

// Convert all png to jpg
const pngs = files.filter(file => path.extname(file).toLowerCase() === '.png')

let jpgs = []

Promise.all(pngs.map(png => jimp.read('./' + png))).then(jimps => {
  jimps.map((img, i) => {
    img
      .rgba(false)
      .background(0xffffffff)
      .write(`./jpgs/${path.basename(pngs[i], '.png')}.jpg`)
  })
  console.log('Done converting')
})

// Zip all the .png and .jpg files into PNGs.zip and JPGs.zip
// TODO:

I fiddled a bite around with JSZip but couldn't make it work.

SOLUTION

const fs = require('fs')
const path = require('path')
const jimp = require('jimp')
const CLIProgress = require('cli-progress')

const zipPNG = new require('node-zip')()
const zipJPG = new require('node-zip')()

const files = fs.readdirSync('./')

// Convert all png to jpg
const pngs = files.filter(file => path.extname(file).toLowerCase() === '.png')
let jpgs = []

Promise.all(pngs.map(png => jimp.read('./' + png))).then(jimps => {
  const bar = new CLIProgress.Bar({}, CLIProgress.Presets.shades_classic)
  bar.start(pngs.length, 0)

  jimps.map((img, i) => {
    img
      .rgba(false)
      .background(0xffffffff)
      .write(`./jpgs/${path.basename(pngs[i], '.png')}.jpg`)

    bar.update(i + 1)
  })
  bar.stop()
  console.log('Done converting')

  // Pack the files nicely in ZIP
  pngs.forEach(png => {
    zipPNG.file(png, fs.readFileSync(path.join('./', png)))
    zipJPG.file(
      `${path.basename(png, '.png')}.jpg`,
      fs.readFileSync(`./jpgs/${path.basename(png, '.png')}.jpg`)
    )
  })

  let data = zipPNG.generate({ base64: false, compression: 'DEFLATE' })
  fs.writeFileSync('PNG.zip', data, 'binary')
  console.log('PNGs zipped')

  data = zipJPG.generate({ base64: false, compression: 'DEFLATE' })
  fs.writeFileSync('./jpgs/JPG.zip', data, 'binary')
  console.log('JPGs zipped')
})

I would use the npm package node-zip . It is a very straightforward library with an easy to use interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM