我已使用 JSON.stringify(data) 将 Json 数据写入文件。
但是,当我使用 JSON.parse(data)
从文件中读取时,出现错误 Unexpected token u in JSON atposition 0
。当我打印 data
Undefined
function read(req, res) {
reader.on('data', function (chunk) {
response += chunk;
});
reader.on('end', function () {
console.log(response);
})
reader.on('error', function (err) {
console.log(err.stack);
});
}
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + "/" + "index.html");
})
app.get('/process_get', function (req, res) {
read(req, res);
console.log(response);
res.end(JSON.parse(response)); // Here is the error - reading from file
})
<小时/>
文件中的内容 - outputs.txt
{"first_name":"Kumar","last_name":"Roul"}
从网络路由到文件的代码 -
function write(req, res) {
response = {
first_name: req.body.first_name,
last_name: req.body.last_name
};
writer.write(JSON.stringify(response));
}
app.post('/process_post', urlencodedParser, function (req, res) {
write(req, res);
console.log(response);
res.end('Successfully written to file');
})
最佳答案
您正在尝试在读完文件之前解析该文件。由于读取内容是异步发生的,因此执行会继续。这意味着在调用 JSON.parse
时,response
是未定义
,它需要一个字符串,因此会抛出异常,因为它没有得到一个字符串。
您的read
函数需要在完成读取时发出信号,通过调用回调(使签名read(req, res,callback)
)或返回一个promise。然后你的路由应该在回调或 Promise 的 .then()
中对文件内容进行任何处理。
关于node.js - JSON 中位置 0 处出现意外标记 u - 将文件中的 JSON 字符串数据解析到 Web 服务器时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560009/