How Nodejs Work?
- First, Node.js reads and parses the JavaScript code written by the developer.
- When Node.js encounters an asynchronous operation, such as reading data from a file or making a network request, it sends that operation to the operating system's kernel to be executed asynchronously.
- While the asynchronous operation is being executed, Node.js continues to run other code in the program instead of blocking the entire program until the operation is complete.
- Once the asynchronous operation is complete, Node.js adds the result to an event queue to be processed later.
- Node.js then enters the event loop, which constantly checks the event queue for new events to process.
- If there are any events in the queue, the event loop will execute the associated callback function, which was defined by the developer when the asynchronous operation was initiated.
- The event loop will continue to process events until the queue is empty or the program is terminated.
- During all of this, Node.js uses a single-threaded model to handle multiple simultaneous connections efficiently by using non-blocking I/O and the event loop.