3

I'm just learning Node.js and am confused about (at least) one thing. It appears that Node.js has no problem servicing multiple requests that upload or download large files. Each request might take minutes to complete. Why is it that the event loop is not frozen while one of these requests is being serviced?

-brian

bjlevine
  • 873
  • 1
  • 9
  • 23

1 Answers1

3

In Node.js even if you work only on a single thread, at the OS level it uses async non-blocking events. That means that the task of writing/reading the buffer is multiplexed with other events from other connections.

If you noticed the IncomingMessage implements ReadbleStream http://nodejs.org/api/http.html#http_http_incomingmessage

That's because it doesn't read all the data of once, it reads blocks. Each block of data from the HTTP request will be sent to you as an event which you have to handle.

The event loop is not frozen cause async read from a file or a socket is a service provided by the OS. You tell the OS you want to read a file and you can check from time to time how many bytes have bean read from that file, or if the whole file has bean read (loaded into memory). These async functions are provided by the OS in our days because the reading of a file or from a socket is usually slower than reading from RAM or cache. So while your process keeps doing other tasks, the OS will have a thread which takes care of the reading.

Avner Solomon
  • 1,486
  • 11
  • 17