How can I detect when my image is saved on my server?

Viewed 215

Basically I finished uploading an image to my server(file) and when I want to save it I want to use the library called imagemin to compress the size, but it seems that when I use this library, the image is not available, or it has not finished saving in the folder.

I tried to compress an image that is already in that same directory and it compresses it perfectly, so I am almost sure that the problem happens because the image has not been completely saved yet.

How can I solve that?

let saveImage = (file) => {


 return new Promise((resolve, reject) => {

    let folder=__dirname + "/../gallery/";
    let name_file="my_image.png";
    file.mv(`${folder}${name_file}`, (err) => {

        (async () => {

        //at this moment my image is not avalaible
        const files =  imagemin([`${folder}${name_file}`], {
            destination:folder,
            plugins: [
            imageminPngquant({
                quality: [0.5, 0.6],
            }),
            ],
        });
        console.log(files); //output is []
        })();
        resolve({ ok: true});
    });
 })
}



app.post("/upload_photo", [], async function (req, res) {
    my_file = await saveImage(req.files.my_file);
    if(my_file.ok){
      return res.json({
       ok: true,
       message: "success!",
      });
    }

  });

I am assuming a perfect scenario where I will have no errors, then I will put the respective validations. Note: err is always null, so I have no errors.

2 Answers

This is asynchronous operation. You need to await until it's finished before resolving your promise

        const files = /* needs*/ await /*here*/  imagemin([`${folder}${name_file}`], {
            destination:folder,
            plugins: [
            imageminPngquant({
                quality: [0.5, 0.6],
            }),
            ],
        });

This works:

const fs = require('fs');
const imagemin = require('imagemin');
const imageminPngquant = require('imagemin-pngquant');

let saveImage = async (file) => {
  return new Promise((resolve, reject) => {
    let folder = __dirname + '/gallery/';
    let name_file = 'my_image-' + Date.now() + '.png';
    fs.rename(file, `${folder}${name_file}`, (err) => {
      //at this moment my image is not avalaible
      (async () => {
        const files = await imagemin([`${folder}${name_file}`], {
          destination: folder,
          plugins: [
            imageminPngquant({
              quality: [0.5, 0.6],
            }),
          ],
        });
        console.log(files); //output is []
      })();
      resolve({ ok: true });
    });
  });
};

(async () => {
  my_file = await saveImage('./screenshot.png');
  if (my_file.ok) {
    console.log('Success');
  }
})();
Related