Skip to content

Instantly share code, notes, and snippets.

Last active May 20, 2022 16:56
  • Star 34 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mef/7044786 to your computer and use it in GitHub Desktop.
proof-of-concept pre-rendering d3.js svgs on the server using node.js and jsdom module.
// pre-render d3 charts at server side
var d3 = require('d3')
, jsdom = require('jsdom')
, fs = require('fs')
, htmlStub = '<html><head></head><body><div id="dataviz-container"></div><script src="js/d3.v3.min.js"></script></body></html>'
features : { QuerySelector : true }
, html : htmlStub
, done : function(errors, window) {
// this callback function pre-renders the dataviz inside the html document, then export result into a static file
var el = window.document.querySelector('#dataviz-container')
, body = window.document.querySelector('body')
, circleId = 'a2324' // say, this value was dynamically retrieved from some database
// generate the dataviz
.attr('width', 600)
.attr('height', 300)
.attr('cx', 300)
.attr('cy', 150)
.attr('r', 30)
.attr('fill', '#26963c')
.attr('id', circleId) // say, this value was dynamically retrieved from some database
// make the client-side script manipulate the circle at client side)
var clientScript = "'#" + circleId + "').transition().delay(1000).attr('fill', '#f9af26')"
// save result in an html file, we could also keep it in memory, or export the interesting fragment into a database for later use
var svgsrc = window.document.innerHTML
fs.writeFile('index.html', svgsrc, function(err) {
if(err) {
console.log('error saving document', err)
} else {
console.log('The file was saved!')
} // end jsDom done callback
// no semi-column was harmed during this development
Copy link

i get the content in the "index.html" as "undefined", can you tell me why it is??

Copy link

Same here

Copy link

Line 37 should become:

var svgsrc = window.document.documentElement.innerHTML

Copy link

@Climax777 indeed that fixed it.

Copy link

Also note that jsdom need to be 3.x.x as 4.0.+ does not support node.js

Copy link

Also, if you plan on using d3.json, you need to pull the XMLHTTPRequest from here, because otherwise you get get the following error:
oresend", "progress", "load", "error"), headers = {}, request = new XMLHttpReq
ReferenceError: XMLHttpRequest is not defined

Copy link

@Climax777 mad props. Thanks so much!

Copy link

thx, here is my first pass at using node to render js (OWASP/Maturity-Models@f35b924)

Copy link

Give d3-node a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment