0

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!

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Well you need to add error handling as readFileSync will throw exceptions. But everything else looks ok.
code.runnable.com/VVPFREu0oblSpIch/read-file-sync-for-node-js Also make sure you wrap all in try/catch block. And you should be fine.
I want to parse that data. How do I do that?
Check my answer. I give you example
var data = fs.readFileSync('/uploads/' + bbbid + '/device'+count+ '.json' , 'utf8');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.