[Node.js] Apply image filter on Express
2023-09-14 08:59:12 时间
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)
相关文章
- JS框架_(JQuery.js)圆形多选菜单选项
- JS框架_(coolShow.js)图片旋转动画特效
- JS框架_(Progress.js)圆形动画进度条
- JS框架_(JQuery.js)图片相册掀开切换效果
- JS框架_(JQuery.js)夜晚天空满天星星闪烁动画
- 【华为云技术分享】【一统江湖的大前端(8)】matter.js 经典物理
- flv.js播放视频时出现Failed to execute ‘appendBuffer’ on ‘SourceBuffer’ 错误
- JS插件之——bootstrap-suggest.js
- thymeleaf中js跳转到另外一个页面
- js的server worker创建子进程
- [Node.js] Add node.js command line to global
- [Node.js] node-persist: localStorage on the server
- [Whole Web, Node.js, PM2] Restarting your node.js app on code change using pm2
- js导出excel
- [Node.js] Add node.js command line to global
- [NPM] Use npx to run commands with different Node.js versions
- [Vue] Use Vue.js Component Computed Properties
- [Node.js] node-persist: localStorage on the server
- [Node.js] Using npm link to use node modules that are "in progress"
- 华为OD机试 - 可以组成网络的服务器(Java & JS & Python)
- 原生js实现随机验证码HTMl-JS
- JS compose 函数实现
- JS中数组深度拷贝
- 使用live delegate on解决js后装html故障问题
- 【JS高级】js面向对象三大特性之继承_06
- 【JS高级】js之闭包对象_04
- 前端必备技能知识:JS导出Blob流文件为Excel表格、Vue.js使用Blob的方式实现excel表格的下载(流文件下载)
- 2021前端常见面试题必考必问:js中 非==和 非=的区别是什么?js中==和===区别?