首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >节点-无法保存文件流

节点-无法保存文件流
EN

Stack Overflow用户
提问于 2016-01-21 23:16:33
回答 1查看 986关注 0票数 0

我使用节点将一些数据发布到外部服务,该服务应该将PDF送回保存,但我认为这两个部分都做得不对(我是节点新手)。我在论坛上看过,尝试过十几种方法,但我要么得到一个空白的PDF,要么一个坏的。下面是我为请求使用的代码(万一我做错了),尽管我尝试使用postman调用该服务,并得到一个保存文件的提示,而且它可以工作,所以它并不一定是外部服务。

代码语言:javascript
复制
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.
    });

以下是我从外部服务得到的响应:

代码语言:javascript
复制
{
  "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
    }
  }
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-22 20:39:27

我希望您使用的是请求模块,它返回一个流。您需要做的唯一一件事就是将这个流输送到一个文件中。这是通过以下方式完成的

代码语言:javascript
复制
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

然后,完整的示例如下所示:

代码语言:javascript
复制
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中更容易。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34936227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档