0

In the code, im trying to add multiple objects into an array by using .push() method. All the objects are valid and type object when i log them using console.log but the array after the code runs is still empty.

Here's the code: app.js

const fs = require('fs');
var outdata = {};
var objArray = [];

fs.readFile('rawdata.json', 'utf8', (err, data) => {
  debugger;
  let dataObj = JSON.parse(data);             
  let tmpObj = {};
  Object.keys(dataObj).map(n => {
    let tmp = dataObj[n].search(/(\d{1,2}:\d{2}:\d{2})/g);
    if (tmp !== -1) {
      tmpObj = {};
      tmpObj.crafttime = dataObj[n];
      return true;
    } else {
      //make obj
      let value = dataObj[n].split(' ');
      tmpObj.type = value[0]; //type
      tmpObj.name = value[1].toLowerCase(); //name
      tmpObj.link = `abc.com/${value[1]}`;

      //appends obj
      objArray.push(tmpObj);
      return false; //break
    }
  });
});
console.log(objArray);

The console output expected :

[{obj},{obj},...]

output

[]

1 Answers1

0

You have to put your console.log just one line above - in your fs.readFile callback - because it is asynchronous and the log is executed before the file is read.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35