D3 & Node

Posted .

Using node we can create and save graphs so they can just be embedded as images rather than having to be rendered from data client-side. However this requires some additional considerations since D3 doesn’t work from node out of the box.

DOM

D3 requires a DOM but node doesn’t provide one, you could use jsdom for this.

let dom = new JSDOM()
let svg = d3.select(dom.window.document.body)
  .append("svg")
  .attr('xmlns', 'http://www.w3.org/2000/svg')

(The namespace is necessary because we’re going to write this one to disc rather than inserting it immediately into a html5 document.)

Loading data

D3’s fetch based data loading functions obviously don’t work in node so we have to load the data manually.

let csv = await fs.readFile("seattle-temps.csv")
let data = d3.csvParse(csv.toString(),
  d => ({
    date: new Date(d.date),
    temperature: +d.temp
  }))

(The use readFileSync if you don’t want to deal with the promise.)

Saving graphs

Because we want to create and save graphs locally we have to extract the raw svg and save them.

fs.writeFile(name + ".svg", svg.node().outerHTML)