2017-08-24 47 views
1

这是我在express中遇到的问题。 在我的快递中间件的某处,我想检查文件的存在。如何将快捷参数传递给nodejs异步调用

//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,资源,未来作为参数fs.access的回调? 上面的代码不起作用。我怀疑我需要使用闭包,但是如何?

查看问题的完全不同的方式是:如何将fs.access本身用作明确的中间件功能?

+0

我认为这样会更好地描述你正在尝试做的事情,因为目前你正在尝试做什么并没有什么意义...... –

回答

1

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

假设你想创建一个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); //   <----| 
相关问题