How to read file with async/await properly?

I cannot figure out how async/await works. I slightly understand it but I can’t make it work.

function loadMonoCounter() {
    fs.readFileSync("monolitic.txt", "binary", async function(err, data) {
       return await new Buffer( data);
  });
}

module.exports.read = function() {
  console.log(loadMonoCounter());
};

I know, I could use readFileSync, but if I do, I know I’ll never understand async/await and I’ll just bury the issue.

Goal: Call loadMonoCounter() and return the content of a file.

That file is incremented every time incrementMonoCounter() is called (every page load). The file contains the dump of a buffer in binary and is stored on a SSD.

No matter what I do, I get an error or undefined in the console.

12 Answers
12

Leave a Comment