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.
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.
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.