Initialization
- Node.js starts the event loop and initializes the environment. This includes loading the required modules, setting up the global objects, and preparing the execution context.
Execution of Scripts
- Node.js executes the provided script or file. It parses the code, executes the top-level code, and sets up event listeners for asynchronous operations.
Event Loop
- The heart of Node.js's asynchronous nature. It processes the events and callbacks generated by asynchronous operations. The event loop runs in cycles, called ticks, and it has several phases:
Event Loop Phases
Timers Phase
- Executes callbacks scheduled by
setTimeout()andsetInterval(). - Node.js checks the timer queue and executes any timer callbacks that are due.
- Executes callbacks scheduled by
Pending Callbacks Phase
- Executes I/O callbacks deferred to the next loop iteration.
- This includes some system operations like TCP errors, which require more time than the timers phase allows.
Idle, Prepare Phase
- Only used internally by Node.js for performing tasks that need to be executed before the poll phase.
- This phase is not directly accessible by developers.
Poll Phase
- The most crucial phase where the event loop retrieves new I/O events.
- Node.js blocks here when waiting for new events, processing I/O callbacks as they arrive.
- When the poll queue is empty, the event loop will either end the poll phase or continue to wait for callbacks.
Check Phase
- Executes callbacks scheduled by
setImmediate(). - Node.js processes all
setImmediate()callbacks, which are often used for breaking up long operations.
- Executes callbacks scheduled by
Close Callbacks Phase
- Executes close event callbacks, such as when a socket or handle is closed.
- This includes cleanup or shutdown functions for resources.
Interaction between Call Stack, Callback Queue, and Event Loop
Call Stack
- Synchronous code execution context.
- Functions are called and executed here in a LIFO (Last In, First Out) order.
- When an asynchronous function is called, it sends the callback to the appropriate queue.
Callback Queue
- Stores callbacks of asynchronous operations.
- Includes queues for different phases (e.g., timer queue, I/O queue, check queue).
Event Loop
- Continuously checks the call stack and the callback queue.
- If the call stack is empty, it picks the next callback from the callback queue and pushes it onto the call stack for execution.
