Problem
You need to generate SVG files server-side in Node.js, perfect for data visualizations, icon generation or automated graphics. Front-end APIs aren’t an option so you need a pure Node.js solution.
Solution
Use rough.js with xmldom to create SVG in Node. Here’s an example:
const { DOMImplementation, XMLSerializer } = require(‘xmldom’);const rough = require(‘roughjs’);
const fs = require(‘fs’);
const doc = new DOMImplementation().createDocument(null, null);
const svg = doc.createElementNS(‘http://www.w3.org/2000/svg’, ‘svg’);
const rc = rough.svg(svg);
svg.appendChild(rc.rectangle(10, 10, 200, 100, { fill: ‘blue’ });
const xml = new XMLSerializer().serializeToString(svg);
fs.writeFileSync(‘output.svg’, xml, ‘utf-8’);
console.log(‘SVG saved as output.svg’);
This creates a simple SVG rectangle and writes it to a file using XML serialization. It works without browser DOM APIs and is good for output or file based graphics.
Also Read: A Comprehensive Guide To Building A Node JS MVC Application
Conclusion
So there you have it! By using xmldom and rough.js you can create and save SVG files in pure Node.js, no headless browser required. This is great for graphics generation and automation workflows.