NodeJS gm getting image size synchronously

taichino picture taichino · Oct 29, 2013 · Viewed 7.1k times · Source

I'm using gm and trying to process images according to it's size. Since "size" getter needs callback function, I can't use size in following lines.

What I want to do is like that:

function processImage(url) {
    var img = gm(this.getImgStream(url));

    var width, height;
    img.size(function(err, val) {
        width = val.width;
        height = val.height;
    });

    // I want to use width here, but it's undefined when this line is executed.
    if (width > 500) width = 500;
    return img.resize(width)
}

I want to use width in following resize method. Is there any way to get size synchronously or wait for a callback to complete? I don't want to use ivars as long as possible.

Answer

hexacyanide picture hexacyanide · Oct 29, 2013

Since img.size() is asynchronous, you can't do the operation synchronously (which means you also can't use return for a return value). Therefore, you need img.size() to finish before you can do anything else. You can either assign a callback within the operation, or pass callbacks around:

function processImage(url, callback) {
  var img = gm(this.getImgStream(url));

  var width, height;
  img.size(function(err, val) {
    width = val.width;
    height = val.height;

    callback(err, width, height);
  });
};

processImage(url, function(err, width, height) {
  if (width > 500) width = 500;
  img.resize(width);
});