Node.js reacts to events (Reactor Pattern), like so it runs on an event-driven model containing: 1) Event Demultiplexer (accepts an I/O request and routes it to the correct OS Low Level hardware and registers a callback handler on the Event Queue (*phase 4 - POLL)) 2) Event Queue (the orchestrator of Node.js) The Event Queue is a FIFO. Node.js keeps looping throught the queue (1,2,3,4,5,6 phases) until there are messages to be processed. Like so, the Event Loop is a single threaded and semi-infinite loop. Diagram of Node.js Event Loop (the heart of Node.js) Based on: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ *If you want to share this diagram, please refer to this post.
The Event Loop contains 6 stacks processed in sequence. Each stack is processed as a FIFO. Event Loop Diagram (6 phases)
↣↣ start the loop ↣↣
┌───────────────────────────┐ ┌─>│ 1 expired timers FIFO │ setTimeout(), setInterval() callbacks │ └─────────────┬─────────────┘ | ▼ │ ┌────────┴────────┐ ┌────────────────────────────────┐ │ │ nextTick | >> | MicroTasks, resolved Promises) | │ └────────┬────────┘ └────────────────┬───────────────┘ | | <─────────────────────────────| | ▼ │ ┌─────────────┴─────────────┐ │ │ 2 pending callbacks FIFO │ I/O callbacks │ └─────────────┬─────────────┘ | ▼ │ ┌────────┴────────┐ ┌────────────────────────────────┐ │ │ nextTick | >> | MicroTasks, resolved Promises) | │ └────────┬────────┘ └────────────────┬───────────────┘ | | <─────────────────────────────| | ▼ │ ┌─────────────┴─────────────┐ │ │ 3 idle, prepare FIFO │ INTERNAL USE ONLY │ └─────────────┬─────────────┘ | ▼ │ ┌────────┴────────┐ ┌────────────────────────────────┐ │ │ nextTick | >> | MicroTasks, resolved Promises) | │ └────────┬────────┘ └────────────────┬───────────────┘ | | <─────────────────────────────| | ▼ │ ┌─────────────┴─────────────┐ │ │ 4 poll FIFO │ retrieve new I/O events; execute I/O related callbacks │ └─────────────┬─────────────┘ | ▼ │ ┌────────┴────────┐ ┌────────────────────────────────┐ │ │ nextTick | >> | MicroTasks, resolved Promises) | │ └────────┬────────┘ └────────────────┬───────────────┘ | | <─────────────────────────────| | ▼ │ ┌─────────────┴─────────────┐ │ │ 5 immediates check FIFO │ setImmediate() callbacks │ └─────────────┬─────────────┘ | ▼ │ ┌────────┴────────┐ ┌────────────────────────────────┐ │ │ nextTick | >> | MicroTasks, resolved Promises) | │ └────────┬────────┘ └────────────────┬───────────────┘ | | <─────────────────────────────| | ▼ │ ┌─────────────┴─────────────┐ └──┤ 6 close callbacks FIFO │ Special callbacks, eg: socket.on('close', ...) └───────────────────────────┘
↢↢ exit the loop ↢↢
Created on 2/17/2019