Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 371
user3732793 Avatar asked Oct 11 '16 15:10

user3732793


People also ask

How do I load a JSON file in node JS?

To load the data from customer. json file, we will use fs. readFile , passing it the path to our file, an optional encoding type, and a callback to receive the file data. If the file is successfully read, the contents will be passed to the callback.

Can a JSON file just be an array?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects.


2 Answers

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.

like image 78
jesusbotella Avatar answered Oct 26 '22 10:10

jesusbotella


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

You want fs.fstatSync instead.

like image 27
Quentin Avatar answered Oct 26 '22 12:10

Quentin