I have an Asyn function that, with an URL of an image, resizes the image and send it to a /thumb folder.
The problem is that when invoking the next function "readFile()", the previous Async function hasn't finished yet, therefore there is not image in the /thumb folder.
I have tried different ways but I can't find a solution.
This is my image.ts file:
/* eslint-disable prettier/prettier */
import express from 'express';
import fsPromises from 'fs';
import path from 'path';
import resize from '../../utilities/resize';
const image = express.Router();
let myImagePath = path.join(__dirname, '/../../../assets/full/');
let myImageBuffer = path.join(__dirname, '/../../../assets/thumb/');
image.get('/', (req, res) => {
myImagePath += `${req.query.filename}`;
myImageBuffer += `${req.query.filename}`;
const filename = req.query.filename as unknown as string;
const width: number = res.locals.width;
const height: number = res.locals.height;
(async function resizer(width: number, height: number): Promise<boolean | undefined> {
try {
const result = resize(myImagePath, width, height, filename);
return result;
} catch (error) {
console.error(error);
}
})(width, height);
const myImage = ( function readFile(myPath: string) {
try {
const result = fsPromises.readFileSync(myPath);
return result;
} catch (error) {
console.error(error);
res
.status(404)
.send('Image not found, please provide the right name of the file.');
}
})(myImageBuffer);
myImagePath = path.join(__dirname, '/../../../assets/full/');
myImageBuffer = path.join(__dirname, '/../../../assets/thumb/');
res.end(myImage);
});
export default image;
This is my resize.ts file:
import sharp from 'sharp';
import path from 'path';
import fs from 'fs';
const resize = function (
filePath: string,
width: number,
height: number,
filename: string
): boolean | undefined {
const newPath = path.join(__dirname, `/../../assets/thumb/${filename}`);
let result: boolean;
if (fs.existsSync(filePath)) {
result = true;
try {
sharp(filePath).resize(width, height).toFile(newPath);
return true;
} catch (error) {
console.error(error);
}
} else {
result = false;
return result;
}
};
export default resize;
Thank you