emptygif
語言: 繁體中文

所有語言和框架

NestJS TypeScript

適用於 NestJS 的 TypeScript 程式碼片段,以空 GIF 回應對 /pixel.gif 的請求,GIF 在啟動時只解碼一次。

NestJS TypeScript

安裝
npm i @nestjs/core @nestjs/common @nestjs/platform-express reflect-metadata rxjs
檔案
main.ts
import { Controller, Get, Header, Module, StreamableFile } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

const GIF = Buffer.from('R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', 'base64');

@Controller()
class PixelController {
  @Get('/pixel.gif')
  @Header('Cache-Control', 'no-store')
  pixel(): StreamableFile {
    // A plain Buffer would be serialised as JSON; StreamableFile sends raw bytes.
    return new StreamableFile(GIF, { type: 'image/gif', length: GIF.length });
  }
}

@Module({ controllers: [PixelController] })
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(8080);
}
bootstrap();

我們執行了這段程式碼,並比對了它回傳的位元組。

驗證

curl -sI http://localhost:8080/pixel.gif

官方網站: NestJS

更多 TypeScript 範例