Voora Tarun
Voora Tarun

Reputation: 1226

Nodejs read file from data and create objects

I am trying to write a nodejs program. I have a file data.json , it contains json objects. For every object i have to add another key as review ,value as a text file data. here , I wrote code for reading data from json file, in that file , for every object I inserted key and value pairs. and stored in a array named 'matter', In below code, I used callback to post data to calling function. but callback is executing before 'for loop' in Fetchdata function. How to call callback after for loop.

var fs = require('fs');
var jf = require('jsonfile')
var file = '../data/data.json'

function readfile(str,callback) {
    fs.readFile(str, function (err, data) {
       callback && callback(data.toString());

    });
}

function Fetchdata(callback) {
    var matter = [];
    jf.readFile(file, function (err, jsonData) {
        var j=0;
        for (var i = 0; i < jsonData.length; ++i) {

            obj = jsonData[i];
            var purchase_url = obj["purchase_url"];
            if (purchase_url.indexOf("flipkart") > -1) {

                var ss = purchase_url.split("pid=");
                if (ss[1]) {
                    var s2 = ss[1].split('&');
                    readfile(s2[0],function(some){
                        "use strict";
                        obj["review"]= some;
                        matter.push(obj);
                    })
                }
            }
        }
    callback && callback(matter);

    });

}

Fetchdata(function (some) {
    console.log(some[0]);
});

Upvotes: 1

Views: 5085

Answers (1)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24650

You can use sync version of readFile

function readfile(filename,callback) {
    callback(fs.readFileSync(filename).toString())
}

The sync version of readFile, will not continue to the next line. It will return the content of the file.

You can also, do it in one line fs.readFileSync(str,'utf-8') instead of using toString.


More info

Upvotes: 3

Related Questions