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.
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);
}