0

I am building a dummy image generator to improve my understanding of Node and Express. I get the dimensions from the URL and use GM package to resize it. The resulting stream is piped into the response. But I don't get the data on the front end and when I check the response tab in the Network panel of the dev tools in Chrome I see 'this response has no data available'. Can someone please give me some pointers as I am not sure where I can begin debugging this.

const IMAGE_DIR_PATH = path.join(__dirname, './../../data/images');

const getRandomImageName = () => {
  return new Promise((resolve, reject) => {
    fs.readdir(IMAGE_DIR_PATH, (err, images) => {
      err ? reject(err) : resolve(
        images[Math.floor(Math.random() * images.length)]
      );
    });
  });
};

const pickDimensions = (dimensionsStr) => {
  const dimensions = dimensionsStr.toLowerCase().split('x');
  return {
    width: dimensions[0],
    height: dimensions[1] ? dimensions[1] : dimensions[0]
  };
};

exports.getRandomImageByDimension = (req, res, next) => {
  const dimensions = pickDimensions(req.params.dimensions);

  //getRandomImageName returns a Promise
  //resolves with the name of the file example: abc.jpg
  getRandomImageName()
  .then((img) => {
    res.set('Content-Type', 'image/jpeg');

    //I am getting the right image and the path below is valid
    gm(path.resolve(`${IMAGE_DIR_PATH}/${img}`))
    .resize(dimensions.width, dimensions.height)
    .stream(function (err, stdout, stderr) {
      if (err) { throw new Error(err); }
      stdout.pipe(res);
    });
  })
  .catch(e => {
    res.status(500);
    res.send(e);
  });
};

The response headers I receive is shown below: enter image description here

larrydalmeida
  • 1,570
  • 3
  • 16
  • 31
  • 1
    I'd start debugging this using a much simpler example. First create a Node script that doesn't use Express or GM at all, just open an image file and pipe it into another file, check that works, using hard-coded filenames so there's no doubt what it's doing. Then add in the resizing stuff, using hard-coded sizes and check that works. Then gradually introduce the Express bits and remove the hard-coding. Keep checking it still works at each stage until you isolate exactly where it goes wrong. – skirtle Oct 07 '17 at 17:15

1 Answers1

0

Turns out that I had forgotten to add ImageMagick as a dependency for gm and this was causing an error. Strangely the error was not shown in the console and I found it only after breaking down the app into simpler pieces and debugging as skirtle mentioned in a comment above.

To fix I did the following:

npm install --save imagemagick

Then in the file where I was using the gm package, I set the imageMagick property:

const gm = require('gm').subClass({imageMagick: true});

Note: I was running this on a Windows 7.

larrydalmeida
  • 1,570
  • 3
  • 16
  • 31