You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中如何将Buffer转为StreamableFile?类型错误求助

解决StreamableFile接收字符串参数的类型错误问题

问题分析

你遇到的TypeScript类型错误,核心原因是StreamableFile构造函数仅接受Buffer或Node.js Readable流作为参数,但你传入的是字符串类型的filesToPdf。原代码中Buffer.from(filesToPdf, 'utf-8')仅执行了转换操作,却未将结果赋值给变量,导致传入StreamableFile的仍然是原始字符串。

错误提示如下:

法语错误提示:
Aucune surcharge ne correspond à cet appel.
La surcharge 1 sur 2, '(buffer: Buffer): StreamableFile', a généré l'erreur suivante.
L'argument de type 'string' n'est pas attribuable au paramètre de type 'Buffer'.
La surcharge 2 sur 2, '(readable: Readable): StreamableFile', a généré l'erreur suivante.
L'argument de type 'string' n'est pas attribuable au paramètre de type 'Readable'.ts(2769)

英语错误提示:
No overload matches this call.
The 1 of 2 overload, '(buffer: Buffer): StreamableFile', generated the following error.
Argument of type 'string' is not assignable to parameter of type 'Buffer'.
The 2 of 2 overload, '(readable: Readable): StreamableFile', generated the following error.
Argument of type 'string' is not assignable to parameter of type 'Readable'.ts(2769)

修正代码

async FindCommands(@Res({ passthrough: true }) response, @Query() query: DateRangQueryVm): Promise<StreamableFile> {
    const filesToPdf = await this.commandsService.getCommands(query.startDate, query.endDate);
    
    const nommation = `commands.pdf`;

    response.setHeader('Content-Type', `application/pdf`);
    response.setHeader('Content-Disposition', `attachment; filename=${nommation}`);
    
    // 将字符串转换为Buffer并赋值给变量
    const pdfBuffer = Buffer.from(filesToPdf, 'utf-8');
    return new StreamableFile(pdfBuffer);
};

关键要点

  • StreamableFile仅支持Buffer或Readable流作为输入参数,不能直接传入字符串。
  • Buffer.from()方法返回新的Buffer实例,必须将其赋值给变量才能使用,原字符串不会被修改。

官方文档内容翻译(文件流式传输)

NestJS提供StreamableFile类用于实现文件流式传输,它接收Buffer或Readable流作为输入,自动处理响应的流式输出逻辑。使用时可通过@Res()装饰器手动配置响应头,比如设置内容类型、指定下载文件名等。

内容的提问来源于stack exchange,提问作者Black-Badger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:05:32