节点 - 无法保存文件流

时间:2016-01-21 23:16:33

标签: node.js stream file-writing

我正在使用节点将一些数据发布到外部服务,该服务应该发送给我一份PDF以保存,但我不认为我正在做任何一部分正确(I&# 39; m new to node)。我已经在论坛上看过并尝试了十几种方法,但我要么得到一个空白的PDF或一个损坏的PDF。这是我用于请求的代码(如果我做错了),虽然我尝试使用邮递员调用该服务并且我得到一个提示来保存文件,但是它有效,所以它和&#39 #39;不是外部服务肯定。:

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
    }
  }
}

如果有人知道如何正确获取和保存此文件,我们将不胜感激。

1 个答案:

答案 0 :(得分:2)

我希望你使用request模块返回一个流。您需要做的唯一事情是将此流传输到文件中。这是通过以下方式完成的

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

完整示例可以如下所示:

var options = {
  method: 'POST',
  body: JSON.stringify({ template: { recipe: 'phantom-pdf', engine: 'handlebars', content: 'Hello world'}}),
  uri: 'http://localhost:3000/api/report',
  headers: {
    "Content-Type": "application/json",
    'Authorization': 'Basic ' + new Buffer("admin:password").toString('base64')
  }
};

request(options, function(error, response, body) {

}).pipe(fs.createWriteStream("report.pdf"))

您还可以检查jsreport-client,这使得node.js中的远程报告呈现更容易。

相关问题