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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With