node.js - JSON 中位置 0 处出现意外标记 u - 将文件中的 JSON 字符串数据解析到 Web 服务器时

标签 node.js file express input stream

我已使用 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/

相关文章:

javascript - 如何在特定时间跨度内进行具有速率限制的异步 API 调用?

c# - "File in use"写入文本文件时出错

Node.js,表达可变权重

node.js - 使用 Redis 和 Nodejs 创建 Restful API

node.js - 如何在express上处理客户端的post数据

c - 文件结束的原因

node.js - 如何枚举nodejs+express中的所有 session ?

mysql - 如何在Sequelize中的belongsToMany关系中包含模型

javascript - 将客户端套接字连接到 cookie

multithreading - 多线程文件访问