在节点进程退出时发送http请求

时间:2017-08-04 13:16:48

标签: node.js http process request exit

我编写了示例节点应用程序来处理错误数据,例如数据库连接错误,端口冲突错误,进程未捕获异常。发生错误时,会发出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);
    });

})

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

“事件:'退出'监听器函数必须仅执行同步操作。”很难将请求发送到其他系统。

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

import exec from 'child_process'

mocha.run(failures => {
  process.on('exit', () => {
    exec.execSync(some cmd, function (error, stderr) {
      if (error) {
        throw (error);
      }
 }
}
相关问题