Rajesh Nayak
Rajesh Nayak

Reputation: 73

How to add Promises in readFile function in node js

fs.readFile(answer, 'utf8', function (err, data) {
                    var dataArray = data.split(/\r?\n/).filter(entry => entry.trim() != '');
                 console.log(dataArray);  // **Line 1**
                 });
                 console.log(dataArray);  // **Line2**
        }

Above code line 2 executed first then line 1 executed

Upvotes: 0

Views: 56

Answers (2)

MrfksIV
MrfksIV

Reputation: 930

Try the following:

function readFilePromisified(file) {
   return new Promise( (resolve, reject) => {
      fs.readFile(file, 'utf8', function (err, data) {
         if (err) {
            reject(err);
         } 
         const dataArray = data.split(/\r?\n/).filter(entry => entry.trim() != '');
         console.log(dataArray);  // **Line 1**
         resolve(dataArray);

      });

   });

}

You can then use async/await :

( async () => {
   const dataArray = await readFilePromisified(file); // this will print **Line 1** before it returns
   console.log(dataArray); **Line 2**
})();

Upvotes: 0

Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

You can use readFileSync for achieving synchronousy.

var data = fs.readFileSync(answer, 'utf8');
var dataArray = data.split(/\r?\n/).filter(entry => entry.trim() != '');
console.log(dataArray);

Upvotes: 1

Related Questions