监视 NodeJS 集群的退出

Watching NodeJS Clusters For Exit

本文关键字:退出 NodeJS 监视      更新时间:2023-09-26

我很难理解让节点.js进程(异步运行)但仍然触发"退出"状态,以便我可以在 CPU 处理完成后做更多的事情。

例如,我有一个Google Places抓取工具,可以有效地在所有可用的CPU之间分配http请求。

} else if (cluster.isWorker) {
//  Code to run if we're in a worker process
// Send the object we created above from variables so they're available to the workers
process.on('message', function(clusterDivisionObject) {
    var tempArray;
    // Send the chunk of array appropriate for this cluster to process, then request it's place details
    tempArray = clusterDivisionObject.placeIdArray.splice(((cluster.worker.id * clusterDivisionObject.clusterDivision) - clusterDivisionObject.clusterDivision), clusterDivisionObject.clusterDivision);
    tempArray.forEach(function(arrayItem, index, array){
      request({url: config.detailsRequestURI + '?key=' + config.apiKey + '&placeid=' + arrayItem, headers: config.headers}, detailsRequest);
    });
});
}

这里真正的问题是我发送异步request()语句的最后一行。 代码正确执行,但是一旦我点击回调(detailsRequest)来做某事(在这种情况下,写入json文件),我就无法控制退出进程。 我的回调函数:

function detailsRequest(error, response, body) {
    if (!error && response.statusCode == 200) {
        var detailsBody = JSON.parse(body);
        ...
    }
}

。不知道哪个进程正在运行它或它进行了多少次迭代(在整个tempArray耗尽后触发退出)。 那么,假设一个集群request()运行 x 长度的tempArray,那么当该tempArray.forEach(){}完成时,我该如何触发process.exit(0)

我尝试在tempArray.forEach(){}之后直接调用 process.exit(0),但该进程将在运行之前request()死亡。 是否有任何有效的方法可以更好地观察一个进程来调用它的退出,或者我真的在尝试解决一个不存在的问题,因为request()是异步的,可以按任何顺序调用或不调用?

您需要异步流控制。您不希望在所有请求完成之前退出进程。相反,您要求节点发送所有这些请求,然后退出进程。签出异步.js或其他一些流控制库。但是你需要这样的东西:

var tempArray;
var counter = 0;
tempArray = []; // same as above
// Without asyncjs
tempArray.forEach(function(arrayItem, index, array){
  request({url: config.detailsRequestURI + '?key=' + config.apiKey +'&placeid=' + arrayItem, headers: config.headers}, detailsRequest);
});
function detailsRequest(){ 
 // increment counter and handle response
 // this callback gets called N times.
 counter +=1;
 if(counter >= tempArray.length){ process.exit(0); }
}

//With async.js:
async.map(tempArray, sendRequestFunc, function finalDone(err, results){ 
  // here you can check results array which has response
  // and then exit
  process.exit(0);
}); 
function sendRequestFunc(el, done){ 
  // done callback as per async docs
  // done must be invoked here or the final callback is never triggered 
  request({url:'same as above'}, done)
}

请记住,您可能需要添加针对错误或错误响应的其他检查,并相应地处理这些检查。

sendRequestFunc 中的 done 回调仅在请求返回响应或错误(异步)时调用,并且仅当所有响应都返回时才调用最后一个异步回调"finalDone"。