繁体   English   中英

使用npm安装的d3库不会加载json文件

[英]d3 library installed with npm doesn't load json file

我刚刚使用npm安装了d3。 package.json它显示依赖项"d3": "^4.11.0" version,

我试图用下面的代码加载一个简单的json文件:

const d3 = require('d3')

d3.json('jsonfile.json', (err, data) => {
  if (err) {
    console.log(err)
  }
  data.keys.map((t) => {
    console.log(t)
  })
})

但是我得到了这个错误:

SyntaxError: Unexpected token T in JSON at position 0

json文件实际上是可以的。 我使用此工具进行了验证: https : //codebeautify.org/jsonvalidator

但是,当我删除此行const d3 = require('d3')并将脚本直接插入HTML文件中时:

<script type='text/javascript' src='/js/d3.min.js'></script>

...使用3.5.5版本,已加载json文件。

d3版本^4.11.0中有什么新功能可以加载本地文件?

如果要将代码作为节点应用程序运行,则必须使用完整的URL加载json:

const d3 = require('d3');
//use full url to where the json file is
d3.json('http://localhost:8080/jsonfile.json', (err, data) => {
  if (err) {
    console.log(err)
  }
  data.keys.map((t) => {
    console.log(t)
  })
});

如果要将代码作为节点应用程序运行并从磁盘加载文件,则可以这样加载文件:

fs = require('fs');
const readFile = (file,encoding) => 
  new Promise(
    (resolve,reject)=>
      fs.readFile(
        file
        ,encoding
        ,(err,data) => {
          if(err !== null){
            reject(err);return;
          }
          resolve(data);
        }
      )
    )
;

readFile("./static/jsonfile.json",'utf8')
.then(
  data =>
    data.toString()
).then(
  text =>
    console.log("Got file content:\n",text)
  ,err =>
    console.error("Failed to load file:",err)
);

如果您的代码在浏览器中运行,但是您想使用npm作为依赖项管理,则可以使用requirejs(旧方法)或webpack(更好的方法是学习和设置,但要复杂一些)。 如果您在浏览器中使用代码,我想知道如何在const d3 = require('d3');上不会出现错误const d3 = require('d3');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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