通过API

时间:2017-03-16 04:55:58

标签: node.js stream

我使用webshot模块从html(或url)截取屏幕截图,截屏文件将通过rest api发送到另一台服务器。

   var options = {
        shotSize: {
            width: 'all'
            , height: 'all'
        }
        , userAgent: 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us)'
        + ' AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g'
    };

    var renderStream = webshot('google.com');
    var file = fs.createWriteStream('google.png', {encoding: 'binary'});

    renderStream.on('data', function(data) {
        file.write(data.toString('binary'), 'binary');
        //code to encode base64Content and send api
    });

我不知道如何从文件流编码发送api。 我希望我的身体发布这样的api:

{
    api: "/file/upload",
    file: {
        base64Content: "data:image/jpeg;base64,/9j/4AAgABAgAAAQAxxxxx",
        lastModified: 1486989111609,
        lastModifiedDate: "2017-02-13T12:31:51.609Z",
        name: "14566344_1443324692346127_1005895525450508957_o.jpg",
        size: 408675,
        type: "image/jpeg"
    }
}

请帮助我!

1 个答案:

答案 0 :(得分:0)

您可以使用stream-to-buffer模块在​​一个缓冲区中获取屏幕截图的内容,然后将其简单地转换为base64,如下所示:

'use strict';

const webshot = require('webshot');
const fs = require('fs');
const streamToBuffer = require('stream-to-buffer');

let options = {
	shotSize: {
		width: 'all'
		, height: 'all'
	}
	, userAgent: 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us)'
	+ ' AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g'
};

let renderStream = webshot('google.com', options);

streamToBuffer(renderStream, (err, buffer) => {
	if (err) {
		console.error(err.stack);
		throw err;
	}

	let base64String = buffer.toString('base64');
	//Now you have base64 encoded screen shot. Use it however you want.
	console.log(base64String);
});

仅供参考。如果您需要动态地将流转换为base64,然后通过管道传输到另一个流(比如写入文件),您可以通过base64-stream这样做:

const base64 = require('base64-stream');

let renderStream = webshot('google.com', options);
let file = fs.createWriteStream('google.txt');

//So you can pipe it wherever needed, so it will bring base64 encoded data
renderStream.pipe(base64.encode()).pipe(file);