监视 NodeJS 集群的退出
Watching NodeJS Clusters For Exit
我很难理解让节点.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"。
- nodejs-expressjs上传图像并显示它们
- 弹出窗口出现,然后退出
- TypeError:在不兼容的接收器nodejs上调用了方法Uint8Array.length
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- 退出全屏不起作用
- NodeJS日期格式不起作用
- 基于两个条件退出While循环
- Nested Q.all nodejs
- Nodejs API控制器,用于在API之间切换
- 否'访问控制允许来源'标头存在于IISNOde中请求的资源(AngularJS+NodeJs)上
- 如何在大型nodeJS代码的基础上逐步引入typescript
- 在Nodejs中Express输入DEBUG=app时权限被拒绝/bin
- 无法使用nodeJS在html中设置Image src
- 与域在同一台计算机上运行的NODEJS服务器的CORS错误
- 如何准确执行加载脚本&退出弹出窗口
- nodejs:child_process.spawn未报告退出代码
- 在NodeJS中,如何从虚拟函数中退出父函数
- 监视 NodeJS 集群的退出
- NodeJS在未退出的情况下引发错误
- Bash 脚本,用于从 NodeJs 脚本返回退出代码