I have a background process which generates lots of output. I want to send the output to client as they become available. My expectation is client will send a HTTP GET/POST request, server opens a connection and keeps it alive
, then server keeps streaming data as they become available.
Real World Example: When you run a test or shell command in AWS/Heroku/GoogleAppEngine, it shows the output in real time, as if the command was running on my local machine. How are they doing that?
Server: In this sample server, the process generates a message every second.
function handleRequest (request, response) {
for (let i = 0; i < 10; i++) {
response.write('This is message.' + i)
require('child_process').execSync("sleep 1")
}
response.end()
}
Client: The client should receive data as they become available i.e. one by one. But the output is of course what I expected, the entire data is collected at once and sent back to the client.
request.put(formData)
.on('data', function (data) {
console.log(data.toString())
})
I am pretty new to NodeJS, but I am hoping maybe I can return some form of
writable stream
back to client, and as data are written to this stream on server side, the client will receive it on its end?