我有一个在Heroku(免费版本)上运行的NodeJS服务器。服务器从客户端接受HTTP POST(传递参数),并在无头浏览器中发出Web请求(使用参数)。无头浏览器称为HorsemanJS。 “Horseman是一个Node.js模块,使使用PhantomJS成为一种乐趣。它具有直接可链接的API,可理解的控制流,对多个选项卡的支持以及内置的jQuery。”
当我从客户端(我的计算机)向服务器发送请求(实际上是20个请求的for
循环)时,服务器代码可以正常工作(执行20个HorsemanJS Web请求),并返回期望值。然后,它等待下一个连接。一切都很好。
问题是,当我尝试同时使用两个不同的客户端(我的计算机和电话)连接到服务器时,它崩溃了。我可以重新启动服务器并成功使用一个客户端。如何让它处理多个客户?
崩溃时出错:
child_process.js:788
child.stdout.addListener('data', function(chunk) {
^
TypeError: Cannot read property 'addListener' of undefined
at Object.exports.execFile (child_process.js:788:15)
at exports.exec (child_process.js:649:18)
at Socket.<anonymous> (/app/node_modules/node-horseman/node_modules/node-phantom-simple/node-phantom-simple.js:237:7)
at Socket.g (events.js:199:16)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at Pipe.onread (net.js:538:20)
从我的服务器代码中提取:
var express = require('express');
var app = express();
var Horseman = require('node-horseman');
app.set('port', (process.env.PORT || 5000));
var printMessage = function() { console.log("Node app running on " + app.get('port')); };
var getAbc = function(response, input)
{
var horseman = new Horseman();
horseman
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0") // building web browser
.open('http://www.stackoverflow.com')
.html()
.then(function (result) {
var toReturn = ijk(result));
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(toReturn);
}).close();
}
var handleXyz = function(request, response)
{
getAbc(response, request.query.input);
}
app.listen(app.get('port'), printMessage);
app.post('/xyz', handleXyz);
我尝试将
.close
移到.then
内,也移到.then
之前。该代码仍适用于单个客户端,但不适用于多个客户端。我怀疑问题是一个客户端在客户端尝试使用它之前/之前关闭了一个PhantomJS实例。
最佳答案
将hormanman.close()放入finally可能不会给它足够的时间来完全完全关闭phantomJS进程。尝试将finally更改为.then(),然后返回horseman.close()。