NodeJS gm resizes and processes the response

Is there a way to redirect the changed 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 have the wrong syntax.

+8
imagemagick
source share
2 answers

Your question really helped me get an answer on 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 deleted the entire link to the completion function because it is not defined, and sent an error to express the error handler. Hope this helps someone. I would also like to add that I use express 3, so creating a server is slightly different.

+13
source share

You get an error because you want to write to res after you have posted the image. Try adjusting the headers before , you will skip 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); 
+4
source share

All Articles