Can Snap.svg be used just server side with Node.js? (Not through the browser)

node.js, snap.svg, svg

Solution

You can use jsdom to simulate browser environments and natively run Snap.svg in Node.js.

Example:

const jsdom = require('jsdom');
const xmlserializer = require('xmlserializer');

jsdom.env('', [require.resolve('snapsvg')], (error, window) => {
    if (error) throw error;

    const paper = window.Snap(100, 100);

    const rect = paper.rect(20, 20, 60, 60);
    rect.attr({fill: 'red'});

    const svg = xmlserializer.serializeToString(paper.node);
    window.close();

    console.log(svg);
});

Prints:

<svg height="100" version="1.1" width="100" xmlns="http://www.w3.org/2000/svg"><desc>Created with Snap</desc><defs/><rect x="20" y="20" width="60" height="60" style="" fill="#ff0000"/></svg>

Problem

I need to create and manipulate some SVGs just with some server-side code (like with cron jobs) but I'm wondering if it's possible to use Snap.svg in this scenario where it's not included in a web page. Will this work without Snap.svg being run in a browser?

Original source