I've made a function that rotates images 90 degrees on an Express server in Node.js. It works the first time it is called, but not the 2nd time. If i restart the server, then it will work one more time again, so if I restart the server 3 times then I could rotate the image all the way around.
The Product.findById is a mongoose query to find the image name for the image id specified from the request from the frontend.
In both the first and second try the console.log on line 7 returns the correct plant path/name, and no error is thrown. The response status is 200 "image rotated", both times aswell
router.patch("/rotate/:image", (req, res, next) => {
let image = ""
Product.findById(req.params.image)
.exec()
.then(result => {
image = './uploads/resized/'+result.image
console.log("image", image)
sharp(image)
.rotate(90)
.withMetadata()
.toBuffer(function(err, buffer) {
if(err) throw err
fs.writeFile(image, buffer, function() {
res.status(200).json("image rotated")
});
})
})
.catch(err => {res.status(400).json("invalid img id")
console.log(err)})
})
Expected output is image rotated 90 degrees on every http request, but the actual output is only image rotated 90 degrees on the first http request.
Try disabling cache writing following line after importing sharp
module:
sharp.cache(false);