2015-03-31 26 views
1

試圖編寫一個測試(mocha)來檢查從我的api端點返回的PDF是否保存了正確的數據,看起來應該如此。 PDF是在服務器上生成的。它在手動點擊端點時返回'正確',但想寫一些測試。我上傳了一個'正確'的PDF文件到我的測試套件中,我可以用hummus js解析並抽出必要的方面進行比較。節點不能管pdf響應

我想向我的端點(使用superagent)發出請求,然後將響應(pdf)轉換爲臨時pdf。然後我將解析PDF(上傳的完美文件和從我的端點返回的文件)並確保它們匹配。

我的請求代碼:

it('Should look like the proposed pdf', function (done) { 

     request(app) 
      .get(url) //var that sets the path earlier 
      .expect(200) 
      .end(function (err, res) { 
       if(err) return done(err); 

       var writeStream = fs.createWriteStream('./test/materials/tmp.pdf'); 
       writeStream.pipe(res); //ERROR can't pipe 
       writeStream.on('end', function() { 
        console.log('complete'); 
        done(); 
       }) 
      }); 

     }); 

當我跑我的測試中,我得到:未捕獲的錯誤:無法管。不可讀。我對節點非常陌生,所以我不確定是什麼導致了錯誤。當我安慰水庫時,我得到一個大的二進制編碼混亂,所以也許這是問題?我試了幾件事 - 使用鷹嘴豆泥pdfWriter,試圖解碼與

new Buffer(res, 'base64')

等...但仍然沒有運氣。我相信我已經爲這些操作安裝了所有必要的軟件包,並且似乎是一個管道/解碼/ superagent問題。謝謝您的幫助!

編輯:我是誤解管道。您可以簡單地將響應寫入文件:

fs.writeFile('./test/materials/test_tmp.pdf', new Buffer(res.text, 'ascii')); 

將此情況轉換爲ascii。我現在更接近,但仍然掛在編碼片上。這會創建一個空白的PDF。當我在崇高中觀察文件內容時,它們看起來與我正在比較的PDF相同,但具有不同的編碼。有人知道如何匹配原始PDF的編碼或找出它的編碼方式嗎?或者如果這甚至是可能的?我使用PDFkit來構建PDF。

回答

0

我不認爲(或知道)一種方式來做到這一點原生。如果你打開使用其他模塊,採取look at pdfkit

你可以做這樣的事情

var pdf = new PDFDocument; 
pdf.pipe(fs.createWriteStream('./test/materials/tmp.pdf')); 

編輯
我的道歉,我看了你的問題,稍有不妥。該模塊雖然有一些例子。例如,從他們的文檔 -

PDFDocument = require 'pdfkit' 

# Create a document 
doc = new PDFDocument 

# Pipe it's output somewhere, like to a file or HTTP response 
# See below for browser usage 
doc.pipe fs.createWriteStream('output.pdf') 

# Embed a font, set the font size, and render some text 
doc.font('fonts/PalatinoBold.ttf') 
    .fontSize(25) 
    .text('Some text with an embedded font!', 100, 100) 

# Add another page 
doc.addPage() 
    .fontSize(25) 
    .text('Here is some vector graphics...', 100, 100) 

# Draw a triangle 
doc.save() 
    .moveTo(100, 150) 
    .lineTo(100, 250) 
    .lineTo(200, 250) 
    .fill("#FF3300") 

# Apply some transforms and render an SVG path with the 'even-odd' fill rule 
doc.scale(0.6) 
    .translate(470, -380) 
    .path('M 250,75 L 323,301 131,161 369,161 177,301 z') 
    .fill('red', 'even-odd') 
    .restore() 

# Add some text with annotations 
doc.addPage() 
    .fillColor("blue") 
    .text('Here is a link!', 100, 100) 
    .underline(100, 100, 160, 27, color: "#0000FF") 
    .link(100, 100, 160, 27, 'http://google.com/') 

# Finalize PDF file 
doc.end() 
+0

嘿賈斯汀,感謝您的答覆。我實際上使用pdfkit在返回之前在服務器上構建pdf。來自superagent請求的響應現在返回來自先前構建的pdf的二進制數據。我現在要做的是將所有響應數據轉換爲另一個pdf文檔,而不是使用pdfkit方法重建它(數據解碼和管道應該能夠生成PDF)。我的問題是處理響應對象和如何管理它。一旦我把它加入到一個新的文檔中,我就可以與我手動上傳的pdf進行比較,以檢查它們是否匹配。 – eps 2015-03-31 23:32:07