【发布时间】:2017-10-08 21:55:56
【问题描述】:
我正在使用 Nightmare.js 打印 pdf。 我向节点服务器发送请求并构建页面,使用 Nightmare 确保页面已加载,然后打印 pdf。 但是对于每个请求,我都会创建一个新的电子窗口,我如何重用同一个窗口或最大 X 个电子窗口池来处理我的 pdf 打印?
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);
我知道在之前的打印完成之前可能再次使用相同的电子窗口可能会出现所有并发问题,所以我希望答案能说明如何避免这种情况。
【问题讨论】:
标签: javascript performance pdf-generation nightmare