1

I'm a total beginner with backend, node and express I'm trying to build an api that resize the image according to the entered params in the URL and render it in the browser using typeScript, so I'm using sharp to resize the image, express to build the local server and fs to read the image.

here is my code:

import express from "express";
import sharp from "sharp";
const fs = require("fs");

const img = express.Router();

const resizeImage = async function (width: number, height: number) {
try {
await sharp("./imgs/fjord.jpg")
.resize({
width: width,
height: height,
})
.toFile("./imgs/thumbs/fjord-resized.jpg");
} catch (err) {
console.log(err);
}
};

img.get("/", (req, res) => {
const queryData = req.query;
resizeImage(Number(queryData.width), Number(queryData.height)).then(
fs.readFile(
"./imgs/thumbs/fjord-resized.jpg",
(err: string, data: unknown): void => {
if (err) throw err;

        res.writeHead(200, { "content-type": "image/jpg" });
        res.end(data);
      }
    )

);
});

export default img;

I tried to chain the resizeImage async function with "then" to make the app resize the Image first then use the fs to acquire the resized image and read it but for some reason it is not working the image get resized and output to the folder but every time I need to restart the server or reload the page to read the new resized image

  • You're using Express, so why not use it's built-in `sendFile`? It would then be only `.then(() => res.sendFile(theFilePath))`. – kelsny Jan 09 '23 at 14:49

0 Answers0