如何从unirest响应中获取.tar.gz存档?

时间:2017-01-02 18:54:47

标签: javascript node.js unirest

我开发了一个使用onlinefontconverter.com API将ttf字体转换为其他格式的工具。所以我在获取propper 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'));

1 个答案:

答案 0 :(得分: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' );
        });