Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS gm resize and pipe to response

Is there a way of piping the resized image to my express response?

Something along the lines of:

var express = require('express'),
    app = express.createServer();

app.get('/', function(req, res){

    gm('images/test.jpg')
        .resize(50,50)
        .stream(function streamOut (err, stdout, stderr) {
            if (err) return finish(err);
            stdout.pipe(res.end, { end: false }); //suspect error is here...
            stdout.on('end', function(){res.writeHead(200, { 'Content-Type': 'ima    ge/jpeg' });});
            stdout.on('error', finish);
            stdout.on('close', finish);
    });
});

app.listen(3000);

This unfortunately causes an error...
Pretty sure I've got some syntax wrong.

like image 630
Alex Avatar asked Sep 17 '12 23:09

Alex


2 Answers

your question actually helped me get the answer for the same issue. How it worked for me:

    var express = require('express'),
    app = express.createServer();

app.get('/', function(req, res, next){

    gm('images/test.jpg')
        .resize(50,50)
        .stream(function streamOut (err, stdout, stderr) {
            if (err) return next(err);
            stdout.pipe(res); //pipe to response

            // the following line gave me an error compaining for already sent headers
            //stdout.on('end', function(){res.writeHead(200, { 'Content-Type': 'ima    ge/jpeg' });}); 

            stdout.on('error', next);
    });
});

app.listen(3000);

I removed all reference to finish function as it's not defined and sent the error to express error handler. Hope it helps someone. i also would like to add i'm using express 3, so creating the server is slightly different.

like image 131
Marco Gabriel Godoy Lema Avatar answered Nov 18 '22 07:11

Marco Gabriel Godoy Lema


You get the error because you want to write to res after you've piped the image. Try setting the headers before you pipe your image:

var express = require('express'),
    app = express.createServer();

app.get('/', function(req, res){

  res.set('Content-Type', 'image/jpeg'); // set the header here

  gm('images/test.jpg')
    .resize(50,50)
    .stream(function (err, stdout, stderr) {
      stdout.pipe(res)
    });
});

app.listen(3000);
like image 6
zemirco Avatar answered Nov 18 '22 07:11

zemirco