2014-03-27 38 views
6

我想有一個CasperJS腳本,啓動一個網頁,然後一直開下去,所以我可以通過HTTP發送給它的命令,每當我想要的。問題是,只要casper.run調用完成,整個CasperJS進程就會關閉。我試着在一個步驟中使用長wait電話獲取解決這個問題,但後來因爲卡斯珀正在等待wait調用來完成繁忙的Web服務器無法與卡斯帕做任何事情。PhantomJS/CasperJS - 保持會話無限期打開並通過HTTP與它交互?

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); 

有什麼辦法可以讓卡斯帕打開併發送命令給它嗎?

編輯:原來我可以很容易地做到這一點與原PhantomJS,只是沒有要求exit。這工作完全作爲一個PhantomJS腳本:

var port = 6100; 

var page = require("webpage").create(); 
page.open("http://google.com", function() { }); 

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(); 
    page.render(src); 
}); 
console.log("listening on port", port); 

但我的問題仍然是如何做同樣的事情,同時也考慮CasperJS的正派的優勢。

回答

13

終於有了一些合理的!

有一個onRunComplete設置,默認情況下調用this.exit。如果你用一個什麼都不做的函數覆蓋它,那麼當run完成時,進程將不會終止。然後,您可以再次撥打thenrun,這些任務將正常工作。完整的例子:

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, function(request, response) { 
    var src = "my_picture_" + (pictureNum++) + ".png"; 
    response.writeHead(200, { '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);