I have problem when try to calculate size of stream file with nestjs and fast-csv lib. This is file service:
import { format } from 'fast-csv';
async export() {
const stream = format({ headers: true });
stream.write(['id', 'first_name', 'last_name', 'is_active']);
let size = 0;
// There is a problem when I add event listener to calculate stream size
// stream.on('data', (chunk) => {
// size += chunk.length;
// });
// stream.on('end', () => {
// console.log(size);
// });
await this.getData(stream)().finally(() => {
stream.end();
});
return stream ? { stream, size } : null;
}
private getData = (stream: Transform) => async () => {
for (let i = 0; i < 1; i++) {
const users = await User.find();
if (users.length === 0) {
break;
}
for (let i = 0; i < users.length; i++) {
const row = users[i];
stream.write([row.id, row.firstName, row.lastName, row.isActive]);
}
}
};
This is file controller:
@Post('export')
async exporrt() {
const data = await this.appService.export();
console.log('size', data.size);
return new StreamableFile(data.stream, {
disposition: `attachment; filename=test.csv`,
type: 'text/csv; charset=utf-8',
});
}
The code run well and below is the result when I call API export

However when I try to calculate stream size with stream's event listener, I can get the size of stream but I got no data in response:

How can I calculate stream size with on('data') or with other solution. Thank for your attention.