user3732793 user3732793 - 1 month ago 8
Javascript Question

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

Answer

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

You want fs.fstatSync instead.