Timing problem in code execution

Asked

Viewed 35 times

1

Speak people, I made a small script to resize some images, save locally and create a zip with each of them, however, when the program will create the zip, the image has not finished being processed and has not been saved yet, then when it zips, it does not find the image and brings an error.

libs:

  • JIMP (for image editing)

  • Admzip (to zip images)

const jimp = require("jimp")
const AdmZip = require('adm-zip');

const imgs = [img1, img2, img3] // array com imagens

//tratando cada uma das imagens

for(let i = 0; i < imgs.length ; i++){ 
    let name = imgs[i].match(/[^\/]*$/)
    jimp.read(imgs[i], (err, imgs) => {
        if(err) throw err;
        imgs    
                .resize(jimp.AUTO,720)
                .quality(80)
                .write(`./images/${name}.jpg`); 
    })

//zipando a imagem
   
        let zip = new AdmZip();
        zip.addLocalFile(`./images/${name}.jpg`); <<< ERRO POIS A IMAGEM NÃO FOI ENCONTRADA PQ AINDA TÁ SENDO PROCESSADA PELO BLOCO ACIMA
         zip.writeZip(/*target file name*/`./images/${name}.zip`);
   
   
   
}

I even made it work by putting one setinterval to wait for the image to be saved for the zip to find the image:

    setInterval(()=>{
        let zip = new AdmZip();
        zip.addLocalFile(`./images/${name}.jpg`);
         zip.writeZip(/*target file name*/`./images/${name}.zip`);
    },5000)

but I believe that there is a better way to solve, without having to do this gambiarra of setinterval. You can help me?

  • opa, I added there, thanks for the tip!!!

1 answer

0

I think it’s missing to use the Promises to wait for the return. Looking at the library documentation I found this here.

Documentation

Example Usage (Promise will Never resolve if callback is passed):

var Jimp = require('jimp');
// open a file called "lenna.png"
Jimp.read('lenna.png', (err, lenna) => {
  if (err) throw err;
  lenna
    .resize(256, 256) // resize
    .quality(60) // set JPEG quality
    .greyscale() // set greyscale
    .write('lena-small-bw.jpg'); // save
});

Using Promises:

Jimp.read('lenna.png')
  .then(lenna => {
    return lenna
      .resize(256, 256) // resize
      .quality(60) // set JPEG quality
      .greyscale() // set greyscale
      .write('lena-small-bw.jpg'); // save
  })
  .catch(err => {
    console.error(err);
  });

I hope it helps :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.