How to use D3 in Node.js properly?

一世执手 提交于 2019-11-27 11:07:18

The correct way to use D3 within Node is to use NPM to install d3 and then to require it. You can either npm install d3 or use a package.json file, followed by npm install:

{
  "name": "my-awesome-package",
  "version": "0.0.1",
  "dependencies": {
    "d3": "3"
  }
}

Once you have d3 in your node_modules directory, load it via require:

var d3 = require("d3");

And that's it.

Regarding your other issues: Canvas is not required to use D3. The node-canvas example you linked requires canvas because it renders to a canvas. The TypeError (Cannot read property 'BSON' of undefined) appears to be related to your use of mongoose / monogdb, not D3.

Thomas Fauskanger

To use with ES6's import instead of require:

import * as d3 from 'd3';

This is perhaps obvious to any experienced babel/ES6-user, and I know this is an old question, but I came here in an attempt to figure this out. Hope this is helpful for someone.

More on import vs. require is found here.

Try d3-node, built on JS-Dom. Has helpers for D3.

I cannot see why require it. I expect d3 to work on client side after passing the data through say a socket.

You need to install jsdom using yarn or npm. Node.js does not support dom by default, thus the need to use jsdom for creating dom elements. Use d3 for all other manipulations except fetch operations. i.e d3.xml,d3.tsv

import jsdom from 'jsdom';
import * as d3 from 'd3';
const { JSDOM } = jsdom;
JSDOM.fromURL(
    'your resource url',
  ).then((dom) => {
    const doc = dom.window.document;
    const states = d3
      .select(doc)
      .select('path')
      .attr(':fme:ID');
    console.log(states);
  });

creating dom from file

JSDOM.fromURL(
    'your resource url',
  ).then((dom) => {
    const doc = dom.window.document;
}

dom from html string

const dom = new JSDOM(
  `<p>Hello
    <img src="foo.jpg">
  </p>`,
  { includeNodeLocations: true }
);

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!