聽起來好像你有一個highly coupled應用程序;你很難將你的代碼分解成模塊,因爲不應該依賴於彼此的應用程序塊。調查the principles of OO design可能會在這裏幫助。
例如,如果要將數據庫邏輯從主應用程序中分離出來,應該可以這樣做,因爲數據庫邏輯不應該依賴於app
或io
- 它應該能夠使用它的自己的,而你require
它到你的應用程序的其他部分使用它。
這是一個相當基本的例子 - 它比實際代碼更僞代碼,因爲重點是通過示例演示模塊化,而不是寫一個工作的應用程序。這也只是您決定構建應用程序的許多方法中的一種。
// =============================
// db.js
var mongoose = require('mongoose');
mongoose.connect(/* ... */);
module.exports = {
User: require('./models/user');
OtherModel: require('./models/other_model');
};
// =============================
// models/user.js (similar for models/other_model.js)
var mongoose = require('mongoose');
var User = new mongoose.Schema({ /* ... */ });
module.exports = mongoose.model('User', User);
// =============================
// routes.js
var db = require('./db');
var User = db.User;
var OtherModel = db.OtherModel;
// This module exports a function, which we call call with
// our Express application and Socket.IO server as arguments
// so that we can access them if we need them.
module.exports = function(app, io) {
app.get('/', function(req, res) {
// home page logic ...
});
app.post('/users/:id', function(req, res) {
User.create(/* ... */);
});
};
// =============================
// realtime.js
var db = require('./db');
var OtherModel = db.OtherModel;
module.exports = function(io) {
io.sockets.on('connection', function(socket) {
socket.on('someEvent', function() {
OtherModel.find(/* ... */);
});
});
};
// =============================
// application.js
var express = require('express');
var sio = require('socket.io');
var routes = require('./routes');
var realtime = require('./realtime');
var app = express();
var server = http.createServer(app);
var io = sio.listen(server);
// all your app.use() and app.configure() here...
// Load in the routes by calling the function we
// exported in routes.js
routes(app, io);
// Similarly with our realtime module.
realtime(io);
server.listen(8080);
這是所有寫了我的頭與各種API的文檔的最小檢查的頂部,但我希望它的植物,你會如何從應用程序解壓模塊的種子。
這對於一般新增節點和模塊結構的人員非常有用。這就像一個魅力,正如你所說,我可以看到如何可以有很多方法來做到這一點。 – Deminetix
非常感謝,它的工作 –