我試圖製作一個可以發送貓圖片的Facebook聊天機器人。我使用RESTful API來獲取貓的照片。他們返回原始png。下一步也是最後一步是將該圖像轉換爲可讀流,以便Facebook Chat API可以作爲附件發送。將PNG從GET請求轉換爲Node.js中的可讀流
我用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 }
請參閱https://github.com/maxogden/mississippi#from和https://github.com/yoshuawuyts/from2-string –
只有在請求返回所有pody後纔會推送可讀流,因爲您是使用回調,你需要管...像'request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))' – yeya