2016-03-15 70 views
1

我是node.js和phantom.js的新手,所以我不知道如何更好地利用它們,比我在下面做的更好。使用phantom.js和node.js計劃PDF生成

我有100多所學校的服裝價目表,可以從各自的學校頁面下載爲PDF格式。我們所做的是生成PDF並在一夜之間上傳到服務器。

現在我們想要使用node.js和phantom.js來批量生成PDF,並儘可能地自動執行該過程。

以下鏈接不是價格表網頁,而是測試PDF的示例網址。

```

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); 
    }); 
    }); 
}); 

```

我想知道的是爲什麼console.log('New PDF - "' + childArgs[2] + '" generated!');始終打印相同的輸出。即「新PDF - 」dltr.pdf「生成!」

2.有沒有更好的方式來實現與node.js & phantom.js和任何改進你想建議的相同的東西?

謝謝!

回答

1

回答1.由於execFile的異步性質,輸出是相同的。因此,基本上在forEach循環中,您將值賦予childArgs[2]並呼叫execFile,但它的回調放入隊列中,然後在第二次循環中,您覆蓋childArgs[2]並再次調用execFile。現在是回調的時候了,但事情是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

+0

感謝。測試但結果相同。 –

+0

嗯奇怪。你是否可以添加'console.log(cArgs);'justow bellow'(function(cArgs){'並且實際上是否創建了2個不同的PDF文件? – Molda

+0

是用正確的內容創建的2個不同的PDF文件。 。 –