使用phantom.js和node.js安排PDF生成

我是node.js和phantom.js的新手,所以我不知道如何更好地利用它们。

我有100多所学校的价目表,可以从各自的学校页面下载为PDF格式。 我们所做的是生成PDF并在一夜之间上传到服务器。

现在我们想要使用node.js和phantom.js来批量生成PDF,并尽可能地自动完成这个过程。

以下链接不是价格表网页,而是testingPDF的示例url。

“`

var schedule = require('node-schedule'), path = require('path'), childProcess = require('child_process'), phantomjs = require('phantomjs'), binPath = phantomjs.path, childArgs = [ // phantomjs rasterize.js http://codefight.org codefight.pdf path.join(__dirname, 'rasterize.js'), 'http://codefight.org/', 'codefight.pdf', '400*300' ] // add all the URLs and name of PDF here var pdfSources = [ ['codefight.pdf', 'http://codefight.org/'], ['dltr.pdf', 'http://dltr.org/'] ]; // schedule generating PDFs // running every minute for now to test var j = schedule.scheduleJob('* * * * *', function(){ // loop through the pdfSources and generate new PDFs pdfSources.forEach(function(item, index){ // update childArgs childArgs[1] = item[1]; // pdf content source url childArgs[2] = item[0]; // pdf filename childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) { // for some reason childArgs[2] always prints last item of pdfSources // not sure how to make it work :( console.log('New PDF - "' + childArgs[2] + '" generated!'); console.log(err + stdout + stderr); }); }); }); 

“`

1.我想知道是为什么console.log('New PDF - "' + childArgs[2] + '" generated!'); 总是打印相同的输出。 即“新PDF – ”dltr.pdf“生成!”

2.有没有更好的方法来达到与node.js&phantom.js同样的事情和任何改进,你想build议?

谢谢!

回答1.由于execFileasynchronous性质,输出是相同的。 所以基本上在forEach循环中,你给childArgs[2]赋值并调用execFile但是它的callback被放入一个队列中,然后在第二次循环中覆盖childArgs[2]并再次调用execFile。 现在是时候callback运行,但是事情是childArgs[2]有你分​​配给它的最后一个值。 解决方法可能是将execFile放入如下的闭包中

 (function(cArgs){ childProcess.execFile(binPath, cArgs, function(err, stdout, stderr) { console.log('New PDF - "' + cArgs[2] + '" generated!'); console.log(err + stdout + stderr); }); })(childArgs); 

问题2我没有什么要补充的。