Javascript 使用噩梦重用电子会话
我正在使用梦魇.js打印pdf。 我向节点服务器发送请求并构建页面,使用噩梦确保页面已加载,然后打印pdf。 但是对于每一个请求,我都会创建一个新的electron窗口,如何重用同一个窗口,或者一个max X electron窗口池来处理我的pdf打印Javascript 使用噩梦重用电子会话,javascript,performance,pdf-generation,nightmare,Javascript,Performance,Pdf Generation,Nightmare,我正在使用梦魇.js打印pdf。 我向节点服务器发送请求并构建页面,使用噩梦确保页面已加载,然后打印pdf。 但是对于每一个请求,我都会创建一个新的electron窗口,如何重用同一个窗口,或者一个max X electron窗口池来处理我的pdf打印 var nightmare = require('nightmare'), http = require('http'); function createPage(o, final) { var page = nightmar
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);
我知道在上一次打印完成之前再次使用同一个电子窗口可能会出现的所有并发问题,因此我希望答案能够明确说明如何避免这种情况。您需要创建噩梦实例一次,而不是在循环中
var page = nightmare()
.goto('file:\\\\' + __dirname + '\\index.html');
这会在每次创建页面时创建新的噩梦实例。
您可以创建一次实例
const Nightmare = require('nightmare');
const browser = Nightmare();
然后每次与browser.gotour一起使用它。您可以使用以下地址提供的答案链接您的goto Station:
摘自其中一个答案:
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()
}
var browser1 = Nightmare();
var browser2 = Nightmare();