When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize
and .toBuffer()
multiple times is causing corruption in the response object (res).
router.post('/submit', upload.single('file'), (req, res) => {
var image = sharp(req.file.buffer)
image.resize(1500, 1500, { fit: 'inside' }).toBuffer()
.then(buffer => fs.writeFile('../image-md.jpg', buffer))
.then(() => image.resize(500, 500, { fit: 'inside' }).toBuffer())
.then(buffer => fs.writeFile('../image-sm.jpg', buffer))
.then(() => res.json({ success: true }))
.catch(err => res.status(400).json({ error: err.message }))
})
// Issue: res is undefined and no status is being returned
An interesting observation is that when one of the resizing operations is commented out, everything functions properly:
router.post('/submit', upload.single('file'), (req, res) => {
var image = sharp(req.file.buffer)
image.resize(1500, 1500, { fit: 'inside' }).toBuffer()
.then(buffer => fs.writeFile('../image-md.jpg', buffer))
// .then(() => image.resize(500, 500, { fit: 'inside' }).toBuffer())
// .then(buffer => fs.writeFile('../image-sm.jpg', buffer))
.then(() => res.json({ success: true }))
.catch(err => res.status(400).json({ error: err.message }))
})
// Solution: res.data is { success: true } and status 200 is properly returned
In need of assistance!