I am trying to stream CSV file using NestJS Streaming Files technique, but the request seems to be stuck. Am I missing something here?
Sample code snippet:
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);
}
The data log gets printed (check statement - readStream.on('data', (chunk) => console.log(chunk))
), and output is similar to below:
<Buffer 23 4a 45 67 11 97 ... 1022 more bytes>
and the request stays stuck in this state.
Following worked for me, locally...
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);
}
}
Please mind the { passthrough: true }
. That's what made me get a response, so seems quite important!!!