La idea es pasar una consulta que contenga el nombre del archivo y el tamaño de la siguiente manera:
localhost:3000/images?filename=myImage&width=100&height=100Primero, quiero saber cómo obtener las imágenes de la carpeta de imágenes. Segundo, utilícelas para cambiar el tamaño de la imagen. Y por último, escribe el archivo en una nueva carpeta llamada upload. Estoy intentando con el siguiente código por ahora, pero estoy atascado y necesito ayuda para continuar: Empiezo a refactorizar el código y ahora tengo un archivo utilities.ts con el siguiente código:
import { promises as fs } from "fs"; // accessing the images let getAccessToFiles = (path: string): boolean => { try { fs.access(path) return true; } catch (err) { return false; } } let getFilesName = ( imageToResize: string, width: number | null, height: number | null ): string => { let filename = imageToResize; if (width) { filename += `width${width}`; } if (height) { filename += `height${height}`; } return `${filename}.jpg` }; export { getAccessToFiles, getFilesName };Ahora simplemente creo la conversión de esta manera:
import express, { Request, Response, Router } from "express"; import path from "path"; import sharp from "sharp"; import { getAccessToFiles, getFilesName } from "../../utils/utilities"; const resizeImages: Router = Router(); const app = express(); // access the images const importImages = path.resolve(__dirname, "images"); // add the output file const exportImages = path.resolve(__dirname, "uploads"); // allowing our application to parse json input app.use(express.json()); resizeImages.get("/", (req: Request, res: Response) => { const resizeImage = async ( imageName: string, width: number | null, height: number | null ): Promise<string> => { const resizedImageName = getFilesName(imageName, width, height); try { await sharp(`${importImages}${imageName}.jpg`) .resize(width, height) .jpeg() .toFile(`${importImages}${resizedImageName}`); } catch (err) { res.status(400).json({ error: err}); } return resizedImageName; }; return res.send(resizeImage) }); export default resizeImages;Y finalmente tiene el siguiente error: el primer argumento debe ser de tipo cadena o una instancia de Buffer, ArrayBuffer o Array o un objeto tipo Array. Función recibida resizeImage
express coloca los parámetros de consulta en un accesorio llamado query , por lo que en el código OP: req.query.filename , req.query.width y req.query.height .
Una versión más plausible (no probada) del código OP se vería así...
// presuming a query looks like "?filename=myImage&width=100&height=100" const importImages = './images'; // note the removal of the trailing '/' const exportImages = './uploads'; resizeImages.get('/', (req, res) => { // note the suggested change in route name // note that res.send() moved to become the last promise in the chain const fileIn = `${importImages}/${req.query.filename}`; const fileOut = `${exportImages}/${req.query.filename}`; // note the construction of a complete input and output file specs const params = { width: req.query.width, height: req.query.height, fit: 'contain', background: { r: 255, g: 0, b: 0, alpha: 0.5 } }; return sharp(fileIn) .resize(params).toBuffer().then(data => { fs.writeFile(fileOut, data); }).then(() => { return res.send('done'); }) .catch(err => { console.log(err); return res.status(400).send(err); }); });