Koko
Koko

Reputation: 131

Continuously send a response to client

Is there a way, I could continuously send a response to the client before finally calling end on the response object?

There is a huge file and I want to read,parse and then send the analysis back to the client. Is it possible that I keep sending a response as soon as I read a line?

response.send also calls end, so I cannot use it.

Upvotes: 2

Views: 2661

Answers (2)

apsillers
apsillers

Reputation: 116020

You want to use res.write, which sends response body content without terminating the response:

This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.

Note that write is not included in the Express documentation because it is not an Express-specific function, but is inherited from Node's core http.ServerResponse, which Express's response object extends from:

The res object is an enhanced version of Node's own response object and supports all built-in fields and methods.

However, working with streaming data is always little tricky (see the comment below warning about unexpected timeouts), so it may be easier to restructure your application to send streaming data via a WebSocket, or socket.io for compatibility with browsers that don't support WebSockets.

Upvotes: 2

Frank Malenfant
Frank Malenfant

Reputation: 146

What kind of server side application are you working with? You could use Node.js with Socket.IO to do something like this. Here's some useful links.

First Node.js application

Node.js readline API

Upvotes: 1

Related Questions