How to read file with async/await properly?

Jeremy Dicaire picture Jeremy Dicaire · Oct 21, 2017 · Viewed 99.2k times · Source

I cannot figure out how async/await works. I slightly understands 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 contain 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.

Answer

Joel picture Joel · Jun 30, 2019

Since Node v11.0.0 fs promises are available natively without promisify:

const fs = require('fs').promises;
async function loadMonoCounter() {
    const data = await fs.readFile("monolitic.txt", "binary");
    return new Buffer(data);
}