组织大型 node 的好方法有哪些.js项目?
例如,一款同时使用两种express的应用程序.js和套接字.伊奥?这将包括应用程序逻辑 struct 和文件系统.
目前,我发现自己将大量代码塞进一个主js文件中,并将代码放入一个巨大的全局对象中,这让我感觉很淘气.
组织大型 node 的好方法有哪些.js项目?
例如,一款同时使用两种express的应用程序.js和套接字.伊奥?这将包括应用程序逻辑 struct 和文件系统.
目前,我发现自己将大量代码塞进一个主js文件中,并将代码放入一个巨大的全局对象中,这让我感觉很淘气.
我喜欢@david ellis最初判断的内容,你应该深入研究它以理解它,因为它是一个好的内容.然而,对于那些想要看到一个简单例子的初学者来说,我希望它更简单一些.这是我希望有人给我看的.
让我们给出一个典型的场景,您正在使用express,并且应用程序上列出了很多路由.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...
你可以想象,如果你有50条路由,这个文件可能会失控.将这些杂乱无章的东西从应用程序中移除会很好.js文件.
你要做的是在你的应用程序中创建一个"控制器"文件夹,这样你的 struct 现在看起来像这样:
app.js
/controllers
在"/controllers"中创建一个名为"index.js"的文件,然后输入以下代码.
/controllers/index.js
module.exports.set = function(app) {
// copy your routes listed in your app.js directly into here
}
从"app.js"文件中剪切并粘贴路由列表,并将其放入"/controllers/index.js"文件中.
在你的应用上.在js文件中,删除路由,并执行以下操作.
app.js
// remove your routes and replace with this code
var controllers = require('./controllers');
controllers.set(app);
现在,如果您还想拆分"/controllers/index.js"文件,那么让我们再添加一个示例,这样您就可以看到如何拆分 node .js的代码组织方式就像一个俄罗斯玩偶.
在"/controllers"中,再添加一个文件"accounts.js",并在其中放置以下内容.
/controllers/account.js
module.exports.set = function(app) {
// put more app route listings here
}
现在,在"/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);
}
正如你所想象的,你可以不断地把事情分解成越来越小的部分,把更多的文件夹放在文件夹中,如果你愿意,可以用"require"来引用.对于"/lib"或库文件,可以使用相同的概念." node _模块"已经在这样做了.
这只是众多原因之一.js编程非常有趣.
这是我回复的另一篇关于快车4号线的帖子.