Node.js:不同文件中的配置和路由

2022-01-24 00:00:00 node.js express javascript coffeescript

我正在启动一个新的 Node.js 应用程序,这一次,我试图正确地组织代码,而不是将所有内容都放在同一个文件中.

I am starting a new Node.js app and this time, I'm trying to organize the code correctly instead of having everything in the same file.

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

I only have a simple setup now at 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

我对这个简单的代码有一些疑问,我知道所有答案都取决于开发人员,但我真的想把它做对:

I have some questions regarding that simple code and I know that all the answers depend on the developer but I really want to do it right:

  • server.js 文件应该比 app.listen 多吗?究竟应该有什么?
  • 不应该所有配置都在与路由不同的文件中吗?如何在运行 server.coffee 时将 app.get 删除到其他文件并使其工作?
  • 我在 Hubot 等许多应用程序中看到的 index.coffee 究竟应该包含什么?
  • Should the server.js file have more than the app.listen? What should be there exactly?
  • Shouldn't all the configurations be in a different file than the routes? How can I remove the app.get to other file and make them work when I run the server.coffee?
  • What exactly should contain the index.coffee that I see in a lot of apps like Hubot?

我希望有人能给我一个取决于"以外的答案.

I hope someone can give me an answer other than "it depends".

推荐答案

您可以利用 require,只需将 app var 作为参数传递给方法.它不是最漂亮的语法,在 CoffeeScript 中也不是,但你应该明白.

You can leverage require, and simply pass the app var in as a parameter to a method. It's not the prettiest syntax, nor is it in CoffeeScript, but you should get the idea.

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

app.js

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

如果您想更进一步,我会将路线分成更小的组,并放在它自己的子文件夹中.(例如:routes/auth.js 用于登录/注销,routes/main.js 用于 home/about/contact 等)

If you want to take it a step further, I separate my routes into smaller groups, and in it's own subfolder. (like: routes/auth.js for login/logout, routes/main.js for home/about/contact and so on)

// 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,源本身保持不变)

(rename routes.js from before as routes/main.js, the source itself remains the same)

相关文章