如何将图像从 nodejs 缓冲区发送到 Slack

时间:2020-12-23 18:46:36

标签: node.js stream puppeteer slack

我必须获取带有 puppetter 的页面的屏幕截图,然后将其发送到 Slack 频道。

如果我将屏幕截图保存到文件,则一切正常:

var Slack = require('nodejslack');
....
await page.goto('https://www.google.com');
const body = await page.$('body');
await page.screenshot({path: '1.png'})

var slack = new Slack("xoxb-......");

var form = {
       file: fs.createReadStream("1.png"),
       filename: '1.png',
       fileType: 'auto',
       title: '1.png'
       channels: channel_id 
};

slack.fileUpload(form).then(function(response){
     console.log('Response: ' + response);
})

但我想删除不必要的磁盘写入/读取。并使用 puppeteer 功能将屏幕截图保存到 Buffer。我试试这个:

class VirtualFileReadable extends Readable {
    constructor (options, buffer) {
        super(options)
        this.buffer = buffer
    }

    _read(size) {
        this.push(this.buffer)
    }
}

function bufferToStream(buffer) {
    return new VirtualFileReadable({}, buffer);
}

并与第一个(工作)案例完全相同。:

var Slack = require('nodejslack');
....
await page.goto('https://www.google.com');
const body = await page.$('body');
const buffer = await page.screenshot({encoding: 'binary'})

var slack = new Slack("xoxb-......");


var form = {
       file: bufferToStream(buffer),
       filename: '1.png',
       fileType: 'auto',
       title: '1.png'
       channels: channel_id 
};

slack.fileUpload(form).then(function(response){
     console.log('Response: ' + response);
})

因此,我尝试使用我自己的 stream.Readable 后代而不是 stream.createReadStream。并且在descendat slack 的情况下返回错误no_file_data。怎么了?

0 个答案:

没有答案