首页 > 解决方案 > 节点幻影多个实例不呈现正确的页面

问题描述

我正在使用幻像来保存多个交易的 pdf,但有一天我注意到一些奇怪的事情,假设有两个页面 A 和 B 然后我想将其捕获为 pdf,但是当 A.pdf 和 B.pdf 创建时,两者其中显示页面 B。仅当我同时调用它们时才会发生。

示例代码:

function testPhantom(i)
{
    var phantom = require('phantom');
    phantom.create()
    .then(function(ph){phInstance = ph; return ph.createPage();})
    .then(function(page){
        page.property('viewportSize', {width: "210mm", height: "297mm"});  
        page.property('paperSize', {format: 'A4', orientation: 'portrait', margin: '1cm'});
        pageInstance = page;
        if (i == 1)
        {
            return page.open('http://www.google.com/');
        }
        else if (i == 2)
        {
            return page.open('https://www.facebook.com/');
        }
    })
    .then(function(status){
        console.log(status);
        return pageInstance.render('test'+i+'.pdf');
    })
    .then(function(){
        // phInstance.exit();
    })
    .catch(function(error){
        console.log(error);
        // phInstance.exit();
    });
}

testPhantom(1);
testPhantom(2);

使用此代码,它既可以是 google 也可以是 facebook。

如果我在函数上调用 exit,警告将显示为

warn: exit() was called before waiting for commands to finish. Make sure you are not calling exit() prematurely

或错误为

Error: Error reading from stdin: Error: This socket has been ended by the other party

我怎样才能有不同的幻影实例,所以他们会做对

标签: node.jsphantomjs

解决方案


我认为你应该制作phInstance一个pageInstance局部变量。像这样:

var phInstance;
var pageInstance;
var phantom = require('phantom');
etc.

推荐阅读