NestJS 流文件技术不起作用
NestJS Streaming Files technique not working
我正在尝试使用 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>
请求停留在这个状态。
以下为我工作,在本地...
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 }
。这就是让我得到回应的原因,所以看起来很重要!!!
我正在尝试使用 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>
请求停留在这个状态。
以下为我工作,在本地...
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 }
。这就是让我得到回应的原因,所以看起来很重要!!!