将PNG从GET请求转换为Node.js中的可读流

时间:2016-08-02 22:34:38

标签: javascript node.js png node.js-stream requestjs

我试图建立一个可以发送猫图片的Facebook聊天机器人。我使用RESTful API来获取猫图片。它们作为原始png返回。下一步也是最后一步是将该图像转换为可读流,以便Facebook Chat API可以将其作为附件发送。

我使用request.js来抓取图片。请求文档仅提及将图像保存为文件并将文件读入stream.Readable。我想知道是否有办法绕过该临时文件,并将图像直接传送到Facebook Chat API。

到目前为止,这是我的代码:

var request = require("request");
var stream = require("stream");

module.exports = function getCatPicture(api, threadID, body) {
    var options = {
        url: 'http://thecatapi.com/api/images/get?type=png',
        encoding: 'base64'
    }
    var picStream = new stream.Readable;
    request.get(options, function (error, response, body) {
        picStream.push(body, 'base64');
        var catPic = {
            attachment: picStream
        };
        api.sendMessage(catPic, threadID);
        return;
    });
}

我收到错误:

Error in uploadAttachment Error: form-data: not implemented
Error in uploadAttachment     at Readable._read (_stream_readable.js:457:22)
Error in uploadAttachment     at Readable.read (_stream_readable.js:336:10)
Error in uploadAttachment     at flow (_stream_readable.js:751:26)
Error in uploadAttachment     at resume_ (_stream_readable.js:731:3)
Error in uploadAttachment     at nextTickCallbackWith2Args (node.js:442:9)
Error in uploadAttachment     at process._tickCallback (node.js:356:17)
Error in uploadAttachment  { [Error: form-data: not implemented]
Error in uploadAttachment   cause: [Error: form-data: not implemented],
Error in uploadAttachment   isOperational: true }

1 个答案:

答案 0 :(得分:1)

这里有一些问题:

  1. 这是您需要在新的._read()流实例上实现Readable的主要问题。即将推出的节点版本将有更好的错误消息。因此,目前,您可以在创建picStream._read = function(n){};后添加picStream
  2. 图像被不必要地转换为base64并再次返回。您只需在encoding: null对象中设置optionsbody将成为回调中的Buffer个实例。然后你就可以picStream.push(body);
  3. 流未结束。执行picStream.push(null);
  4. 后添加picStream.push(body);

    最后,这有点偏离主题,但当form-data使用的基础request模块支持许多不同类型的值时,模块会强制使用流,这有点愚蠢(包括用作文件内容的原始Buffer实例)。