Sunny
Sunny

Reputation: 10075

How to pass express arguments to nodejs asynchronous calls

Here is the problem that I am facing in express. Somewhere in my express middleware, I want to check for the presence of a file.

 //Setting up express middeleware...
 app.use(f1);
 app.use(f2);
 ...



 function f1(req, res, next) {
   ...
   //Here I want to check if 'somefile' exists...
   fs.access('somefile', callback1, req, res, next);

 }

 //In the callback, I want to continue with the middleware... 
 function callback1(err, req, res, next) {
   if (err) {
     //Report error but continue to next middleware function - f2
     return next();
   }
   //If no error, also continue to the next middleware function - f2
   return next();
 }

 function f2(req, res, next) {

 }

How do I pass req, res, next as arguments to the callback of fs.access? The above code does not work. I suspect I need to use closures but how?

A totally different way of looking at the problem is: How do I use, for example, fs.access, itself as a express middleware function?

Upvotes: 1

Views: 51

Answers (1)

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

For me this approach have much more sense:

Assume you want to create a middleware in f1, and then have a middleware for error handling handleError, and any other middleware.

For f1 you already have the req, res in the closure so you will have access in fs.access callback.

function f1(req, res, next) {
   fs.access('somefile', (err) => {
     if (err) return next(err);
     // here you already have access to req, res
     return next();
   }
}

function f2(req, res, next) {
   // do some stuff if there is err next(err);
}

function handleError(err, req, res, next) {
   if (err) {
     // handle somehow the error or pass down to next(err);
   }
}

app.use(f1); // you pass down the err |
app.use(f2); //          ------------ |
app.use(handleError); //         <----|

Upvotes: 1

Related Questions