Events
Events
• The Node.js event model of using the event callbacks is great until
you run into the problem of functions that block waiting for I/O.
Blocking I/O stops the execution of the current thread and waits for a
response before continuing.
Some examples of
• blocking I/O are
• Reading a file
• Querying a database
• Socket request
• Accessing a remote service
Node.js event model
Node.js event model
• Figure illustrates the full Node.js event model including the
• Event queue,
• Event loop,
• and the thread pool.
• Notice that the event loop either executes the function on the event
loop thread itself or, for blocking I/O, it executes the function on a
separate thread.
Node.js event model
• Figure In the Node.js event model, work is added as a function with
callback to the event queue, and then picked up on the event loop
thread.
• The function is then executed on the event loop thread in the case of
non-blocking, or on a separate thread in the case of blocking
• Node.js uses event callbacks is not to have to wait for blocking I/O.
• Therefore, any requests that perform blocking I/O are performed on a
different thread in the background. Node.js implements a thread pool
in the background.
• When an event that requires blocking I/O is retrieved from the event
queue, Node.js retrieves a thread from the thread pool and executes
the function there instead of on the main event loop thread. This
prevents the blocking I/O from holding up the rest of the events in the
event queue.
• The function executed on the blocking thread can still add events
back to the event queue to be processed. For example, a database
query call is typically passed a callback function that parses the results
and may schedule additional work on the event queue before sending
a response.
Adding Work to the Event
Queue
• As you create your Node.js applications, keep in mind the event
model
• To leverage the scalability and performance of the event model, make
sure that you break work upinto chunks that can be performed as a
series of callbacks.
• Once you have designed your code correctly, you can then use the
event model to schedule work on the event queue.
• In Node.js applications, work is scheduled on the event queue by
passing a callback function using one of these methods:
1. Make a call to one of the blocking I/O library calls such as writing to
a file or connecting to a database.
2. Add a built-in event listener to a built-in event such as an
http.request or server.connection.
3. Create your own event emitters and add custom listeners to them.
4. Use the process.nextTick option to schedule work to be picked up
on the next cycle of the event loop.
5. Use timers to schedule work to be done after a particular amount of
time or at periodic intervals.
Implementing Timers