How to read a file with async / await?

I can not understand how async / await works . I understand this a bit, but I can't get it to 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 can use readFileSync , but if so, I know that I will never understand async / wait, and I just forget the problem.

Purpose: call loadMonoCounter () and return the contents of the file.

This file is incremented each time incrementMonoCounter () is called (every page load). The file contains the buffer dump in binary format and is stored on the SSD.

No, I am making a mistake, I get an error message or undefined in the console.

+64
source share
4 answers

await/async , . API , promisify:

const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use 'await' outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

, readFileSync , . , , , , .

+129

Node v11.0.0 fs promisify:

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

readFile :

async function readFile(path) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
          reject(err);
        }
        resolve(data);
      });
    });
  }

:

await readFile("path/to/file");
+3

@Joel. 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(file);
}

main();
+2

Source: https://habr.com/ru/post/1687952/


All Articles