node.js - 在 Node 进程退出时发送http请求

标签 node.js http process request exit

我编写了示例 Node 应用程序来处理错误数据,例如数据库连接错误、端口冲突错误、进程未捕获的异常。当发生错误时,会发出 http 请求来处理错误。在这种情况下,当 Node 进程异常存在时,我可以处理 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);
    });

})

最佳答案

遇到同样的问题, 根据文档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);
      }
 }
}

关于node.js - 在 Node 进程退出时发送http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45507882/

相关文章:

c# - 将程序作为线程而不是进程执行

linux - 如果两个线程同时调用 fork() 会发生什么

node.js 函数应该仅在 mongodb 查询完成后返回

node.js - 如何卸载无效的全局NPM包?

json - 如何仅将 Spring Resttemplate 与 JSON 一起使用

http - AWS Load Balancer 是否可以配置为过滤掉请求?

Python 多处理在连接处挂起

node.js - 返回 MongoDB 中具有不同字段和 1 个选择查询的整个文档

javascript - Linux 上的 NodeJS/V8/JavaScript : Upredictable ramp-up to full performance

delphi - 如何使用 THTTPReqResp 添加/覆盖 HTTP header ?