Creating an SVG file with D3 and Node.js

On a recent work project, we were using the D3 library to create some graphs. But the graphs were on a page that we also needed to export to PDF and so we needed some static versions of those graphs to use with a <img> tag. At first, I thought this was going to require using a different command line library that could help generate the same file but wasn’t happy with the prospect of two separate code libraries to get the same graphing.

Since we’re JavaScript to make the graphs, let’s see if we can run that graphing code with Node.js and save that output to a file. And it turns out this is fairly simple.

First, we need to get Node setup with a few packages. We’ll need: d3 and xmldom.

Next, we’ll take start with this example doughnut graph. So we’ll take that code and load it into a script we can use with node:

This will run the graph code for us in node when we run: node graph.js. But we still want this saved out into a file. This is where xmldom comes into play:

The second script is similar to the first, but we’ve add the xmldom module so we can serialize the object to XML and added fs module so we can save the data to a file.

And you’re done! Well, kinda. This will likely save the SVG file with capitalized XML tags, which you will have to convert to lowercase to have a working SVG file: http://stackoverflow.com/questions/20693235/get-lowercase-tag-names-with-xmldom-xmlserializer-in-node-js/20704228