[英]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.