0
我正在使用節點將一些數據發佈到外部服務,該服務本應發回給我一個PDF以進行保存,但我認爲我沒有正確執行任何部分(我對節點來說是新的)。我看過論壇並嘗試了十幾種方法,但我要麼得到一個空白的PDF或一個腐敗的。這裏是我用於請求的代碼(如果我做錯了),儘管我嘗試使用郵遞員調用服務,並且我得到一個提示來保存文件,並且它可以工作,所以它不是外部服務可以肯定的:節點 - 無法保存文件流
var x = {//data to be sent}
var options = {
method: 'POST',
uri: '//link',
form: x,
headers: {
"Content-Type": "application/json",
'Authorization': 'Basic ' + new Buffer("user:pass").toString('base64')
}
};
request(options, function(error, response, body) {
//How to properly get the stream and save it as a valid PDF?
//I tried fs.witeFile, createWriteStream, pipe, and a bunch
//of other ways without luck.
});
下面是我從外部服務獲得的響應:
{
"statusCode": 200,
"body": "%PDF-1.4\n1 0 obj\n<<\n/Title (��)\n/Creato..{//very long response}..",
"headers": {
"x-powered-by": "Express",
"access-control-allow-origin": "*",
"vary": "Origin",
"connection": "close",
"content-type": "application/pdf",
"content-disposition": "inline; filename=\"report.pdf\"",
"file-extension": "pdf",
"number-of-pages": "1",
"x-xss-protection": "0",
"set-cookie": [
"session=_O2T27N......"
],
"date": "Thu, 21 Jan 2016 23:13:16 GMT",
"transfer-encoding": "chunked"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": "xxxxx.net",
"port": 443,
"hostname": "xxxxx.net",
"hash": null,
"search": null,
"query": null,
"pathname": "/api/report",
"path": "/api/report",
"href": "https://xxxxx.net/api/report"
},
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic aXRA......",
"content-length": 129
}
}
}
如果有人知道如何正確地獲取並保存此文件,我們將不勝感激。
謝謝!我正在使用在線版本,但我改變了一下,它工作。現在,我試圖給附件發送電子郵件,但它在流完成之前似乎正在觸發,如何在文件寫入磁盤後運行函數? – Mankind1023
var w = fs.createWriteStream(「report.pdf」); ('finish',function(){ console.log('done'); }); response.pipe(w); // Source http://stackoverflow.com/questions/13156243/event-associated-with-fs-createwritestream-in-node-js –