2

I'm quite new to nodejs and I'm working on a backend for an Angular 4 application. The problem is that the backend is quite slow to produce the whole data for the response and I'd like to send data over time as soon as it's available. I was reading about RxJS but I can't really figure out how to use it in node, can you please help me?

4
  • 1
    res.write() will send a piece of the response. You can call it as many times as you need to and then call res.end() when done. Commented Aug 24, 2017 at 1:32
  • @jfriend00 what he really needs is get them delivered as soon as available, so res.write(chunk) followed res.flush() to deliver the chunk as soon as the chunks are available, and when ended , then res.end() is performed. Commented Aug 24, 2017 at 10:52
  • I'm now using socket.io and it's working very well! Commented Aug 24, 2017 at 10:55
  • another super nodejs websocket lib is ws npmjs.com/package/ws Commented Aug 24, 2017 at 19:37

1 Answer 1

3

Maybe you are looking for a way to stream the data

Express

Normally you respond with res.send(data), it can be called only once.

If you are reading and sending a large file, you can stream the file data while being read with res.write(chunk) and on the 'end' event of the file reading, you call res.end() to end the response.


EDIT : As you state, what you want is to stream as soon as the chunk is available, so you can use the res.flush() command between writes ( just flush after res.write(chunk)).

It would be much faster in your case but the overall compression will be much less efficient.

Sign up to request clarification or add additional context in comments.

5 Comments

Yeah, but in this way I still receive the data only when the end method is called (all at once)
It will still be much faster than with res.send(data)
In my case some data is available after half a second and some after 5 seconds. Using this method I still get all the data after 5 seconds, which is not what I need
If you want to stream, you can use the res.flush() command between writes, but the compression will be much less efficient.
@lpeppe did you try with res.flush() (as the last edit to my answer mentions) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.