How to attach a node.js readable stream to a Sendgrid email?

node-pdfkit, node.js, sendgrid

Solution

To use the SendGrid nodejs API with a streaming file, just convert the streaming into a buffer. You can convert a readable stream into a buffer using stream-to-array.

var streamToArray = require('stream-to-array');

streamToArray(your_stream, function (err, arr) {
  var buffer = Buffer.concat(arr)
  sendgrid.send({
    to: email,
    files: [{ filename: 'File.pdf' content: buffer }]
  })
})

Problem

I'm using PDFKit to generate PDFs. I'm using Nodejitsu for hosting, so I can't save the PDFs to file, but I can save them to a readable stream. I'd like to attach that stream in a Sendgrid email, like so: ``` sendgrid.send({ to: email, files: [{ filename: 'File.pdf', content: /* what to put here? */ }] /* ... */ }); ``` I've tried `doc.output()` to no avail.

Original source