如何在 node/mean/express 应用程序中拆分 index.js 文件?

How do I split up index.js file in a node/mean/express application?

我的 node/mongo/express 应用程序有一个非常长的 index.js 路由文件。这是结构。

app.js
/models
    Schedule.js
    Task.js
    etc...
/routes
    index.js
/public
    /javascript
    etc...

我想要这样的东西

app.js
/models
    Schedule.js
    Task.js
    etc...
/routes
    index.js
    schedule.js
    tasks.js
    etc...
/public
    /javascript
    etc...

如何拆分我的 index.js 文件?

例如,我曾尝试在我的 app.js 文件中做这样的事情

var routes = require('./routes/index');
var tasks  = require('./routes/tasks');

// later in the file

app.use('/', routes);
app.use('/tasks', tasks);

但是,当我只有 index.js 时,它并没有像以前那样找到我的任务路线。这可能是因为我把我的routes/index.js中所有以“/task”开头的路由都放在了routes/task.js中,但是为什么express不识别这个新文件中的路由?

任何建议都会有所帮助,我和我的朋友对 meanjs 的整个做事方式都非常陌生,并且基本上是将我们从各种教程中获得的内容拼凑在一起。现在我们迫切需要重构,因为 routes/index.js 的工作时间太长了。我尽了最大努力去做直觉上有意义的事情,有人可以就如何分解我们的路线文件提出建议吗?

好吧,这个问题的答案在于您如何导入(在此上下文中需要)路由器实例。这些文件中的每一个都应该使用路由器对象或类似的东西做一个module.exports,其中路由可以安装在您创建的应用程序实例上。

例如,看看我在 GitHub here, then refer to how the router object is exported for each route like this 示例中的项目中是如何做到的(在 yeoman 的帮助下)。

作为这样做的另一个例子,这是我一直在为 here. Notice that we have a slightly similar approach here, then have a look at an example route declaration (with the corresponding export) here 贡献的一个开源项目。