MrManny MrManny - 1 year ago 127
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){
return console.error(err)

var bbe = JSON.parse(data.slice(0,data.length-1));


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

Answer Source

Your callback parameters are backwards, err parameter is first

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download