观察 NodeJS 集群退出

Watching NodeJS Clusters For Exit

我很难思考有一个 node.js 进程(异步的东西)运行 但仍然触发 'exit' 状态所以我可以在 CPU-c运行清算完毕

例如,我有一个 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 耗尽后触发退出)。因此,假设一个集群是 运行ning request() for tempArray x 长度,我如何在 tempArray.forEach(){} 完成时触发 process.exit(0)

我试过在 tempArray.forEach(){} 之后直接调用 process.exit(0),但进程会在 request() 甚至 运行 之前终止。 有什么有效的方法可以更好地观察进程以调用它的退出,或者我真的在尝试解决一个不存在的问题,因为 request() 是异步的,可以调用或不调用有订单吗?

您需要异步流控制。在所有请求完成之前,您不希望进程退出。相反,您要求节点发出所有这些请求,然后退出该过程。 Checkout async.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)
}

请记住,您可能需要添加额外的错误或错误响应检查并相应地进行处理。

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