MilesZew
MilesZew

Reputation: 687

node.js fs how to handle all errors with the same function

I am using express to handle http requests, and the fs module to read the html, css, javascript, etc files. The problem is, if an error occurs, I want to do the exact same thing every time (log the error to the console, which is being piped to a file).

As far as I know there is no easy way to handle all of these errors with the same function, except by adding something like this to every callback:

err ? handleError(err) : doStuff()

Is there any good way to accomplish this?

If not, are there any alternatives (sync is not an option), or is the above the best way?

Upvotes: 0

Views: 83

Answers (1)

skovy
skovy

Reputation: 5650

You have a few options for abstraction. The first option is like what you outlined:

fs.readFile('index.html', (err, data) => {
  err ? handleError(err) : doStuff(data)
});

fs.readFile('style.css', (err, data) => {
  err ? handleError(err) : doStuff(data)
});

The next option is to create a different helper method for the callback:

const callback = doStuffFn => (err, data) =>
  err ? handleError(err) : doStuffFn(data);


fs.readFile('index.html', callback(doStuff));
fs.readFile('style.css', callback(doStuff));

Lastly, you could consider wrapping the entire readFile method in a helper method:

const loadFile = (file) =>
  fs.readFile(file, (err, data) =>
    err ? handleError(err) : doStuffFn(data)
  );


loadFile("index.html")
loadFile("style.css")

Upvotes: 1

Related Questions