Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
A standard for error handling and graceful shutdown of Node/Express server

Below is a basic script I usually use for my express servers. Specifically, I am looking for answers to the following questions: Is it needed to include SIGINT and SIGTERM process signal handlers in production? Do I need to actually include an uncaught exception handler? What about tracking and cleaning up sockets? Do I use process.exit(), process.exit(0), or process.exit(1), and if so, where exactly and why?

var express = require('express');
var sockets = [];
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
var port = 7000;
var app = express();
var server = app.listen(port, function () {
    console.log(`app listening on port ${port}`);
})
.on("connection", onConnection)
.on("listening", onListening)
.on("error", onError)
.on("close", onClose);


var cleanup = function () {
    server.close(function () {
        console.log("Closed out remaining connections.");
        process.exit();
    });
    sockets.forEach(function (socket) {
        socket.destroy();
    });

    setTimeout(function () {
        console.log("Could not close connections in time, forcing shut down");
        process.exit(1);
    }, 30 * 1000);
}

function onConnection(socket) {
  sockets.push(socket);
}

function onError(error) {
  if (error.syscall !== 'listen') throw error;

  var bind = typeof port === 'string'? 'Pipe ' + port : 'Port ' + port;

  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'? 'pipe ' + addr : 'port ' + addr.port;
  console.log('Listening on ' + bind);
}
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!