Created
January 29, 2014 15:36
-
-
Save dmohl/8690440 to your computer and use it in GitHub Desktop.
Example of running D3 in Node without requiring Python and Contextify. The example is a slightly modified version of the example at http://mango-is.com/blog/engineering/pre-render-d3-js-charts-at-server-side.html with some code from https://github.com/mbostock/d3/blob/master/index.js.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs') | |
, jsdom = require('jsdom-nogyp') | |
, htmlStub = '<html><head></head><body><div id="dataviz-container"></div><script src="./d3.min.js"></script></body></html>' | |
, document = jsdom.jsdom(htmlStub) | |
, window = document.createWindow() | |
, globals = {}; | |
jsdom.env({ features : { QuerySelector : true }, html : htmlStub, done : function(errors, win) { | |
// stash globals | |
if ('window' in global) globals.window = global.window; | |
global.window = window; | |
if ('document' in global) globals.document = global.document; | |
global.document = document; | |
// https://github.com/chad3814/CSSStyleDeclaration/issues/3 | |
var CSSStyleDeclaration_prototype = window.CSSStyleDeclaration.prototype, | |
CSSStyleDeclaration_setProperty = CSSStyleDeclaration_prototype.setProperty; | |
CSSStyleDeclaration_prototype.setProperty = function(name, value, priority) { | |
return CSSStyleDeclaration_setProperty.call(this, name + "", value == null ? null : value + "", priority == null ? null : priority + ""); | |
}; | |
var d3 = require('./d3.min.js'); | |
var el = window.document.querySelector('#dataviz-container') | |
, body = window.document.querySelector('body') | |
, circleId = 'a2324'; | |
d3.select(el) | |
.append('svg:svg') | |
.attr('width', 600) | |
.attr('height', 300) | |
.append('circle') | |
.attr('cx', 300) | |
.attr('cy', 150) | |
.attr('r', 30) | |
.attr('fill', '#26963c') | |
.attr('id', circleId); | |
var clientScript = "d3.select('#" + circleId + "').transition().delay(1000).attr('fill', '#f9af26')"; | |
d3.select(body) | |
.append('script') | |
.html(clientScript); | |
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!') | |
} | |
}); | |
// restore globals | |
if ('window' in globals) global.window = globals.window; | |
else delete global.window; | |
if ('document' in globals) global.document = globals.document; | |
else delete global.document; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment