2

const fs = require('fs');
let input = [];
fs.readFile('input.txt',(err,data)=>{
    if(err) throw err;
    input = data.toString().split(' ');
})
console.log(input);

I wanted retrieve the data into input array but I am not getting it.

  • You can't access a variable inside a callback, it will be always `undefined` because you are trying to access before its get finished. – Subburaj Dec 18 '19 at 06:02
  • Your `console` won't wait that callback to finish. It fires before callback ends. – Daniyal Lukmanov Dec 18 '19 at 06:03
  • `console.log(input);` in callback function. – hoangdv Dec 18 '19 at 06:04
  • You should wrap with `Promise` and resolve the result inside the callback. Then do what you need. – Daniyal Lukmanov Dec 18 '19 at 06:04
  • thing is that whatever data i am getting , i wanted to get that data outside this function so, i can use that in my program but i am getting an empty array. just help me out in getting that data so that i can access it throughout my program – Shreyash Kaushal Dec 18 '19 at 06:12
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – nicholaswmin Dec 18 '19 at 06:13

1 Answers1

1

callbacks functions means what do you want to do when data comes?

which means node will start read file and implement next line, without waiting data to came before implement your console.log.

You can make it as a function that returns promise like:

const fs = require('fs');

function getInput() {
    return new Promise((resolve, reject) => {
        let input = [];
        fs.readFile('input.txt',(err,data)=>{
            if(err) return reject(err);
            var input = data.toString().split(' ');
            return resolve(input);
        })
    });
}

getInput().then(input => console.log(input));

or, you can use async and await to wait input, read more about async.

Nimer Awad
  • 3,967
  • 3
  • 17
  • 31