【问题标题】:How to get .tar.gz archive from unirest response?如何从统一响应中获取 .tar.gz 存档?
【发布时间】:2017-01-02 18:54:47
【问题描述】:

我开发了一个使用 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' }

更新: 我对 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'));

【问题讨论】:

    标签: javascript node.js unirest


    【解决方案1】:

    我认为这是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' );
            });
    

    【讨论】:

    • 谢谢!我自己想通了。我的代码在第一篇文章中。
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2020-08-10
    • 2010-09-17
    • 2013-11-27
    相关资源
    最近更新 更多