2014-11-03 100 views
2

我正在寻找一种更好的方式来管理我在快速路由器中的逻辑。 这是一个代码片段:如何将快速路由器拆分为单独的文件?

router.get('/get', function(req, res) { 

    if(typeof req.query.category !== undefined){ 

    //do something 

    } 

}); 

...但这里puting我的逻辑使文件很容易生长。

不过,我觉得这一点:。

if(typeof req.query.category !== undefined){ 

    var gallery = new Gallery(req.query.category) 

} 

这样我就可以在单独的文件

1)如果在单独的文件中存在变种库(即galleryManager.js)我怎么能包括文件处理的东西在我的路由器? 2)你使用什么方法?

回答

3

这通常是我如何做到的。我绝不认为这是做到这一点的最佳方式。但它是一种适合我的方法,可以让事情更有条理。

app.js

var express = require('express'); 
var app = express(); 

app.configure(function() { 
    .. view engine stuff .. 
    app.set('views', __dirname + '/views'); 
    app.use(app.router); 
    app.use("/static", express.static(__dirname + '/static')); 
}); 

require('./controllers/index.js')(app); 
require('./controllers/page2.js')(app); 

//server 
var port = process.env.PORT || 5000; 
app.listen(port); 
console.log('Listening on port ', port); 

index.js控制器或路由器

module.exports = function(app) 
{ 
    app.get('/', function (req, res) {  
     res.render('index', { }); 
    }); 
} 

文件结构

-controller 
     -index.js 
     -page2.js 
    -static 
    -css 
    -js 
    -img 
    -views 
    -index. (ejs, jade, mustache) // or whatever you prefer 
    app.js 
    package.json 

DEMO:

https://github.com/krishollenbeck/express-boilerplate

1

galleryManager.js文件应该是这个样子:

var Gallery = function Gallery(){ 
//... 
} 
//... 
module.exports.Gallery = Gallery; 

在你的路由器/控制器,导入做到以下几点:

var Gallery = require('./galleryManager').Gallery 

在上面的要求中,您必须放入文件的路径。这个例子假定这些文件都在同一个目录中