How to send a pdf file from Node/Express app to the browser

Here's the easiest way:

app.get('/', (req, res) => res.download('./file.pdf'))

If this gives you trouble. Check the Express.js version or any middlewares that might be necessary.

Cheers


You have to pipe from Readable Stream to Writable stream not the other way around:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
file.pipe(res);

Also you are setting encoding in wrong way, pass an object with encoding if needed.


I think I found your answer in another post Display PDF file in a browser using node js.

After testing your code in Chrome, it immediately starts the download of the PDF file. But if you want to display the content of the PDF file you could try below:

var data =fs.readFileSync('./public/modules/datacollectors/output.pdf');
res.contentType("application/pdf");
res.send(data);

This should directly send PDF content into the browser.

Hope this answers your question.