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();
    })
})

};

3
  • 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 Commented Oct 19, 2020 at 7:25
  • try this: const displayTask = async () => { try { const content = await fs.promises.readFile(fileConfig, 'uts-8') return [JSON.parse(content)] } catch (e) { // handle error } }; Commented Oct 19, 2020 at 7:29
  • This will point you in the right directioin: stackoverflow.com/questions/17604866/… Commented Oct 19, 2020 at 7:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.