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
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.
JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects.
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.
fs.stat
is async, so your function is async.
You want fs.fstatSync
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With