#not able to get JSON data outside the fs.readFile()

1 messages · Page 1 of 1 (latest)

mortal badger

Hello dears,
I am trying to read a JSON file and get a value out of it but it keeps giving me undefined or just the empty array
But it gives the full value when i console.log it inside the fs.readFile(),

function getName(userInput, filePath) {
  let namesArray = [];
  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      console.error("Error reading the JSON file:", err);
      return false;
    }

    const jsonData = JSON.parse(data);
    for (let i = 0; i < jsonData.length; i++) {
      if (
        jsonData[i][1] !== null
      ) {
        namesArray.push(jsonData[i][14]);
      }
    }
    if (namesArray.length === 0) {
      return false;
    } else {
      console.log(namesArray);
      // return namesArray;
    }
  });
  return namesArray;
}