brenden / node-webshot

Easy website screenshots in Node.js
2.12k stars 286 forks source link

Render HTML in streaming #115

Open kaliseo opened 9 years ago

kaliseo commented 9 years ago

Hi there,

It is possible to make a stream from an url, but not from simple HTML content. I have to write an image file and to read it back to render it.

Is there a solution to do that without writing an image to disk ?

Thanks a lot !

rmartin commented 9 years ago

hey @kaliseo ,

Webshot returns a node stream, so this is actually pretty straight forward to accomplish. I combined this with express so that I could spin something up quickly that was also accessible by a route. Here's a quick example, just make sure you npm install webshot and express.

'use strict';
var webshot = require('webshot'),
    express = require('express'),
    app = express(),
    options = {};

app.get('/', function(req, res) {
    var renderStream = webshot('google.com', null, options),
        screenshot = '';

    // Capture the streaming output from the screenshot
    renderStream.on('data', function(data) {
        screenshot += data.toString('binary');
    });

    // Once the image capture is completed, write it out to the browser
    renderStream.on('end', function() {
        res.set('Content-Type', 'image/png');
        res.end(screenshot, 'binary');
    });
});

app.listen(3000);

Cheers, Roy

stefek99 commented 8 years ago

Thanks, that helps.

That is (in my opinion) a rather frequent scenario and I was searching for available Stream methods here: https://nodejs.org/api/stream.html#stream_event_end

Your example solves my issue automagically :)