Sadeghbayan
Sadeghbayan

Reputation: 1163

Read txt file in if Statement in nodejs

I'm saving a some variable as array of object in txt file , the question is how can i read them and compare it with another variable in for loop .

Thanks .

The format that i Saved in txt file :

[{"sekke":"445,675","halfsekke":"145,600"}]  

And the code that i want to read is :
NodeJs:

var array = fs.readFileSync('data.txt').toString().split("\n");
            console.log(array[0]['sekke'])
            for (var key in array[0]['sekke']) {
                console.log("key " + key + " has value " + array);
            }  

which is wrong , how can i read achive something like this ?

if (array['sekke] == 100){
console.log("is ok");
}

Upvotes: 3

Views: 628

Answers (2)

Subburaj
Subburaj

Reputation: 5192

Try with the below code:

fs.readFile('data.txt', 'utf8', function read(err, data) {
       if (err) {
         throw err;
       }
       data = JSON.parse(data);
       var dataObject = data[0];
       for (i=0;i<Object.keys(dataObject).length;i++) {
           var ss = dataObject[i];
           var key = Object.keys(ss);
          for(varj=0;j<ss[key];j++){
             //your if condition logic
          }
       }  
    });

Upvotes: 3

Taavi
Taavi

Reputation: 165

You need to parse the string back to JSON if you want to use it like an object. If your file is a collection of arrays (1 array per line) then split it by \n like you do and then parse it with JSON.parse. You would need to run that on each line separately thought so use a map or a loop. If your file however is one big array of objects then just read it in and then parse the whole thing with JSON.parse.

Also, consider using the asynchronous version of readFile as using readFileSync will block the whole node.js app while it's reading (that becomes a problem as the file gets bigger)

Upvotes: 2

Related Questions