typescript NestJS流文件技术不起作用

jtoj6r0c  于 2023-01-03  发布在  TypeScript
关注(0)|答案(2)|浏览(209)

我正在尝试使用NestJS Streaming Files technique流式传输CSV文件,但请求似乎被卡住了。我错过了什么吗?
示例代码片段:

import {StreamableFile} from '@nestjs/common';
import * as fs from 'fs';

@Get('csv')
csvStream(
  @Req() req: Request,
  @Res() res: Response,
): StreamableFile {
  const file = 'test.csv';
  const readStream = fs.createReadStream(file);
  readStream.on('data', (chunk) => console.log(chunk));  <--- the data log gets printed
  readStream.on('finish', () => console.log('done'));
  return new StreamableFile(readStream);
}

打印数据日志(检查语句-readStream.on('data', (chunk) => console.log(chunk))),输出如下所示:

<Buffer 23 4a 45 67 11 97 ... 1022 more bytes>

并且请求停留在该状态。

7ivaypg9

7ivaypg91#

以下对我很有效,在本地......

import { Controller, Get, Req, Response, StreamableFile } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

@Controller()
export class FileController {
    @Get('csv')
    csvStream(@Req() req, @Response({ passthrough: true }) res): StreamableFile {
        res.set({
            'Content-Type': 'text/plain'
        });

        const file = path.join(__dirname, 'test.csv');
        const readStream = fs.createReadStream(file);
        readStream.on('data', (chunk) => console.log(chunk)); // <--- the data log gets printed
        readStream.on('end', () => console.log('done'));
        readStream.on('error', (err) => { console.error(err); });

        return new StreamableFile(readStream);
    }
}

请注意{ passthrough: true }。这是我得到回复的原因,所以看起来很重要!!!

efzxgjgh

efzxgjgh2#

{ passthrough: true }是必需的,因为StreamableFile是一个自定义对象,因此需要显式地将其传递给下一个中间件--它不负责向客户机发送响应。

相关问题