31

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

2
  • Why don't use res.sendFile method?
    – vanadium23
    Commented May 13, 2015 at 11:38
  • 1
    cause I don't have the file : I get this binary content from another WebService. Eventually, I can create a temp file and use sendFile...
    – Varkal
    Commented May 13, 2015 at 12:12

2 Answers 2

57

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'));
};
8
  • 1
    Slight typo. It should be: res.end(new Buffer(data), 'binary') Commented Dec 14, 2017 at 14:00
  • 1
    keep in mind that new Buffer() is deprecated and it have security issues.
    – Idan Dagan
    Commented Feb 18, 2018 at 17:11
  • 2
    @realtebo you can use Buffer.from() - see Node.js docs for more examples.
    – Idan Dagan
    Commented Jan 5, 2019 at 14:23
  • 4
    new Buffer() is deprecated, use Buffer.from() instead.
    – Seybsen
    Commented Jul 18, 2019 at 9:16
  • 1
    why use Buffer.from when data is binary, isn't that reserved for strings? wouldn't you have to use Buffer.alloc?
    – Prav
    Commented Jan 29, 2020 at 19:34
35

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.

4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.