29

I try to return some binary data with Express. In the example, it's a PDF but theorically, this can be any sort of file.

But focus on the pdf for the moment. I wrote this code :

app.get('*', function (req, res) {
    getBinaryData(req.url,
        function (answer) {
            res.type('pdf');
            res.end(new Buffer(answer, 'binary'));
        },
        function (error) {
            res.setHeader('Content-Type', 'text/plain');
            return res.end(error);
        }
    );
});

Based on what I saw here : https://github.com/strongloop/express/issues/1555

But, i get a pdf file with the right number of pages, right title.... but all the pages are blank

I'm sure concern the return of getBinaryData(), because this function asked an external Web Service and when I asked directly this service, I got the right document.

Thank you in advance for your answers

Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57
Varkal
  • 1,336
  • 2
  • 16
  • 31

2 Answers2

56

Here is my slightly cleaned up version of how to return binary files with Express. I assume that the data is in an object that can be declared as binary and has a length:

exports.download = function (data, filename, mimetype, res) {
    res.writeHead(200, {
        'Content-Type': mimetype,
        'Content-disposition': 'attachment;filename=' + filename,
        'Content-Length': data.length
    });
    res.end(Buffer.from(data, 'binary'));
};
Michael Shopsin
  • 2,055
  • 2
  • 24
  • 43
34

I found a more simple solution :

request(req.url).pipe(res);

This pipes the original response from distant Web Service directly to my response! I got the correct file regardless of the file type.

Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
Varkal
  • 1,336
  • 2
  • 16
  • 31
  • 1
    I tried same thing but it's not working for me. http://stackoverflow.com/questions/37517312/issue-while-requesting-a-fileimage-pdf-excel-sheet-from-server-and-then-pipe-t – dark_shadow May 30 '16 at 12:38
  • 8
    In what library does request lib reside for request(req.url).pipe(res)? – Nickolodeon Jun 08 '18 at 16:21
  • 2
    For everyone wondering what library `request` comes from, it's a built in node module, so just add `const request = require('request');` before the call. – Dan Sterrett Dec 15 '21 at 21:50