title: ExpressJS and PDFKit - generate a PDF in memory and send to client for download
body: <p>In my <code>api</code> router, there is a function called <code>generatePDF</code> which aims to use PDFKit module to generate a PDF file in memory and send to client for download instead of displaying only.</p>
  
  <p>In <code>api.js</code>:</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  
  const PDFDocument = require('pdfkit');
  
  router.get('/generatePDF', async function(req, res, next) {
      var myDoc = new PDFDocument({bufferPages: true});
      myDoc.pipe(res);
      myDoc.font('Times-Roman')
           .fontSize(12)
           .text(`this is a test text`);
      myDoc.end();
      res.writeHead(200, {
          'Content-Type': 'application/pdf',
          'Content-disposition': 'attachment;filename=test.pdf',
          'Content-Length': 1111
      });
      res.send( myDoc.toString('base64'));
  });
  
  module.exports = router;
  </code></pre>
  
  <p>This does not work. The error message is <code>(node:11444) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client</code>.</p>
  
  <p>How can I go about fixing the issue and getting it work?</p>
  
  <p>Also, a relevant question would be how I can separate the business logic of PDF generation from the router and chain them up?</p>