Skip to content

Instantly share code, notes, and snippets.

@gabriel-rcpereira
Last active January 24, 2022 13:47
Show Gist options
  • Select an option

  • Save gabriel-rcpereira/fdb7f1af49b0503fa6863b219487c52f to your computer and use it in GitHub Desktop.

Select an option

Save gabriel-rcpereira/fdb7f1af49b0503fa6863b219487c52f to your computer and use it in GitHub Desktop.
Serving a PDF file in memory - NodeJS + Express

How to serving PDF file in memory - NodeJS + Express

To be honest, I googled a lot to learn something to fit in my context and after to consume, to read, and let some hairs on the way(Lol) I found a solution! (Inspired by Al Scoot)

What's the problem?

There are some approaches to serve a PDF file through a Rest Express API, for example download method: send.download(filePath). But when you need to serve a file in memory the problem becomes hard to solve and there aren't many developers talking about it.

The probably(and obvious) solution

  const getPdfFile = async (req, res) => {  
    const { data } = await axios.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');

    res.header('Content-disposition', 'attachment; filename=my-pdf.pdf');
    res.header('Content-Type', 'application/pdf');

    return res.send(data);
  };

The problem is how axios handles the data response. How axios doesn't know what is coming it considers the return as String but in this case, we need a Buffer.

How to solve?

We need to tell axios what's the content it's receiving and after that, the magic happens:

  const getPdfFile = async (req, res) => {  
    const { data } = await axios.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', { responseType: 'arraybuffer' });

    res.header('Content-disposition', 'attachment; filename=my-pdf.pdf');
    res.header('Content-Type', 'application/pdf');

    return res.send(data);
  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment