How to Generate an SVG File in Node.js?

Create SVG graphics in Node.js using xmldom and rough.js. Great for backend data visualization, icons or file-based SVG creation.

Summarize with AI

Not enough time? get the key points instantly.

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 development 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: How Can The Default Node Version Be set using NVM

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.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…