user3732793
user3732793

Reputation: 1939

Node JS Load JSON array from file

a json file has been created with pretty print like that

[
  {
    "name": "c",
    "content": 3,
    "_prototype": "item"
  },
  {
    "name": "d",
    "content": 4,
    "_prototype": "item"
  }
]

I can read the file with that

var fs = require('fs');
var arrayPath = './array.json';

function fsReadFileSynchToArray (filePath) {
    var data = JSON.parse(fs.readFileSync(filePath));
    console.log(data);
    return data;
}

var test  = arr.loadFile(arrayPath);
console.log(test);

but the output is in reverse order

[]
[ { name: 'c', content: 3, _prototype: 'item' },
  { name: 'd', content: 4, _prototype: 'item' },]

obviously the second output is shown as first. I used actually synchronous file read to avoid such an empty data stuff. Is there a way to really make sure the JSON file is completely read into an array before continuing ?

[update] arr is a module which uses

function loadFile(filePath){
    var arrLines = [];
    fs.stat(filePath, function(err, stat) {
        if(err == null) {
            arrLines = fsReadFileSynchToArray(filePath);
        } else if(err.code == 'ENOENT') {
            console.log('error: loading file ' + filePath + ' not found');
        } else {
            console.log('error: loading file', err.code);
        }
    });
    return arrLines;
}

to return the values

Upvotes: 8

Views: 31472

Answers (4)

Rahul Baby
Rahul Baby

Reputation: 209

const fs=require('fs');
var obj = JSON.parse(fs.readFileSync('file.json', 'utf8'));
console.log(obj);

Upvotes: 5

t.niese
t.niese

Reputation: 40842

Testing if a file exists before loading is not recommended and is the reason why fs.exists is deprecated:

Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.

And the way you use fs.stats is just an equivalent to the deprecated fs.exists.

So you should always assume that the file does not exits when reading it.

For a sync call you should write:

var data;

try {
   data = JSON.parse(fs.readFileSync(filePath));
} catch ( err ) {
   // handle your file not found (or other error) here
}

or

var data;

try {
   data = require('./array.json');
} catch ( err ) {
   // handle your file not found (or other error) here
}

And if you do it the async way then check the error argument of your callback function, to handle the case if the file does not exist:

fs.readFile(filePath, (err, fileContent) => {
    var data;
    if( err ) {
      // handle your file not found (or other error) here
    } else {
      data = JSON.parse(fileContent);
    }
})

Upvotes: 5

Quentin
Quentin

Reputation: 943240

fs.stat is async, so your function is async.

You want fs.fstatSync instead.

Upvotes: 5

jesusbotella
jesusbotella

Reputation: 636

As long as the file is inside your project folder (config file, i.e.) you can load it synchronously requiring it directly in NodeJS.

var test = require('./array.json');

And then the content will be loaded into your variable in the next executed sentence.

You can try to console.log it, and it will print:

[ { name: 'c', content: '3', _prototype: 'item' },
  { name: 'd', content: '4', _prototype: 'item' } ]

Right exactly in the order that the file had.

Upvotes: 28

Related Questions