0

I am trying to store JSON file content into a Javascript array, but I am getting an empty array as result.

const displayTask = () => {
  let text = [];
  fs.readFile(fileConfig, (err, data) => {
    if (err) throw err;
    const content = JSON.parse(data);
    for (let task in content) {
      text.push(task);
    }
  });
  console.log(text);
};

output -> []

The type of JSON data is: enter image description here

Thanks to everyone, found the correct solution:

const displayTask = async() => {
return await new Promise((resolve, reject) => {
    fs.readFile(fileConfig, (err, data) => {
        if(err) throw err;
        text = JSON.parse(data);
        console.log(text);
        resolve();
    })
})

};

  • Your console is getting printed before readFile is complete. Hence you are seeing the output as empty. You have to process it in your readFile callback – Vignesh Murugan Oct 19 '20 at 07:25
  • try this: const displayTask = async () => { try { const content = await fs.promises.readFile(fileConfig, 'uts-8') return [JSON.parse(content)] } catch (e) { // handle error } }; – Yakir Fitousi Oct 19 '20 at 07:29
  • This will point you in the right directioin: https://stackoverflow.com/questions/17604866/difference-between-readfile-and-readfilesync – Derek Oct 19 '20 at 07:31

0 Answers0