Câu hỏi phỏng vấn Nodejs
Câu hỏi

How to gracefully shu...

Câu trả lời

To gracefully shut down a Node.js server, you need to handle the appropriate system signals and ensure that all ongoing tasks are completed and resources are properly released before the server process exits. Here’s a step-by-step guide on how to implement a graceful shutdown in a Node.js application:

1. Listen for Shutdown Signals

Node.js can listen for system signals like SIGINT and SIGTERM. These signals are used to indicate that the Node.js process should terminate. SIGINT is typically sent when the user presses CTRL+C in the terminal, and SIGTERM is sent by process managers like Kubernetes or Docker to gracefully stop a process.

javascript Copy
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

2. Define the Graceful Shutdown Function

Create a function called gracefulShutdown that will handle the cleanup tasks necessary before shutting down the server. This function should close all active connections, save any final data needed, and perform any other cleanup tasks.

javascript Copy
function gracefulShutdown() {
    console.log('Received kill signal, shutting down gracefully.');
    server.close(() => {
        console.log('Closed out remaining connections.');
        process.exit(0);
    });

    // Set a timeout to forcefully shut down after 10 seconds
    setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
    }, 10000);
}

3. Implement Server Close Logic

In the gracefulShutdown function, use the server.close() method to stop the server from accepting new connections. This method also waits for all existing connections to finish before the callback function is executed.

4. Handling Edge Cases

Ensure that your shutdown process ...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

Is an Event Emitter synchronous or asynchronous?

expert

How many threads does Node actually create ?

junior

What is Callback?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào