How to read file with async/await properly?

前端 未结 7 2114
时光说笑
时光说笑 2020-11-29 17:12

I cannot figure out how async/await works. I slightly understands it but I can\'t make it work.



        
相关标签:
7条回答
  • 2020-11-29 17:51

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

    0 讨论(0)
  • 2020-11-29 18:06

    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);
    }
    
    0 讨论(0)
  • 2020-11-29 18:08

    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'));
    
    0 讨论(0)
  • 2020-11-29 18:09

    To use await/async you need methods that return promises. The core API functions don't do that without wrappers like 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);
    })
    

    As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

    0 讨论(0)
  • 2020-11-29 18:13

    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);
    }
    
    0 讨论(0)
  • 2020-11-29 18:14

    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");
    
    0 讨论(0)
提交回复
热议问题