Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 431
Chad Avatar asked Feb 03 '14 16:02

Chad


People also ask

Does node JS run in the browser or server?

js is a server-side JavaScript run-time environment. It's open-source, including Google's V8 engine, libuv for cross-platform compatibility, and a core library. Notably, Node. js does not expose a global "window" object, since it does not run within a browser.

Is node js only for server-side?

Node (or more formally Node. js) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS).

How node JS works on server-side?

Node. js is a JavaScript framework for writing server-side applications. In its simplest form it allows you to trigger small JavaScript programs from the command line without any browser involved. For example, assuming node is installed if you write a JavaScript program in a file called hello.


1 Answers

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>
like image 55
hakatashi Avatar answered Sep 20 '22 02:09

hakatashi