Error: write after end
at writeAfterEnd (_stream_writable.js:167:12)
at Socket.Writable.write (_stream_writable.js:212:5)
at Socket.write (net.js:624:40)
at Socket.<anonymous> (/Users/julien/Temp/foo.js:14:12)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:529:20)

As you can see, the firsts 2 requests are fine, but the 3rd one is cut into 2 distinct parts. The headers of the request would be in one data event, and the body in an other.

I discussed this with few developers and we guess it could be related to the TCP stack of my OS, which is OSX Sierra if that could matter.

I couldn't see any other way to patch it than accumulating the buffer into a variable declared in an upper scope, then use an ugly timer trick which end up something similar to a cancellable setImmediate.

That's just how TCP works. TCP is a stream of bytes. There are no packets with boundaries (or even requests) on application layer. A write call for n-bytes on one end of the connection could lead up to n 1-byte read calls on the other end. You have to be prepared that each read yields an arbitrary amount of bytes (up to the buffer size given to the read call - however as you get data pushed in node.js you can't influence that). If you need packets on application level you need to handle that yourself, e.g. by writing length-prefixed packets to the stream.

However HTTP does not require the notion of packets since it's already defined by the HTTP protocol where a header and the body ends.