NodeJS gm resize and pipe to response
Problem
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.
Problem courtesy of: Alex
Solution
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.
Solution courtesy of: Marco Gabriel Godoy Lema
Discussion
View additional discussion.