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