MrManny MrManny - 23 days ago 6
Javascript Question

Parsing JSON file in NodeJS

Having some issues parsing json files using node.
Whenever I try parsing the Json I get some wierd Buffer 7b 0d output in my console. I tried using a sample.json file to test if it was just the file that I was using initially but, same results. Heres the code:

router.get('/', function(req, res){

fs.readFile('./routes/sample.json', function(data, err){
if(err)
return console.error(err)


var bbe = JSON.parse(data.slice(0,data.length-1));
res.render('bbe',{});
console.log(JSON.stringify(data.toString()));
});
})


Sample.JSON:

{
"firstname": "John",
"lastname": "Doe",
"age": "23"
}

Answer

Your callback parameters are backwards, err parameter is first

https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

The callback is passed two arguments (err, data), where data is the contents of the file.