Skip to content

Instantly share code, notes, and snippets.

@dotob
Created January 6, 2016 14:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotob/37b80cbbd9f0e1f135db to your computer and use it in GitHub Desktop.
Save dotob/37b80cbbd9f0e1f135db to your computer and use it in GitHub Desktop.
Directly render and serve d3 visualizations from a nodejs server.
# Start `coffee d3-server.coffee`
# Then visit http://localhost:1337/
# originally from: https://gist.github.com/Caged/6407459
d3 = require('d3')
http = require('http')
jsdom = require('jsdom')
http.createServer((req, res) ->
# Chrome automatically sends a requests for favicons
# Looks like https://code.google.com/p/chromium/issues/detail?id=39402 isn't
# fixed or this is a regression.
if req.url.indexOf('favicon.ico') != -1
res.statusCode = 404
return
console.log "in request"
jsdom.env({
html:'',
features:{ QuerySelector:true } #you need query selector for D3 to work
done: (errors, window) ->
console.log "in jsdom.done"
window.d3 = d3.select(window.document) #get d3 into the dom
pad =
t: 10
r: 10
b: 50
l: 40
width = 800 - (pad.l) - (pad.r)
height = 500 - (pad.t) - (pad.b)
samples = d3.range(10).map(d3.random.normal(10, 5))
x = d3.scale.linear().domain([0, samples.length - 1]).range([0, width])
y = d3.scale.linear().domain([0, d3.max(samples)]).range([height, 0 ])
xAxis = d3.svg.axis().scale(x).orient('bottom').tickSize(height)
yAxis = d3.svg.axis().scale(y).orient('left')
line = d3.svg.line().interpolate('basis').x((d, i) -> x(i)).y(y)
vis = window.d3.select('body').html('').append('svg').attr('xmlns', 'http://www.w3.org/2000/svg').attr('xmlns:xlink', 'http://www.w3.org/1999/xlink').attr('width', width + pad.l + pad.r).attr('height', height + pad.t + pad.b).append('g').attr('transform', 'translate(' + pad.l + ',' + pad.t + ')')
vis.append('g').attr('class', 'x axis').call xAxis
vis.append('g').attr('class', 'y axis').call yAxis
vis.selectAll('.axis text').style('fill', '#888').style('font-family', 'Helvetica Neue').style 'font-size', 11
vis.selectAll('.axis line').style('stroke', '#eee').style 'stroke-width', 1
vis.selectAll('.domain').style 'display', 'none'
vis.selectAll('path.samples').data([ samples ]).enter().append('path').attr('class', 'samples').attr('d', line).style('fill', 'none').style('stroke', '#c00').style 'stroke-width', 2
console.log "before response"
res.writeHead 200, 'Content-Type': 'image/svg+xml'
res.end window.d3.select('body').html()
console.log "after response"
})
).listen 1337, '127.0.0.1'
console.log 'Server running at http://127.0.0.1:1337/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment