从 Express.js 中的 UInt8Array 发送二进制响应

fra*_*pps 4 javascript rest http node.js typescript

我正在将 Express.js 与 Typescript 结合使用,我想将 UInt8Array 作为二进制数据发送。

这是我到目前为止使用的并且它有效,但我不想之前保存文件,因为我认为它浪费性能:

const filePath = path.resolve(__dirname, 'template.docx');
const template = fs.readFileSync(filePath);
const buffer: Uint8Array = await createReport({
  template,
  data: {
    productCode: data.productCode,
  },
});
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buffer);
res.sendFile(path.resolve(__dirname, 'output.docx'));
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我正在使用 docx-templates 生成文件。

Ter*_*nox 5

您可以使用PassThrough流来实现此目的,它将文件保留在内存中,而不需要写入磁盘。

像这样的事情应该这样做:

    const stream = require("stream");
    const readStream = new stream.PassThrough();

    // Pass your output.docx buffer to this
    readStream.end(buffer);
    res.set("Content-disposition", 'attachment; filename=' + "output.docx");
    res.set("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    readStream.pipe(res);
Run Code Online (Sandbox Code Playgroud)

完整的node.js代码:

const fs = require("fs");
const express = require("express");
const port = 8000;
const app = express();
const stream = require("stream");

app.get('/download-file', (req, res) => {
    const buffer = fs.readFileSync("./test.docx");
    console.log("/download-file: Buffer length:", buffer.length);
    
    const readStream = new stream.PassThrough();
    readStream.end(buffer);
    res.set("Content-disposition", 'attachment; filename=' + "test.docx");
    res.set("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    readStream.pipe(res);
});

app.listen(port);
console.log(`Serving at http://localhost:${port}`);
Run Code Online (Sandbox Code Playgroud)

要进行测试,请将“test.docx”文件添加到同一目录,然后将浏览器指向 http://localhost:8000/download-file