如何组织大型Node.js项目

Tho*_* II 82 node.js

组织大型Node.js项目有哪些好方法?

例如,一个使用express.js和socket.io的应用程序?这将包括应用程序逻辑结构以及文件系统.

目前,我发现自己将大量代码推入单个主js文件并将代码放入一个巨大的全局对象中,它感觉很顽皮.

Jas*_*ing 95

一个初学者的例子

我喜欢最初从@ david-ellis检查的,你应该深入研究它,因为它是一个很好的.但是,对于想要看到一个直接的例子的初学者,我会更喜欢它.这就是我希望看到有人给我看的东西.

让我们给出一个典型的场景,你正在使用express,你的app.js文件中列出了很多路由.它的内容看起来像这样:

app.js

// ... startup code omitted above

app.get('/', function(req, res) {
  res.render('index', { title : 'home' });
});
app.get('/contactus', function(req, res) {
  res.render('contactus', { title : 'contact us' });
});
app.get('/anotherpage', function(req, res) {
  res.render('anotherpage', { title : 'another page' });
});
// and so on...
Run Code Online (Sandbox Code Playgroud)

你可以想象如果你有50条路线,这个文件就会变得无法控制.从app.js文件中删除一些混乱是很好的.

你要做的是在你的应用程序中创建一个"controllers"文件夹,这样你的结构现在看起来像这样:

app.js
/controllers
Run Code Online (Sandbox Code Playgroud)

在名为"index.js"的"/ controllers"中创建一个文件,然后输入以下代码.

/controllers/index.js

module.exports.set = function(app) {
   // copy your routes listed in your app.js directly into here
}
Run Code Online (Sandbox Code Playgroud)

从"app.js"文件中剪切并粘贴路线列表,并将它们放入"/controllers/index.js"文件中.

在app.js文件中,删除您的路线并代替它们执行以下操作.

app.js

// remove your routes and replace with this code
var controllers = require('./controllers');
controllers.set(app);
Run Code Online (Sandbox Code Playgroud)

现在,如果您想将"/controllers/index.js"文件拆分,我们再添加一个示例,以便您了解Node.js如何真正像俄罗斯娃娃一样处理其代码的组织方式.

在"/ controllers"中添加一个文件"accounts.js"并在其中放置以下内容.

/controllers/account.js

module.exports.set = function(app) {
    // put more app route listings here
}
Run Code Online (Sandbox Code Playgroud)

现在在你的"/controllers/index.js文件中,添加对"account.js"的引用

/controllers/index.js

var account = require('./account.js');

module.exports.set = function(app) {
   // your routes here

   // let "account.js" set other routes
   account.set(app);
}
Run Code Online (Sandbox Code Playgroud)

您可以想象,如果您愿意,可以将更多的文件放在文件夹中并使用"require"引用.您可以对"/ lib"或库文件使用相同的概念."node_modules"已经在这样做了.

这只是node.js编程非常有趣的众多原因之一.

可管理的Express 4路由示例

这是我回复的关于快递4路线的另一篇文章.

使用Express.js嵌套路由器


mna*_*mna 10

几天前我写了一篇关于这个主题博客文章,虽然这篇文章是用法语写的,但我设置了一个GitHub回购(英文版)来展示我使用的结构的一个工作示例.

显然,这个问题没有明确的答案,但看到其他人在做什么很有意思,而且我对所有关于这个问题的意见都很感兴趣(这里讨论过,你可以看到我建议的摘要) .