简体   繁体   中英

Directly render and serve d3 visualizations from a nodejs server

https://gist.github.com/Caged/6407459

I tried the above link code but it shows the following error message: TypeError: Cannot read property 'querySelector' of undefined

Can you please tell me where is the problem or any solution?

Thank you.

The error is comming from the line

d3.select('body')

This selection searchs in DOM an element 'body', but NodeJS does not provide a DOM. DOM is usually provided by browsers. In NodeJS you have to specify a DOM implementation. This is explained in D3 Documentation :

https://github.com/mbostock/d3/wiki#browser--platform-support

D3 also runs on Node.js. Use npm install d3 to install it.

Note that because Node itself lacks a DOM and multiple DOM implementations exist for it (eg, JSDOM), you'll need to explicitly pass in a DOM element to your d3 methods like so:

var d3 = require("d3"), jsdom = require("jsdom");

var document = jsdom.jsdom(), svg = d3.select(document.body).append("svg");

You could try to fork this project : https://github.com/gregjopa/d3-server-side-demo . It uses jsdom as a DOM implementation as suggested by D3 Doc.

There's a handy package for this, try npm install d3-node

A bunch of examples too. https://github.com/bradoyler/d3-node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM