如何在 Node.js 中正确使用 D3?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9948350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:24:46  来源:igfitidea点击:

How to use D3 in Node.js properly?

node.jsd3.js

提问by pland

I've been trying to invoke D3 within Node.js. I tried firstly to import d3.v2.js from D3's website with the script tag, but then read this thread:

我一直在尝试在 Node.js 中调用 D3。我首先尝试使用 script 标签从 D3 的网站导入 d3.v2.js,但随后阅读了此线程:

I want to run d3 from a Cakefile

我想从 Cakefile 运行 d3

Where D3's author advises one should 'npm install d3'...I did this, and I can successfully invoke it in node console:

D3 的作者建议应该'npm install d3'...我这样做了,我可以在节点控制台中成功调用它:

dpc@ananda:$ node
> var d3 = require("d3");
undefined
> d3.version;
'2.8.1' 

However, when trying to invoke it from app.js with 'node app.js', I get:

但是,当尝试使用“node app.js”从 app.js 调用它时,我得到:

node.js:201
    throw e; // process.nextTick error, or 'error' event on first tick
          ^
TypeError: Cannot read property 'BSON' of undefined
at     /Users/dpc/Dropbox/sync/Business/MindfulSound/Development/nad.am/nadam/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js:45:44

I realise that elsewhere, D3's author has clearly specified that one should require the canvas:

我意识到在其他地方,D3 的作者已经明确指出应该需要画布:

https://github.com/mbostock/d3/blob/master/examples/node-canvas/us-counties.js

https://github.com/mbostock/d3/blob/master/examples/node-canvas/us-counties.js

as:

作为:

var Canvas = require("canvas");

but even then, (and even if specifically requiring index.js instead of d3.v2.js in a require statement in app.js), I can't get the below to work within a Jade template:

但即便如此,(即使在 app.js 的 require 语句中特别需要 index.js 而不是 d3.v2.js),我也无法在 Jade 模板中使用以下内容:

- script('/javascripts/d3.v2.js')
h1 Dashboard
  section.css-table
    section.two-column
      section.cell
        hr.grey
        h2 Statistics
        #mainGraph
            script(type="text/javascript") 
              var Canvas = require("canvas");
              var w = 400,
                  h = 400,
                  r = Math.min(w, h) / 2,
                  data = d3.range(10).map(Math.random).sort(d3.descending),
                  color = d3.scale.category20(),
                  arc = d3.svg.arc().outerRadius(r),
                  donut = d3.layout.pie();
              var vis = d3.select("body").append("svg")
                  .data([data])
                  .attr("width", w)
                  .attr("height", h);
              var arcs = vis.selectAll("g.arc")
                  .data(donut)
                  .enter().append("g")
                  .attr("class", "arc")
                  .attr("transform", "translate(" + r + "," + r + ")");
              var paths = arcs.append("path")
                  .attr("fill", function(d, i) { return color(i); });
              paths.transition()
                  .ease("bounce")
                  .duration(2000)
                  .attrTween("d", tweenPie);
              paths.transition()
                  .ease("elastic")
                  .delay(function(d, i) { return 2000 + i * 50; })
                  .duration(750)
                  .attrTween("d", tweenDonut);

              function tweenPie(b) {
                b.innerRadius = 0;
                var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
                return function(t) {
                  return arc(i(t));
                };
              }

              function tweenDonut(b) {
                b.innerRadius = r * .6;
                var i = d3.interpolate({innerRadius: 0}, b);
                return function(t) {
                  return arc(i(t));
                };

      section.cell
        hr.grey
        h2 Achievements

回答by mbostock

The correct way to use D3 within Node is to use NPM to install d3 and then to requireit. You can either npm install d3or use a package.jsonfile, followed by npm install:

在 Node 中使用 D3 的正确方法是使用 NPM 安装 d3 然后到require它。您可以npm install d3或使用package.json文件,后跟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:

在 node_modules 目录中有 d3 后,通过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.

关于您的其他问题:Canvas 不需要使用 D3。您链接的节点画布示例需要画布,因为它渲染到画布。TypeError(无法读取未定义的属性“BSON”)似乎与您使用 mongoose / monogdb 而不是 D3 有关。

回答by Thomas Fauskanger

To use with ES6's importinstead of require:

与 ES6 一起使用import而不是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.

对于任何有经验的 babel/ES6 用户来说,这可能是显而易见的,我知道这是一个老问题,但我来到这里是为了解决这个问题。希望这对某人有帮助。

More on importvs. requireis found here.

这里可以找到更多关于importvs.require信息。

回答by Joma sim

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

您需要使用 yarn 或 npm 安装 jsdom。Node.js 默认不支持 dom,因此需要使用 jsdom 来创建 dom 元素。将 d3 用于除获取操作之外的所有其他操作。即 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

从文件创建 dom

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

dom from html string

来自 html 字符串的 dom

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