Lưu ý Chương này trình bày cách bạn có thể streaming file từ HTTP application. Các ví dụ dưới đây không áp dụng cho ứng dụng GraphQL hoặc Microservice.
Có những lúc bạn muốn trả về một file từ REST API cho client. Để làm điều này với Nest, thông thường bạn sẽ làm như sau:
@Controller('file')
export class FileController {
@Get()
getFile(@Res() res: Response) {
const file = createReadStream(join(process.cwd(), 'package.json'));
file.pipe(res);
}
}
Nhưng làm theo cách này thì bạn sẽ mất khả năng dùng interceptor logic chạy sau controller (post-controller interceptor). Để xử lý vấn đề này, bạn có thể trả về một instance của StreamableFile và bên dưới, framework sẽ tự lo việc pipe response.
Ghi chú người dịch Cũng giống Express, nếu bạn tự res.pipe() như đoạn code trên, response coi như đã được gửi trực tiếp qua tay bạn — interceptor đăng ký ở tầng NestJS (transform response, logging response, v.v.) sẽ không có cơ hội can thiệp vào dữ liệu trả về, vì Nest không còn kiểm soát response nữa. Trả về StreamableFile giúp bạn giữ được luồng xử lý chuẩn của Nest (qua interceptor) mà vẫn stream được file.
Class StreamableFile (Streamable File class)
StreamableFile là một class giữ (hold) stream sẽ được trả về. Để tạo một StreamableFile mới, bạn truyền vào constructor của StreamableFile một Buffer hoặc một Stream.
Gợi ý Class StreamableFile có thể import từ @nestjs/common.
Hỗ trợ đa nền tảng (Cross-platform support)
Fastify, theo mặc định, đã hỗ trợ gửi file mà không cần gọi stream.pipe(res), nên bạn không cần dùng class StreamableFile chút nào khi dùng Fastify. Tuy nhiên, Nest hỗ trợ dùng StreamableFile trên cả hai loại nền tảng, nên nếu sau này bạn chuyển đổi qua lại giữa Express và Fastify thì cũng không cần lo về tính tương thích giữa hai engine.
Ghi chú người dịch Đây là một ví dụ điển hình của triết lý “platform-agnostic” trong Nest: cùng một đoạn code business logic (trả về StreamableFile) chạy được trên cả Express và Fastify, dù cơ chế xử lý stream bên dưới của hai adapter khác nhau. Nếu bạn viết code phụ thuộc trực tiếp vào res của Express (như ví dụ đầu bài), code đó sẽ không chạy đúng khi đổi sang Fastify.
Ví dụ (Example)
Bạn có thể xem một ví dụ đơn giản về việc trả package.json như một file thay vì JSON dưới đây, nhưng ý tưởng này áp dụng tự nhiên cho hình ảnh, tài liệu, và bất kỳ loại file nào khác.
import { Controller, Get, StreamableFile } from '@nestjs/common';
import { createReadStream } from 'node:fs';
import { join } from 'node:path';
@Controller('file')
export class FileController {
@Get()
getFile(): StreamableFile {
const file = createReadStream(join(process.cwd(), 'package.json'));
return new StreamableFile(file);
}
}
Content type mặc định (giá trị của header response HTTP Content-Type) là application/octet-stream. Nếu bạn cần tùy chỉnh giá trị này, bạn có thể dùng option type của StreamableFile, hoặc dùng method res.set hoặc decorator @Header(), như sau:
import { Controller, Get, StreamableFile, Res } from '@nestjs/common';
import { createReadStream } from 'node:fs';
import { join } from 'node:path';
import type { Response } from 'express'; // Giả sử chúng ta đang dùng ExpressJS HTTP Adapter
@Controller('file')
export class FileController {
@Get()
getFile(): StreamableFile {
const file = createReadStream(join(process.cwd(), 'package.json'));
return new StreamableFile(file, {
type: 'application/json',
disposition: 'attachment; filename="package.json"',
// Nếu bạn muốn đặt giá trị Content-Length thành một giá trị khác thay vì độ dài của file:
// length: 123,
});
}
// Hoặc thậm chí:
@Get()
getFileChangingResponseObjDirectly(@Res({ passthrough: true }) res: Response): StreamableFile {
const file = createReadStream(join(process.cwd(), 'package.json'));
res.set({
'Content-Type': 'application/json',
'Content-Disposition': 'attachment; filename="package.json"',
});
return new StreamableFile(file);
}
// Hoặc thậm chí:
@Get()
@Header('Content-Type', 'application/json')
@Header('Content-Disposition', 'attachment; filename="package.json"')
getFileUsingStaticValues(): StreamableFile {
const file = createReadStream(join(process.cwd(), 'package.json'));
return new StreamableFile(file);
}
}