Send binary response from UInt8Array in Express.js

Viewed 1394

I am using Express.js with Typescript and I would like to send a UInt8Array as binary data.

This is what I use so far and it works, but I would like not to save the file before, because I think it wastes performance:

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'));

I am using docx-templates to generate the file by the way.

1 Answers

You can use a PassThrough stream for this purpose, it'll keep the file in memory with no need to write to disk.

Something like this should do it:

    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);
Related