0

I am trying to implement a decorator on the fs.readFile function. Instead of the regular error and data params, this version should take two callbacks as arguments (both after the file name) – one to be called on success and one to be called on failure. Both callbacks only have one parameter (the data read from the file or an error object). The actual implementation simply calls fs.readFile.

I can't figure out why this isn't working, and what I'm doing wrong. Please help me debug this. Thank you.

function myReadFile(fileName, successFn, errorFn) {
    fs.readFile(fileName,'utf8', function read(errorFn, successFn) {
        if (errorFn) {
            errorFn();
        }
        else {
            successFn();
        }
    });
}

1 Answers1

0

fs.readFile callback does not return an errorFn or successFn.

Example from Node.js fs docs:

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Instead you can pass the err object into your errorFn and same for success with data.

function myReadFile(fileName, successFn, errorFn) {
  fs.readFile(fileName,'utf8', function read(err, data) {
    if (err) return errorFn(err);
    return successFn(data);
  });
}

Alternatively you could turn it into a Promise like so:

function myReadFile(fileName) {
  return new Promise((resolve, reject) => {
    fs.readFile(fileName,'utf8', function read(err, data) {
      if (err) return reject(err);
      return resolve(data);
    });
  });
}
//usage:
myReadFile('/some/file')
.then(data => {
//data here
})
.catch(err => {
//error here
});
George
  • 2,330
  • 3
  • 15
  • 36
  • Isn't `resolve(data)` & `reject(err)` ? See also [this answer](https://stackoverflow.com/a/59386381/8274517). – Firmin Martin Aug 18 '21 at 22:24
  • 1
    @FirminMartin fixed. Also there is now a promise version for fs https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_fs_promises_api – George Aug 20 '21 at 08:19