Stream is loaded using Express.js via gm to eliminate double-entry

I use Express.jsand have a route to upload images, which I then need to change. Currently, I just let you Expresswrite the file to disk (which I think uses node-formidableunder the covers) and then resize it using gm(http://aheckmann.github.com/gm/), which writes the second version to disk.

gm(path)
  .resize(540,404)
  .write(dest, function (err) { ... });

I read that you can capture a file stream node-formidablebefore writing it to disk, and since it gmcan receive a stream instead of a simple path, I should be able to transfer this right by eliminating double write to disk.

I think I need to override form.onPart, but I'm not sure where (should it be done as Expressmiddleware?), And I'm not sure how to get the trick formor what exactly to do with part. This is the code skeleton that I saw in several places:

form.onPart = function(part) {
    if (!part.filename) { form.handlePart(part); return; }

    part.on('data', function(buffer) {

    });
    part.on('end', function() {

    }
}

Can someone help me assemble these two parts? Thank!

+5
source share
1 answer

You are on the right track by rewriting form.onPart. Exceptional write to disk by default, so you want to act before that.

The parts themselves are flows, so you can transfer them to whatever you want, including gm. I have not 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'));
  });
};

, multipart Connect/Express onPart: http://www.senchalabs.org/connect/multipart.html

, formidable , , ? .

+7

All Articles