Operating System Interruption In Express JS

Operating System Interruption In Express JS

Knowledge Transfer - NODE JS

Basic Definition

In an Express application, an OS interruption refers to an event that interrupts the normal execution of the application due to an external factor related to the operating system or the underlying hardware.

These interruptions can occur for various reasons, such as system signals, hardware failures, or operating system events.

Reasons For Interruption

  1. Signals: The operating system can send signals to the Express application, such as SIGINT (interrupt signal) or SIGTERM (termination signal). User actions usually trigger these signals, like pressing Ctrl+C in the terminal. The Express app can listen for these signals and perform cleanup tasks or gracefully shut down the server when received.

  2. System Events: The operating system may generate events that can impact the Express app. For instance, low memory conditions, disk space shortages, or network interruptions can affect the app's execution. The app can handle these events by implementing error-handling mechanisms, logging, or taking appropriate actions to mitigate the impact.

  3. Hardware Failures: Hardware failures, such as power outages or network failures, can interrupt the Express app's operation. In such cases, the app may need to handle these failures gracefully, attempt to recover from the failure or communicate the issue to the users or administrators.

Handling Interruptions

The following code can be used to handle the basic OS Interruption

const express = require('express')
const app = express()
const PORT = 8080

// create a server and pass the PORT
const server = app.listen(PORT, () => {
    console.log('App running on ' + PORT)
})

// function for handling shutdown
const handleShutdown = () => {
    console.log('Shutting down Gracefully')
    server.close(() => {
        console.log('Express Server Closed')
        process.exit(0)
    })
}

// Capture OS interrupt signals
process.on('SIGINT', handleShutdown);
process.on('SIGTERM', handleShutdown);

Note -

Please note that the following code will only work for the express app.
To use Express, you need to first install Express using the following command.

npm install express --save

Ending Note

OS interruption is one of the most ignored topics in web development. A developer needs to understand what an OS interruption is and why it is required and a fallback condition, in case the OS interruption occurs.

Did you find this article valuable?

Support Sandeep Rana by becoming a sponsor. Any amount is appreciated!