【问题标题】:Sending http request on node process exit在节点进程退出时发送 http 请求
【发布时间】:2017-08-04 13:16:47
【问题描述】:

我编写了示例节点应用程序来处理错误数据,例如数据库连接错误、端口冲突错误、处理未捕获的异常。当发生错误时,会发出一个 http 请求来处理错误。在这种情况下节点进程异常存在,我可以在process.on('exit')函数中处理存在但我无法发送http请求,进程正在快速退出。

任何人都可以建议如何在进程退出之前发送 http 请求并在 Node.js 上获取响应。下面是在存在的进程上发送http请求的示例代码

var http = require('http');
var errorData=null;
var sendErrorReport = function(data,callback){
    var options = {
        host : connection.host,
        path : "/api/errorReport",
        port : connection.port,
        method : 'POST',
        timeout: connection.timeInterval,
        headers:{
            'Content-Type':'application/json',
            'Content-Length': Buffer.byteLength(data)}
    }
    var request =  http.request(options,function(response){
        callback(response);
    });
    request.on('error',function(err){
        console.log("On Error");
        callback(err);
    });
    request.on('timeout', function(err){console.log("On Timeout");
        callback(err);});
    request.write(data);
    request.end();
}
process.on('uncaughtException', function ( err ) {
    errorData = err;
});
process.on('exit',function(code){
    sendErrorReport(errorData,function(err,res){
        console.log(res);
    });

})

【问题讨论】:

  • 如果你处理SIGINT或uncaughtException事件,你可以在请求的回调中调用process.exit。它应该挂起,直到你调用 .exit() 函数。
  • 在某些情况下我需要在未抛出未捕获的异常时处理进程退出。

标签: node.js http process request exit


【解决方案1】:

在process.on('exit', [fn]) 中,您不能执行docs 中所述的任何异步操作。然而,这是在许多库中也发现的反模式。

您需要依赖process.on('uncaughtException', [fn]) 或任何信号处理程序,例如SIGTERM。

【讨论】:

    【解决方案2】:

    遇到同样的问题, 根据文档https://nodejs.org/api/process.html#process_event_exit

    “事件:‘exit’监听函数只能执行同步操作。”使向其他系统发送请求变得困难。

    一种可能的解决方法是执行另一个脚本/cmd,例如。

    import exec from 'child_process'
    
    mocha.run(failures => {
      process.on('exit', () => {
        exec.execSync(some cmd, function (error, stderr) {
          if (error) {
            throw (error);
          }
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      相关资源
      最近更新 更多