Rendering SVG to PNG in an API
I work a lot with SVG:s, but sometimes I want to render them as PNG:s to make some of my workflows simpler. This is a neat trick that uses the sharp
library within express
to generate a PNG file from SVG and serve it in an endpoint.
server.get("/api/cover/:id", function(req, res) {
var svg = getSvg(req.params.id);
const buffer = Buffer.from(svg);
const img = await sharp(buffer).png();
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
});