Skip to content Skip to sidebar Skip to footer

Stream File Uploaded With Express.js Through Gm To Eliminate Double Write

I'm using Express.js and have a route to upload images that I then need to resize. Currently I just let Express write the file to disk (which I think uses node-formidable under th

Solution 1:

You're on the right track by rewriting form.onPart. Formidable writes to disk by default, so you want to act before it does.

Parts themselves are Streams, so you can pipe them to whatever you want, including gm. I haven't tested it, but this makes sense based on the documentation:

var form = new formidable.IncomingForm;
form.onPart = function (part) {
  if (!part.filename) return this.handlePart(part);

  gm(part).resize(200, 200).stream(function (err, stdout, stderr) {
    stdout.pipe(fs.createWriteStream('my/new/path/to/img.png'));
  });
};

As for the middleware, I'd copypaste the multipart middleware from Connect/Express and add the onPart function to it: http://www.senchalabs.org/connect/multipart.html

It'd be a lot nicer if formidable didn't write to disk by default or if it took a flag, wouldn't it? You could send them an issue.


Post a Comment for "Stream File Uploaded With Express.js Through Gm To Eliminate Double Write"