Search code examples
node.jsasynchronousnode-imagemagick

NodeJS gm getting image size synchronously


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.


Solution

  • 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);
    });