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