将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
相关产品推荐
相关产品推荐

