How To Get The Data From Fs.readfile Callback Function
I wanted retrieve the data into input array but I am not getting it.
Solution 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');
functiongetInput() {
returnnewPromise((resolve, reject) => {
let input = [];
fs.readFile('input.txt',(err,data)=>{
if(err) returnreject(err);
var input = data.toString().split(' ');
returnresolve(input);
})
});
}
getInput().then(input =>console.log(input));
or, you can use async
and await
to wait input, read more about async.
Post a Comment for "How To Get The Data From Fs.readfile Callback Function"