简体   繁体   中英

Node.js readFile async callback UnhandledPromiseRejectionWarning

I am trying to supply an async function to node.js's fs.readFile callback, but I am not too sure how to handle the errors thrown by the callback. Normally, with non-async callback, you would do:

// error is handled

fs.readFile('/file_does_not_exist.txt', 'utf8', (err, data) => {
  if (err) throw err
  // do things here
})

And if a readFile error occurs, it is handled properly. But as soon as I use an async function as a callback:

// UnhandledPromiseRejectionWarning

fs.readFile('/file_does_not_exist.txt', 'utf8', async (err, data) => {
  if (err) throw err
  // await for things here
})

Then it throws UnhandledPromiseRejectionWarning when a readFile error occurs. How would you try to handle the err in this scenario? I have tried try catch in the body of the callback, but it doesn't work. The only other solution is to wrap the async function inside another function.

`

fs.readFile('/file_does_not_exist.txt', 'utf8', async (err, data) => {
         //if (err) throw err
        /* replace it to */ if (err){
                //handle error here
         }else{
                // await for things here
        }
})

`

It's expected that you get an UnhandledPromiseRejectionWarning error, because throwing an error isn't the same as handling it.

If your goal is to exit the process:

if (err) {
  process.exit(1);
}

If you want to continue running the program but somehow handle the error upstream, you'll end up mixing callbacks and promises, which typically leads to convoluted code.

Instead, I would suggest using fs/promises , the Promise-based implementation of fs :

const fs = require('node:fs/promises');
… 
async function readFile() {
  try {
    const data = await fs.readFile('/file_does_not_exist.txt', 'utf8');
    // process file data
  } catch(e) {
    console.error('caught error reading file', e);
    // here you can cleanly exit the process or re-throw `e` to properly handle it upstream
  }
}

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