Reputation: 38499
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.
Upvotes: 8
Views: 12028
Reputation: 638
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.
Upvotes: 13
Reputation: 16395
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);
Upvotes: 6