-1

Not getting how the below code is getting executed...

// readFile.js

const fs = require('fs');
var readFile = function readFile(fileName){
  return new Promise((resolve, reject)=>{
    fs.readFile(fileName, {encoding: 'utf-8'}, (err, contents)=>{
      if(err){
        reject(err);
      }
      resolve(contents);
    });
  });
};
module.exports.readFile = readFile;

//play.js
const {readFile} = require('./readFile');

var getText = function getTextFromFile(){

  readFile('readMe.txt').then((contents)=>{
     return contents;
  }).catch((err)=>{
    console.log(err);
  });
};
module.exports.getText = getText;

//someFile.js
const {getText} = require('./play.js');

var result = getText();
console.log(result);

When I execute someFile.js, it prints undefined. It should print the content as the then block in play.js file will only execute when the asynchronous task i.e., reading content from a file will end. Using above code, How can I return contents to some other file for example from play.js to someFile.js?

1 Answers1

-1

Promises are asynchronous, you should provide callback for this function, like this:

function getTextFromFile(cb){

  readFile('readMe.txt').then((contents)=>{
     cb(null, contents);
  }).catch((err)=>{
    console.log(err);
    cb(err);
  });
};

and you can get your file this way:

const { getText } = require('./play.js');

getText((err, data) => {
   if(err) throw new Error('file doesnt exist');
   console.log(data);
});

You can use promises here as well but the bottom line is:

You can't use return where something in your code is asynchronous.

Or even better, remove the middle man from here as it is not needed:

const {readFile} = require('./readFile.js');

readFile('example.json')
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

Of course you could use fs.readFileSync but it is a bad practice

sdooo
  • 1,851
  • 13
  • 20