Event Loop: Continuous Task Processing in Node.js

If you have a server running with code that listens on a specific port, you might wonder why the process doesn’t terminate on its own. The event loop keeps running, tasks are added to the queue, but how can we tell the process to move to the next iteration?

When you start a server in Node.js or any other asynchronous environment, the process doesn’t terminate by itself because the server is actively listening on a port and waiting for incoming connections or events.

Here are the key reasons why the process continues running:

1. Listening on a Port:
When you create a server, for example using http.createServer in Node.js, the server starts listening for incoming network connections on a specific port. This means the server is waiting for client requests and will not shut down until it is explicitly stopped. The listener on the port prevents the process from ending because it keeps handling incoming requests and events.

2. Event Loop:
JavaScript and Node.js use an event loop that ensures asynchronous code execution. The event loop keeps running, processing events and tasks in the task queue. Since the server is waiting for incoming connections and processing requests, the event loop remains active, and the process won’t terminate as long as the loop is running.

3. Handling Asynchronous Tasks:
Asynchronous operations like client requests or timers add tasks to the task queue. As long as there are tasks in this queue or active event handlers, the event loop will continue to run, keeping the process alive.

4. Example of Server in Action:

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!\n');
});

server.listen(3000, () => {
    console.log('Server is listening on port 3000');
});

In this example:
• The server starts and listens on port 3000.
• The server handles incoming requests and sends back the response “Hello, World!”.
• As long as the server is running and handling requests, the event loop stays active, and the Node.js process won’t terminate.

5. Stopping the Process:
If you want to stop the process, you need to explicitly stop the server and free up resources. In Node.js, you can call the server.close() method to stop the server from processing further requests:

server.close(() => {
    console.log('Server has been stopped');
});

Thus, the server and asynchronous operations keep the process alive because they continuously wait for and handle events, allowing the process to keep running until explicitly stopped.