简体   繁体   中英

How do I read a file in an async function without promises?

I'm trying to read/write to a file in an async function (example):

async readWrite() {
      // Create a variable representing the path to a .txt
      const file = 'file.txt';

      // Write "test" to the file
      fs.writeFileAsync(file, 'test');
      // Log the contents to console
      console.log(fs.readFileAsync(file));
}

But whenever I run it I always get the error:

(node:13480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'map' of null

I tried using bluebird by installing it using npm install bluebird in my project directory and adding:

const Bluebird = require('bluebird');
const fs = Bluebird.promisifyAll(require('fs'));

to my index.js (main) file, as well as adding:

const fs = require('fs');

to every file where I wan't to use fs.

I still get the same error and can only narrow down the problem to fs through commenting out stuff.

Any help would be appreciated.

First of all: async function s return a promise. So by definition, you are already using a promise.

Second, there is no fs.writeFileAsync . You are looking for fs.writeFile https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

With promises, making use of the power of async functions

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

// Promisify the fs.writeFile and fs.readFile
const write = util.promisify(fs.writeFile);
const read = util.promisify(fs.readFile);

async readWrite() {
  // Create a variable representing the path to a .txt
  const file = 'file.txt';

  // Write "test" to the file
  await write(file, 'test');
  // Log the contents to console
  const contents = await read(file, 'utf8');
  console.log(contents);
}

In the above: We used util.promisify to turn the nodejs callback style using functions to promises. Inside an async function, you can use the await keyword to store the resolved contents of a promise to a const/let/var.

Further reading material: https://ponyfoo.com/articles/understanding-javascript-async-await

Without promises, callback-style

const fs = require('fs');
async readWrite() {
  // Create a variable representing the path to a .txt
  const file = 'file.txt';

  // Write "test" to the file
  fs.writeFile(file, 'test', err => {
    if (!err) fs.readFile(file, 'utf8', (err, contents)=> {
      console.log(contents);
    })
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM