Express - Return binary data from webservice

51,609

Solution 1

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.

Solution 2

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'));
};
Share:
51,609

Related videos on Youtube

Varkal
Author by

Varkal

I'm a French developper holder of a Master Degree in Computer Science My favourite languages are Python and JS. I've learned some piece of C and C++ at school but i dislike this languages. I don't want to lose time to debate with you on a stupid war like OS/languages war. I really think that every piece of technology exist for a reason and help peoples with their specific needs. Even pieces of tech I personally dislike. There is no perfect tool. There is a right tool for a right job. I think we can built a better world with technology : make peoples life easier by offloading from basic and repetitive tasks and by distract them with cool stuff like video games and social networks I love my job so much ! :-)

Updated on October 02, 2020

Comments

  • Varkal
    Varkal over 3 years

    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

    • vanadium23
      vanadium23 about 9 years
      Why don't use res.sendFile method?
    • Varkal
      Varkal about 9 years
      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...
  • dark_shadow
    dark_shadow about 8 years
    I tried same thing but it's not working for me. stackoverflow.com/questions/37517312/…
  • Aneil Mallavarapu
    Aneil Mallavarapu over 6 years
    Slight typo. It should be: res.end(new Buffer(data), 'binary')
  • Idan Dagan
    Idan Dagan over 6 years
    keep in mind that new Buffer() is deprecated and it have security issues.
  • Nickolodeon
    Nickolodeon about 6 years
    In what library does request lib reside for request(req.url).pipe(res)?
  • realtebo
    realtebo over 5 years
    @IdanDagan: what could we use instead of new Buffer()?
  • Idan Dagan
    Idan Dagan over 5 years
    @realtebo you can use Buffer.from() - see Node.js docs for more examples.
  • Seybsen
    Seybsen almost 5 years
    new Buffer() is deprecated, use Buffer.from() instead.
  • Prav
    Prav over 4 years
    why use Buffer.from when data is binary, isn't that reserved for strings? wouldn't you have to use Buffer.alloc?
  • NamedArray
    NamedArray almost 3 years
    What is the significance of using .end() instead of .send() with these examples?
  • Michael Shopsin
    Michael Shopsin almost 3 years
    @NamedArray .end() makes sure the connection is closed after the file is sent. .send() leaves the connection open using up a TCP socket.
  • Dan Sterrett
    Dan Sterrett over 2 years
    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.