user7201227 user7201227 - 1 year ago 109
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);
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) + "}"
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 Source

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

You need to use

Here is the example

var fs = require('fs');

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


Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download