当我在节点中使用phantomJS时,出现错误

时间:2017-05-21 16:05:46

标签: node.js phantomjs

我在节点中使用了phantomJS并编写了以下代码,但错误出现在控制台上。

以下代码只是尝试访问Google首页并拍摄其页面的屏幕截图。

我该如何解决此错误?

(节点版本:v6.10.3)

(1)代码(test.js)

var phantom = require("phantom");
var promise = phantom.create().then(function(ph) {
    return ph.createPage().then(function(page) {
        page.property('onConsoleMessage', function(msg) {
            console.log(msg);
        });
        page.property('onLoadStarted', function() {
            loadInProgress = true;
            console.log('Load Started...');
        });
        page.property('onLoadFinished', function() {
            loadInProgress = false;
            console.log('Load End');
        });

        var loadInProgress = false;
        var stepIndex = 0;
        var steps = [
            function() {
                page.open('https://www.google.co.jp/').then(function (status) {
                    // something process
                }).catch(function(error){
                    console.log(error); // <======= Here, the error appeared
                });
            },
            function() {
                console.log("step end");
            }
        ];

        interval = setInterval(function(){
            if(!loadInProgress && typeof steps[stepIndex] == 'function') {
                steps[stepIndex]();
                stepIndex++;
            } else if (steps[stepIndex] != 'function') {
                ph.exit();
                clearInterval(interval);
            }
        }, 10);
    });
});

(2)错误

$ node test.js
step end
warn: exit() was called before waiting for commands to finish. Make sure you are not calling exit() too soon.
info: Load Started...
Error: Phantom process stopped with exit code 0
    at Phantom._rejectAllCommands (<myfilepath>/phantomjs/node_modules/phantom/lib/phantom.js:361:41)
    at ChildProcess.Phantom.process.on.code (<myfilepath>/phantomjs/node_modules/phantom/lib/phantom.js:164:18)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)

1 个答案:

答案 0 :(得分:0)

您过早退出脚本,完全与错误相同。

从区间函数中删除ph.exit();

    interval = setInterval(function(){
        if(!loadInProgress && typeof steps[stepIndex] == 'function') {
            steps[stepIndex]();
            stepIndex++;
        } else if (steps[stepIndex] != 'function') {
            // ph.exit(); // <-- remove exit() from here
            clearInterval(interval);
        }
    }, 10);

将其移至page.open回调,以便在打开页面后调用它:

page.open('https://www.google.co.jp/').then(function (status) {
    ph.exit();
})