#!/usr/bin/env node const sharp = require('sharp') function parseArgs(argv) { const parsed = {} for (let i = 2; i < argv.length; i += 1) { const key = argv[i] const value = argv[i + 1] if (key === '--width' && value) { parsed.width = Number(value) i += 1 continue } if (key === '--height' && value) { parsed.height = Number(value) i += 1 } } return parsed } async function main() { const args = parseArgs(process.argv) const chunks = [] process.stdin.on('data', (chunk) => { chunks.push(chunk) }) process.stdin.on('end', async () => { try { const svgBuffer = Buffer.concat(chunks) if (!svgBuffer.length) { throw new Error('empty svg input') } const width = Number.isFinite(args.width) && args.width > 0 ? Math.round(args.width) : null const height = Number.isFinite(args.height) && args.height > 0 ? Math.round(args.height) : null let pipeline = sharp(svgBuffer, { density: 300 }) if (width || height) { pipeline = pipeline.resize({ width: width || undefined, height: height || undefined, fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 1 }, withoutEnlargement: false, }) } const pngBuffer = await pipeline.png({ compressionLevel: 9 }).toBuffer() process.stdout.write(pngBuffer) } catch (error) { process.stderr.write(`svg_to_png_error: ${error && error.message ? error.message : String(error)}\n`) process.exit(1) } }) } main()