[node.js] How to read file with async/await properly?

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.

This question is related to node.js asynchronous readfile

The answer is


There is a fs.readFileSync( path, options ) method, which is synchronous.


You can easily wrap the readFile command with a promise like so:

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

then use:

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

To keep it succint and retain all functionality of fs:

const fs = require('fs');
const fsPromises = fs.promises;

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

Importing fs and fs.promises separately will give access to the entire fs API while also keeping it more readable... So that something like the next example is easily accomplished.

// the 'next example'
fsPromises.access('monolitic.txt', fs.constants.R_OK | fs.constants.W_OK)
    .then(() => console.log('can access'))
    .catch(() => console.error('cannot access'));

This is TypeScript version of @Joel's answer. It is usable after Node 11.0:

import { promises as fs } from 'fs';

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

You can use fs.promises available natively since Node v11.0.0

import fs from 'fs';

const readFile = async filePath => {
  try {
    const data = await fs.promises.readFile(filePath, 'utf8')
    return data
  }
  catch(err) {
    console.log(err)
  }
}

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

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to asynchronous

How to read file with async/await properly? Use Async/Await with Axios in React.js Waiting until the task finishes How to reject in async/await syntax? React - Display loading screen while DOM is rendering? angular 2 how to return data from subscribe How do I access store state in React Redux? SyntaxError: Unexpected token function - Async Await Nodejs Why does .json() return a promise? Why is setState in reactjs Async instead of Sync?

Examples related to readfile

How to read file with async/await properly? ReadFile in Base64 Nodejs How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? How do I read a file line by line in VB Script? open read and close a file in 1 line of code Reading file using fscanf() in C Where to put a textfile I want to use in eclipse?