我想要一个启动页面的CasperJS脚本,然后无限期地保持打开状态,这样我就可以随时通过HTTP向它发送命令.问题是,一旦casper.run调用完成,整个CasperJS进程就会关闭.我已经尝试通过在一个步骤中使用长时间等待来解决这个问题,但随后Web服务器无法对Casper执行任何操作,因为Casper正忙着等待等待呼叫完成.
var port = 6100; var casper = require("casper").create(); casper.start("http://google.com"); casper.then(function() { // If I include this wait,then the server works,but the // `this.capture` call inside it never executes,presumably // because casper is executing the `then` calls in serial. // But if I don't include this wait,the entire process finishes // instantly and I can't use the server anyway. this.wait(100000000,function() { console.log("i have waited"); }); }); casper.run(function() { console.log("finished"); }); var pictureNum = 0; require("webserver").create().listen(port,function(request,response) { var src = "my_picture_" + (pictureNum++) + ".png"; response.writeHead(200,{ 'Content-Type': 'text/html' }); response.write("written " + src); response.close(); casper.then(function() { // How can I do this whenever I want? this.capture(src); }); casper.run(); // Maybe? }); console.log("listening on port",port);
有什么方法可以保持Casper打开并像这样发送命令吗?
编辑:结果我可以很容易地使用原始PhantomJS,只是不调用退出.这非常适合作为PhantomJS脚本:
var port = 6100; var page = require("webpage").create(); page.open("http://google.com",function() { }); var pictureNum = 0; require("webserver").create().listen(port,{ 'Content-Type': 'text/html' }); response.write("written " + src); response.close(); page.render(src); }); console.log("listening on port",port);
但我的问题仍然是如何在利用CasperJS的优点的同时做同样的事情.
解决方法
终于有了合理的东西!
有一个onRunComplete设置,默认情况下调用this.exit.如果使用不执行任何操作的函数覆盖它,则运行结束时进程不会终止.然后你可以调用然后再次运行,任务就可以了.完整的例子:
var port = 6100; var casper = require("casper").create({ onRunComplete: function() { // Don't exit on complete. } }); casper.start("http://google.com"); casper.run(function() { console.log("finished"); }); var pictureNum = 0; require("webserver").create().listen(port,{ 'Content-Type': 'text/html' }); response.write("written " + src); response.close(); // HACK: without this,the `run()` call will re-execute all // the prevIoUs steps too! casper.steps = []; casper.step = 0; casper.then(function() { this.capture(src); }); casper.run(); }); console.log("listening on port",port);