I load a JSON from file as a string, try to parse it back to JSON and send as a response:
router.get('/todos', (req,res) =>{
let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{
if (err) throw err
res.send(JSON.parse(todos))
})
})
my todos.json file:
{
"todos": [
{
"id": 1,
"text": "task number 1",
"priority": 3,
"done": false
},
{
"id": 2,
"text": "task number 2",
"priority": 3,
"done": false
},
{
"id": 3,
"text": "task number 3",
"priority": 3,
"done": false
},
{
"id": 4,
"text": "task number 4",
"priority": 3,
"done": false
},
{
"id": 5,
"text": "task number 5",
"priority": 3,
"done": false
}
]
}
However I get this error:
undefined ^
SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at fs.readFile (/Users/mgonline/Desktop/programs/assessment/node-todo/routes/api/v1/todo.js:11:17) at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
I don't know why but when I console.log this string fetched from file it seems like my program change it a bit by adding a commma after last object in array of collections:
{
"id": 5,
"text": "task number 5",
"priority": 3,
"done": false
},
Which supposedly rise this error. Should I rewrite my JSON different way in order to avoid collisions?
res.send(JSON.parse(data))instead ofres.send(JSON.parse(todos))