title: NodeJS & express catch write function of HTTP module using a Promise
body: <p>I am writing an express application using </p>
  
  <ul>
  <li>NodeJS v8</li>
  <li>express (latest version) </li>
  </ul>
  
  <p>After looking at the <a href="https://github.com/jshttp/on-headers/blob/2e844930550c913c6411250cdf2fed66570477f0/index.js#L24" rel="nofollow noreferrer">onHeaders</a> module and finding out how the module rewrites the HTTP head, I wanted to make use of that function of JavaScript.</p>
  
  <p>I wanted to write a small session system using my SQL server. I am aware of the <code>session</code> module from express, but this module is not able to handle the specific tables and customization, I need. 
  For convenience reasons I wanted the session to be inserted into the request before the controllers and saved after all controllers finished. (e.g. the writeHead method has been called) </p>
  
  <p>My code in the session looks like: </p>
  
  <pre><code>    core = async function(req, res, next) {
          res.writeHead = hijackHead(res.writeHead);         // Hijack the writeHead method to apply our header at the last
      }
  
      //[...](Omitted code)
  
      hijackHead = function(writeFunction) {
          let fired = false;
  
          return function hackedHead(statusCode) {
              if ( fired ) {
                  return;
              }
  
      //[...](Omitted code)
  
              debug("Session data has changed. Writing");
              sessionManager.storeSessionData(session.identifier, session).then(() =&gt; { // Promise taking ~60ms to resolve 
                  debug("Finished writing...");
                  callMe(); // Current idea of calling the writeHead of the original res 
              });
  
  
  
              let that = this,     // Arguments to apply to the original writeHead
                  args = arguments
  
              function callMe() {
                  debug("Finished! Give control to http, statuscode: %i", statusCode);
                  writeFunction.apply(that, args);  // Call the original writeHead from the response
                  debug("Sent!")
              }
         } // End of hackedHead
      } // End of hijackHead 
  </code></pre>
  
  <p>The core function is being passed to express as a middleware.
  Additionally <code>sessionManager.storeSessionData</code> is a Promise storing data and fulfilling after that, taking ~60ms. The Promise has been testes and works perfectly.
  When I now make a request using this Controller, the Node <code>net</code> Module returns the error: </p>
  
  <pre><code>TypeError: Invalid data, chunk must be a string or buffer, not object
      at Socket.write (net.js:704:11)
      at ServerResponse._flushOutput (_http_outgoing.js:842:18)
      at ServerResponse._writeRaw (_http_outgoing.js:258:12)
      at ServerResponse._send (_http_outgoing.js:237:15)
      at write_ (_http_outgoing.js:667:15)
      at ServerResponse.end (_http_outgoing.js:751:5)
      at Array.write (/usr/lib/node_modules/express/node_modules/finalhandler/index.js:297:9)
      at listener (/usr/lib/node_modules/express/node_modules/on-finished/index.js:169:15)
      at onFinish (/usr/lib/node_modules/express/node_modules/on-finished/index.js:100:5)
      at callback (/usr/lib/node_modules/express/node_modules/ee-first/index.js:55:10)
  </code></pre>
  
  <p>Since the new function needs about 30ms to react and return the Promise, the function finishes earlier causing Node to crash. 
  I already tried blocking the Node loop with a while, timeout or even a recursive function. Neither of them worked. </p>
  
  <p>I tries to simplfy the code as much as possible and I hope that I didn't simplify it too much.</p>
  
  <p>Now I am asking if anybody can help me, how to call the <code>writeHead</code> function properly after the Promise has resolved?</p>