Node.js – Read .json file line by line

node.js

I have a json file with json objects in it, please how can I read the json objects line by line. Is this the best way to read a json file using node.js, pardon my question, just a node.js newbie

My json file simply contains lines of json objects as:

file.json
{"name":"user1"},
{"name":"user2"},
{"name":"user3"}

and I am trying to read the file with

app.get('/s',function(req,res){
  var fs = require('fs');
var file = __dirname + '/file.json';


    fs.readFile(file, 'utf8', function (err, data) {
      if (err) {
        console.log('Error: ' + err);
        return;
      }

      data = JSON.parse(data);

      console.dir(data);
    });
    });

I get an error with that code that says "unexpected token {" just on the second line", tanks

//EDIT
It turned out my Json file was invalid because readFile reads the entire file, I changed it by putting the objects in an array:

file.json
[
{"name":"user1"},
{"name":"user2"},
{"name":"user3"}
]

Then this code reads the entire file (array)

var fs = require('fs');
var file = __dirname + '/file.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }

  data = JSON.parse(data);

  data.forEach(function(user){ 
    console.log(user.name);
  })

});

Best Answer

Node's built-in require function can read JSON and convert it to an object (or array) for you automatically, so all you need is:

var users = require(__dirname + '/file.json');

Also FYI the filename extension is optional, so you don't necessarily have to know or care if this is .js, .json or any other extension that node may learn to load in the future.