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

将pdfkit生成的PDF通过管道传输到Fastify时下载空文档的问题排查

问题原因

你直接把PDFKit的流pipe到reply.raw,但Fastify的响应机制没正确识别流的完成状态,导致响应提前结束,所以下载的PDF是空文件。而用fs.createWriteStream时,文件系统流能正确处理结束事件,生成的PDF就是完整的。

修复方案

把doc.pipe(reply.raw)换成reply.send(doc)就行。Fastify的send方法原生支持处理可读流,会自动搞定流的传输、结束和错误,保证PDF内容完整输出:

import PDFDocument from 'pdfkit'

const downloadPdfRoute = async (app) => {
    app.get('/download/:filename', async (req, reply) => {
        const doc = new PDFDocument()

        reply.type('application/pdf')
        reply.header(
            'content-disposition',
            `attachment; filename="${req.params.filename}"`
        )

        // 用reply.send替代pipe,交给Fastify处理流
        reply.send(doc)

        doc.text('Hello, this is your PDF content.')
        doc.end()
    })
}

export default downloadPdfRoute
补充说明

要是你非得用reply.raw,得手动监听流的finish事件来结束响应,但这种方式不如直接用reply.send省心:

doc.pipe(reply.raw)
doc.on('finish', () => {
    reply.raw.end()
})

还是优先用reply.send(doc),这是Fastify处理流响应的标准方式,能避免手动管理响应生命周期踩坑。

内容的提问来源于stack exchange,提问作者user4893295

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:45:09