Search code examples
node.jsexpressstreaming

NodeJS: How to send a Buffer in chunks


I'm trying to create an artificially slow-loading image with NodeJS (currently using ExpressJS). I have Buffer containing a base64-encoded image in it, and I'd like to stream chunks of the buffer to the client each separated by a given delay. Is this possible?

I know how to send raw text to the client in chunks, and I know how to send an entire Buffer to the client (both of these with response.write()), but I am not sure how I can break up an image's bytes into chunks and send that to the client incrementally. Is this possible?


Solution

  • You can construct slices from a buffer using buf.subarray(start, end) and send these via response.write.