user7201227 user7201227 - 14 days ago 7
JSON Question

NodeJS need to concatenate JSON using custom structure

Hi I am trying to create a JSON file using all the JSON files in a particular directory. I want it to be updated any time I add a new file to the directory. So, I am writing the code for this in the 'post' part of my file upload page. I have the following code:

for (i = 0; i < files; i++) {
console.log('Entered For loop');
console.log('Count:', count);
console.log('Count:', sensor);
fs.readFile('/uploads/' + bbbid + '/device'+count+ '.json' , 'utf8', function (err, data) {
if (err) throw err; // we'll not consider error handling for now
var obj = JSON.parse(data);
JSON.stringify(obj);
//console.log(myfiles[i]);
var ddl = require('/uploads/' + bbbid + '/device' +sensor+ '.json');
//var ddl = require('/uploads/' + bbbid + '/device' + count + '.json');
cddl = cddl + ", {" + obj.DDL.Sensor.Description.Verbose_Description + ":" + JSON.stringify(ddl) + "}"
JSON.stringify(cddl);
console.log(cddl);
count++;
sensor++;
console.log('Count:', count);
console.log('Sensor:', sensor);
});

}


I have initialized count and sensor to 1 before the post method begins. The output I get:

Entered For loop
Count: 2
Count: 2
Entered For loop
Count: 2
Count: 2


Can we not use fs.readFile in the for loop? I think my loop exits before going in the readfile function. Help please!

Answer

For loop is sync and fs.ReadFile async. Your assumption is correct.

You need to use

https://nodejs.org/api/fs.html#fs_fs_readfilesync_file_options

Here is the example

var fs = require('fs');

var contents = fs.readFileSync('package.json');

console.log(JSON.parse(contents));

Hope this helps.