【发布时间】:2025-12-28 22:30:17
【问题描述】:
我正在尝试使用 fs 读取外部 json 文件,然后记录它,但它不起作用。在我的 json 文件中,我只有一个数组要读取:
{
"tags": [ "blah", "blah1", "etc..."
]
}
我正在使用异步 readFile 函数来读取它
...
const tagsjson = require('../tags.json');
var tags;
...
fs.readFile(tagsjson, 'utf8', function(err,data){
if(err) throw err;
tags = data;
})
console.log(tags)
我不知道有什么问题,我试过 JSON.parse(data) 但它也不起作用,我使用的是原始数据,因为我想在阅读后将该标签发送给客户端。
【问题讨论】:
-
...但它不起作用 什么不起作用?你有任何错误吗?还是因为
readFile的异步调用有问题(因为console.log(tags)没有回调)? -
我正在使用 try catch 并将其记录在浏览器控制台中,
Failed to load resource: the server responded with a status of 500 (Internal Server Error) -
文件名应该是例如一个字符串,
const tagsjson = require('../tags.json');看起来有点不对。喜欢fs.readFile('../tags.json', 'utf8', (err, data) => { ...。 -
哦,它记录了这个
The system cannot open the device or file specified让我试试你告诉我的
标签: arrays node.js json express fs