2017-05-10 14 views
0

私はNightmare.jsを使ってpdfを印刷しています。 ナイトメアを使用してページがロードされたことを確認した後、pdfを印刷してノードサーバーにリクエストを送信し、ページをビルドします。 しかし、私は新しい電子ウィンドウを作成するたびに、PDFファイルの印刷を処理するために、同じウィンドウまたは最大X電子ウィンドウのプールを再利用する方法を教えてください。悪夢と電子セッションを再利用

var nightmare = require('nightmare'), 
    http = require('http'); 

function createPage(o, final) { 

    var page = nightmare() 
    .goto('file:\\\\' + __dirname + '\\index.html'); 
    .wait(function() { 
     return !!(window.App && App.app); //Check Javascript has loaded 
    }) 

    page.evaluate(function (template, form, lists, printOptions) { 
     App.pdf.Builder.create({ 
      //args for building pages 
     }); 
    }, o.template, o.form, o.lists, o.printOptions); 

    page.wait(function() { 
     return App.pdf.Builder.ready; 
    }) 
    .pdf(form.filename, { "pageSize": "A4", "marginsType": 1 }) 
    .end() 
    .then(function() { 
     console.log('Pdf printed'); 
     final(true); 
    }) 
    .catch(function (err) { 
     console.log('Print Error: ' + err.message); 
    }); 
} 

http.createServer(function (request, response) { 
    var body = []; 
    request.on('data', function (chunk) { 
     body.push(chunk); 
    }).on('end', function() { 
     body = Buffer.concat(body).toString(); 
     var json = JSON.parse(body); 
     createPage(json, function (status) { 
      if (status === true) { 
       response.writeHead(200, { 'Content-Length': 0 }); 
      } else { 
       response.writeHead(500, { 'Content-Type': 'text/html' }); 
       response.write(' ' + status); 
       console.log('status error: ' + status); 
      } 
      response.end('End of Request \n'); //return status msg, if any 
     }); 
    }); 
}).listen(8007); 

私は、以前の印刷が終了する前に潜在的に再び同じ電子窓を使用することによって生じる可能性があるすべての同時実行の問題を認識していたので、私はそれを回避する方法、それを明確にするな答えをしたいと思います。

答えて

0

ループではなく、ナイトメアインスタンスを1回作成する必要があります。

var page = nightmare() 
    .goto('file:\\\\' + __dirname + '\\index.html'); 

これは、新しい悪夢インスタンスにページを作成するたびに作成されます。 あなたはbrowser.goto(URL)でそれを毎回使用後

const Nightmare = require('nightmare'); 
const browser = Nightmare(); 

一度インスタンスを作成することができます。答えの1からhttps://github.com/segmentio/nightmare/issues/708

エキス:

function run() { 
    var nightmare = Nightmare(); 
    yield nightmare 
    .goto('https://www.example.com/signin') 
    .type('#login', 'username') 
    .type('#password', 'password') 
    .click('#btn') 

    for (var i = 0; i < 4; i++) { 
    yield nightmare 
     .goto('https://www.example.com/page'+i) 
     .wait(1000) 
     .evaluate(function(){ 
     return $('#result > h3').text() 
     }) 
    } 

    yield nightmare.end() 
} 

をあなたはまた、同様にプールのために、複数のブラウザを作成することができますあなたはあなたのチェーンのgotoなステートメントを与えられた時に答えを使用することができます。

var browser1 = Nightmare(); 
var browser2 = Nightmare(); 
関連する問題