NodeJS – module.export & fileRead value return to Caller Class

I have readmsgfile.js file which has module.exports and fs.readFile function in it which reads a File and return the data after some operation.

I would like to return the msgBody from readmsgfile class but the Caller Class A always gets "Undefined" in the line code var respondMsg. I tried to return the value out side of fs.readfile scope but did not work.

what modifications has to be done to get the msgBody var value from readmsgfile file to caller Class A

readmsgfile.js
--------------------
const fs = require("fs");

var msgBody;

module.exports = {
  readMSGFile: async function (filepath) {

   let path = filepath;
    var regex = /\\/g;
    const pathOfString = path.replace(regex, "/");

      fs.readFile(pathOfString, function (err, data) {
      var msgBody = Sum Operation Done! ;
      return msgBody;
    });

   return msgBody;
  },
  
};


Class A:
--------------------------
const readFile = require("../readmsgfile");

Async function(){
var respondMsg = await readFile.readMSGFile(detailsoffile);
console.log(respondMsg);
}

62 thoughts on “NodeJS – module.export & fileRead value return to Caller Class”

Leave a Comment