const express = require('express'); const app = express(); const server = app.listen(3000, () => console.log('Server started')); process.on('SIGINT', () => { console.log('SIGINT received'); server.close(() => { console.log('Server closed'); process.exit(0); }); });
When Ctrl+C is pressed, SIGINT is caught first, logging 'SIGINT received'. Then server.close() stops the server and calls its callback, logging 'Server closed'. The process then exits.
Option A correctly passes a function to process.on that calls server.close with a callback. Option A calls server.close immediately, not on signal. Option A passes the result of server.close instead of a function. Option A does not call server.close properly.
const express = require('express'); const app = express(); const server = app.listen(3000); process.on('SIGINT', () => { console.log('SIGINT caught'); server.close(); console.log('Server closed'); });
server.close() stops accepting new connections but is asynchronous. Without calling process.exit() or waiting for the close callback, the process stays alive.
const express = require('express'); const app = express(); const server = app.listen(3000); const connections = new Set(); server.on('connection', (conn) => { connections.add(conn); conn.on('close', () => connections.delete(conn)); }); // Simulate client connect and disconnect const net = require('net'); const client = net.createConnection({ port: 3000 }, () => { client.end(); });
The connection is added on 'connection' event, then removed on 'close' event when the client disconnects. After disconnect, the Set is empty.
Tracking open connections allows the server to finish handling requests and close connections cleanly, preventing clients from experiencing abrupt disconnections or hanging requests.