Unexpected token u in JSON at position 0 - while p

2019-08-04 06:19发布

问题:

I have written Json data into the file using JSON.stringify(data). but, when I read from the file using JSON.parse(data), I get an error Unexpected token u in JSON at position 0 . It prints Undefined when I print data

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
})

Contents in the file - outputs.txt

{"first_name":"Kumar","last_name":"Roul"}

Code to route from web to file -

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');
})

回答1:

You're trying to parse the file before you've finished reading it. Since reading the contents happens asynchronously, execution continues. This means response is undefined at the time you call JSON.parse, which requires a string and therefore throws an exception since it's not getting one.

Your read function needs to signal when it has finished reading, either by invoking a callback (making the signature read(req, res, callback)) or returning a promise. Then your route should do any processing of the file contents in the callback or the promise's .then().