[Node.js] Apply image filter on Express

import fs from 'fs';
import Jimp = require('jimp');

// filterImageFromURL
// helper function to download, filter, and save the filtered image locally
// returns the absolute path to the local image
// INPUTS
//    inputURL: string - a publicly accessible url to an image file
// RETURNS
//    an absolute path to a filtered image locally saved file
export async function filterImageFromURL(inputURL: string): Promise<string>{
    return new Promise( async resolve => {
        const photo = await Jimp.read(inputURL);
        const outpath = '/tmp/filtered.'+Math.floor(Math.random() * 2000)+'.jpg';
        await photo
        .resize(256, 256) // resize
        .quality(60) // set JPEG quality
        .greyscale() // set greyscale
        .write(__dirname+outpath, (img)=>{
            resolve(__dirname+outpath);
        });
    });
}

// deleteLocalFiles
// helper function to delete files on the local disk
// useful to cleanup after tasks
// INPUTS
//    files: Array<string> an array of absolute paths to files
export async function deleteLocalFiles(files:Array<string>){
    for( let file of files) {
        fs.unlinkSync(file);
    }
}

 

Endpoint:

  app.get('/filteredimage', async (req: Request, res: Response) => {
    const {image_url} = req.query;
    if (!image_url) {
      return res.status(422).send({
        message: `image_url query param is required`
      })
    }
    const filtered_img_path = await filterImageFromURL(image_url.toString())
    res.sendFile(filtered_img_path);
    allFiles.push(filtered_img_path);
  })

 

We want to delete previously generate files from local, this can be done by using middleware:

  let allFiles: string[] = [];
  const cleanUp = (req: Request, res: Response, next: NextFunction) => {
    const sendFile = res.sendFile.bind(res);
    res.sendFile = (body: any) => {
      sendFile(body);
      deleteLocalFiles(allFiles)
      allFiles = [];
    }
    next();
  }

  app.use('/', cleanUp)

 

posted @ 2021-03-28 01:48  Zhentiw  阅读(144)  评论(0编辑  收藏  举报