流式传输`request`请求的正确方法?

时间:2015-06-26 19:04:56

标签: javascript node.js mailgun

我正在尝试从request创建一个ReadableStream对象,最终我想将其传递给mailgun-js数据对象的附件变量:

var fileStream = null;
request(String(url)).pipe(fileStream);

msg.attachment = new mailgun.Attachment({
    data: fileStream,
    filename: 'my_custom_name.png',
    knownLength: fileStat.size,
    contentType: 'image/png'});

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

我知道这有点晚了,但希望仍然有用。刚刚提交了拉取请求以获得此功能:

var request = require('request');
var file = request("https://www.google.ca/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'serobnic@mail.ru',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!',
  attachment: file
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

如果没有合并,你可以在这里看到它: https://github.com/antoniosou/mailgun-js

答案 1 :(得分:0)

未经测试,但值得一试:

var stream = new require('stream').PassThrough();

request(String(url)).pipe(stream);

msg.attachment = new mailgun.Attachment({
  data        : stream,
  filename    : 'my_custom_name.png',
  knownLength : fileStat.size,
  contentType : 'image/png'
});

request()似乎没有从Stream继承,因此直接将其作为data属性传递不起作用。相反,会创建PassThrough流,该流继承自ReadableWritable

Mailgun类将使用Readable部分,Writable部分将通过管道传输HTTP响应数据。