Search code examples
node.jsexpresshttpresponsefs

how to send a file in response from express


i am currently using pdf-merge to make a duplicate of a file and then send it via express response

PDFMerge([file/appl.pdf], 'pdfappl/policy.pdf').then((mergedPdf) => {
      res.setHeader('correlationid', correlationid);
      res.contentType("application/pdf");
      return res.send(mergedPdf);
})

how can i do it using node's fs module. i got to copy the file using readStream and writeStream, but it is not passing into the response.

const fs = require('fs');
fs.createReadStream('file/appl.pdf').pipe(fs.createWriteStream('pdfappl/policy.pdf')); //copy works

res.setHeader('correlationid', correlationid);
res.contentType("application/pdf");
return res.send(???); // how to send the copied file here

Solution

  • You can stream the file data to the connection with pipe as it's being read

    res.contentType("application/pdf");
    
    var stream = fs.createReadStream(file_path);
        stream.pipe(response);