Node.js:configuration和路由在一个不同的文件

我开始一个新的Node.js应用程序,这一次,我试图正确组织代码,而不是在同一个文件中的一切。

我只在server.coffee有一个简单的设置:

 express = require 'express' app = module.exports = express.createServer() ## CONFIGURATION ## app.configure () -> app.set 'views', __dirname + '/views' app.set 'view engine', 'jade' app.use express.bodyParser() app.use express.logger('dev') app.use express.profiler() app.use express.methodOverride() app.use app.router app.use express.static(__dirname + '/public') app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) app.configure 'production', () -> app.use express.errorHandler() app.get '/', (req,res) -> res.render 'index' title: 'Express' ## SERVER ## port = process.env.PORT || 3000 app.listen port, () -> console.log "Listening on port" + port 

我有一些关于这个简单的代码的问题,我知道所有的答案取决于开发者,但我真的想做的对:

  • 如果server.js文件比app.listen ? 那里应该有什么?
  • 不应该所有的configuration都在一个不同的文件比路线? 我怎样才能删除app.get到其他文件,并让我们运行server.coffee时,它们的工作?
  • 究竟应该包含我在很多像Hubot这样的应用程序中看到的index.coffee?

我希望有人能给我一个答案,而不是“取决于”。

您可以利用require ,只需将app var作为parameter passing给方法即可。 这不是最漂亮的语法,也不是CoffeeScript中的,但你应该明白。

routes.js

 module.exports = function (app) { // set up the routes themselves app.get("/", function (req, res) { // do stuff }); }; 

app.js

 require("./routes")(app); 

如果你想更进一步,我把我的路线分成更小的组,并在它自己的子文件夹。 (比如: routes/auth.js用于login/注销, routes/main.js用于home / about / contact等)

路线/ index.js

 // export a function that accepts `app` as a param module.exports = function (app) { require("./main")(app); // add new lines for each other module, or use an array with a forEach }; 

(从之前将routes.js重命名为routes/main.js ,源本身保持不变)

Express 4使用express.Router类简化了这一点。

帮助组织路由的另一个特性是一个新的类, express.Router ,您可以使用它来创build模块化可挂载的路由处理程序。 Router实例是一个完整的中间件和路由系统, 为此,它通常被称为“迷你应用程序”。

以下示例创build一个路由器作为模块,在其中加载中间件,定义一些路由,并将其安装在主应用的path上。

在app目录下创build一个名为birds.js的路由器文件,内容如下:

 var express = require('express'); var router = express.Router(); // middleware specific to this router router.use(function timeLog(req, res, next) { console.log('Time: ', Date.now()); next(); }); // define the home page route router.get('/', function(req, res) { res.send('Birds home page'); }); // define the about route router.get('/about', function(req, res) { res.send('About birds'); }); module.exports = router; 

然后,在应用程序中加载路由器模块:

 var birds = require('./birds'); app.use('/birds', birds); 

该应用程序现在将能够处理/birds timeLog/birds/about请求,同时调用特定于该路线的timeLog中间件。

有两个类似的问题可以帮助你很多:

如何构build一个express.js应用程序?

Nodejs / Expressjs应用程序结构