How to return a value inside the .then() from Node.js module to server file?

Viewed 25

I am trying a build a module function that will resize an image passed into it using Sharp. I am logging the image data perfectly inside the .then() given below, but when I return this same result, it turns out to be undefined.

Please help me find what am I doing wrong here.

Module

exports.scaleImg = function (w,h,givenPath){
          let toInsertImgData;
          sharp(givenPath)
            .resize(w, h)
            .jpeg({
              quality: 80,
              chromaSubsampling: "4:4:4",
            })
            .toFile(compressedImgPath)
            .then(() => {
              fsPromises.readFile(compressedImgPath).then((imgData) => {
                  toInsertImgData = {
                    data: imgData,
                    contentType: "image/jpeg",
                  };
                  console.log(toInsertImgData);
                  return(toInsertImgData);
              });
            });
            
      }

here compressedImgPath is just a path to a folder in the root directory.

server file

const imageScalingModule = require(__dirname+"/modules.js");



app.post("/compose",upload.fields([{ name: "propic" }, { name: "image" }]),
      (req, res) => {

           console.log(imageScalingModule.scaleImg(640, 480, req.files.image[0].path));
});
1 Answers

then() returns a promise, so you need to change your code inside the /compose-handler to wait for the promise to resolve (I'm using async/await, but you could also do scaleImg(...).then()):

app.post("/compose",upload.fields([{ name: "propic" }, { name: "image" }]),
      async (req, res) => {
          const res = await imageScalingModule.scaleImg(640, 480, req.files.image[0].path);
          console.log(res);
          res.send(res); // you probably want to do something like this, otherwise the request hangs
});
Related