Node / Express服务器的错误处理和正常关闭的标准

时间:2017-04-24 20:08:12

标签: node.js express error-handling server shutdown

以下是我通常用于快速服务器的基本脚本。具体来说,我正在寻找以下问题的答案:是否需要在生产中包含SIGINT和SIGTERM过程信号处理程序?我是否需要实际包含未捕获的异常处理程序?跟踪和清理插座怎么样?我是否使用process.exit(),process.exit(0)或process.exit(1),如果是,那么究竟在哪里以及为什么?

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);
}

0 个答案:

没有答案