2017-01-02 53 views
0

我開發了一個工具,使用onlinefontconverter.com API將ttf字體轉換爲其他格式。所以我有一個獲取propper tar.gz存檔的問題。我收到文件,但操作系統告訴我存檔已損壞。那麼如何從響應體保存文件?這裏是我的代碼使用:如何從最簡單的響應獲取.tar.gz存檔?

'use strict'; 
const unirest = require('unirest'); 
const fs = require('fs'); 
const file = fs.createWriteStream('./onlinefontconverter.com.tar.gz'); 

unirest.post("https://ofc.p.mashape.com/directConvert/") 
    .header("X-Mashape-Key", "key") 
    .attach("file", fs.createReadStream('./Roboto-Thin.ttf')) 
    .field("format", "svg") 
    .end((result) => { 
    file.write(result.body, {encoding:'binary'}); 
    }); 

這裏是頭:

{ 'accept-ranges': 'bytes', 
 
    'access-control-allow-headers': 'X-Mashape-Key', 
 
    'access-control-allow-methods': 'POST, OPTIONS', 
 
    'access-control-allow-origin': '*', 
 
    'access-control-expose-headers': 'Content-Disposition', 
 
    'cache-control': 'public, max-age=0', 
 
    'content-disposition': 'attachment; filename="onlinefontconverter.com.tar.gz"', 
 
    'content-type': 'application/octet-stream', 
 
    date: 'Mon, 02 Jan 2017 18:52:34 GMT', 
 
    expires: '0', 
 
    'last-modified': 'Mon, 02 Jan 2017 18:52:34 GMT', 
 
    pragma: 'no-cache', 
 
    server: 'Mashape/5.0.6', 
 
    via: '1.1 vegur', 
 
    'content-length': '119251', 
 
    connection: 'Close' }

UPD: 我已經unirest一個問題,所以我已經重寫簡單的請求。

const file = fs.createWriteStream('./fonts.tar.gz'); 
 
const request = require('request'); 
 
var r = request.post({ 
 
    url:  'https://ofc.p.mashape.com/directConvert/', 
 
    headers: {'X-Mashape-Key' : 'key'}, 
 
}, function(error, response, body){ 
 
    // console.log(body); 
 
    // console.log(response.statusCode); 
 
    // console.log(response.headers); 
 

 
}); 
 
r.pipe(file); 
 
var form = r.form(); 
 
form.append('format', 'ttf'); 
 
form.append('my_file', fs.createReadStream('Aller_Rg.ttf'));

回答

0

我認爲這是在unirest圖書館響應的編碼不正確的問題。嘗試類似這樣(並隱藏您的密鑰):

'use strict'; 
const fs = require('fs'); 

const request = require('request'); 

const formData = { 
    format: 'svg', 
    file: fs.createReadStream('./Roboto-Thin.ttf') 
} 

var buff = []; 
request.post({ url: "https://ofc.p.mashape.com/directConvert/", 
      formData: formData, 
      headers: { 
       "X-Mashape-Key": "SecretMashapeKey" 
      } 
      }) 
     .on('data', function(chunk) { 
      buff.push(chunk); 
     }) 
     .on('end', function() { 
      var data = Buffer.concat(buff); 
      fs.writeFileSync('onlinefontconverter.com.tar.gz', 
           data, 
           'binary'); 
     }); 
+0

謝謝!我想出了自己。我的代碼在第一篇文章中。 –