📜  如果 url 是图像,节点 js - TypeScript (1)

📅  最后修改于: 2023-12-03 15:09:18.600000             🧑  作者: Mango

如果 URL 是图像,节点 JS - TypeScript

在运行 Node.js 的服务器端应用程序中,经常需要处理从客户端请求的 URL。其中,如果 URL 是图像,需要采取特殊处理。

本文将简要介绍如何在 Node.js 中使用 TypeScript 处理 URL 中的图像。我们将使用 express 来构建我们的应用程序,并使用 sharp 库来处理图像。

步骤
  1. 首先,我们需要将 expresssharp 安装到我们的项目中。

    npm install --save express sharp
    
  2. 然后,我们需要创建一个 index.ts 文件,并初始化我们的应用程序。

    import express from 'express';
    
    const app = express();
    
    app.listen(3000, () => {
      console.log('Server started on port 3000');
    });
    
  3. 接下来,我们需要编写我们的路由处理程序。在这个例子中,我们将从 URL 加载一个图片文件,将其大小调整为 200x200 像素,并将其发送回客户端。

    import sharp from 'sharp';
    import express from 'express';
    import { Request, Response } from 'express';
    
    const app = express();
    
    app.get('/:image', async (req: Request, res: Response) => {
      const image = req.params.image;
    
      if (!image) {
        return res.status(400).send('Image parameter is required');
      }
    
      if (!image.match(/\.(jpg|jpeg|png|gif)$/)) {
        return res.status(400).send('Image must be a JPG, JPEG, PNG, or GIF file');
      }
    
      const imageBuffer = await sharp(`images/${image}`)
        .resize(200, 200)
        .toBuffer();
    
      res.writeHead(200, {
        'Content-Type': `image/${image.split('.').pop()}`,
        'Content-Length': imageBuffer.length,
      });
    
      res.end(imageBuffer);
    });
    
    app.listen(3000, () => {
      console.log('Server started on port 3000');
    });
    
  4. 最后,我们需要为我们的应用程序添加一个 images 文件夹,并将我们的图片文件放入其中。

    |-index.ts
    |-images
      |-example.jpg
    

现在我们的应用程序已准备就绪。我们可以通过访问 http://localhost:3000/example.jpg 来测试我们的应用程序。如果一切正常,你将看到一个调整大小为 200x200 像素的图片。

结论

在这个例子中,我们学习了如何在 Node.js 中使用 TypeScript 处理 URL 中的图像以及如何使用 sharp 库来处理图像。我们还学习了如何使用 express 来构建我们的应用程序,并编写一个简单的路由处理程序来处理从客户端请求的 URL。

现在,你已经准备好在自己的应用程序中使用这些技术了。