node.js - 如何将明确的参数传递给nodejs异步调用

标签 node.js express node-modules

这是我在 express 中遇到的问题。 在我的快速中间件中的某个位置,我想检查文件是否存在。

 //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) {

 }

如何将 req、res、next 作为参数传递给 fs.access 的回调? 上面的代码不起作用。我怀疑我需要使用闭包,但如何使用?

看待问题的一种完全不同的方式是:例如,我如何使用 fs.access 本身作为快速中间件函数?

最佳答案

对我来说,这种方法更有意义:

假设您要在 f1 中创建一个中间件,然后有一个用于错误处理 handleError 的中间件,以及任何其他中间件。

对于f1,您已经在闭包中拥有了 req, res,因此您可以在 fs.access 回调中进行访问。

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); //         <----|

关于node.js - 如何将明确的参数传递给nodejs异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45868492/

相关文章:

javascript - 如何循环遍历页面的链接并将所有http链接写入java脚本中的文件中

javascript - 如何从 .ejs 获取值到 javascript 文件

node.js - 在 Phonegap/Cordova 项目中使用 Node 包

javascript - 升级到 Angular 8 后 d3.js 运行时错误

node.js - module.exports 导出默认 : how to rewrite in a proper way?

mysql - 带有 MySQL 的 OpenShift 上的 SailsJS

javascript - 无法在范围之外访问函数结果

javascript - 无法使用 Node js process.kill(pid) 终止 linux 进程

javascript - 获取 jsdom 窗口变量

node.js - Node Express 测试模拟 res.status(status).json(obj)