我正在使用 Socket.IO 开发我的第一个 Node.js 应用程序,一切都很好,但现在应用程序正在慢慢变大,我想将应用程序代码划分为不同的文件以便更好地维护。
例如,我在主文件中定义所有 Mongoose 模式和路由。下面是socket.IO 连接的所有函数。但现在我想要一个额外的模式文件、一个额外的路由文件和一个额外的函数文件。
当然,我知道可以编写自己的模块或使用 require 加载文件。这对我来说没有意义,因为如果不将它们设为全局变量,我就无法使用 app、io 或 db 等变量。如果我将它们传递给模块中的函数,我将无法更改它们。我缺少什么?我想看一个在实践中如何在不使用全局变量的情况下完成此操作的示例。
最佳答案
听起来你有一个 highly coupled应用;您很难将代码拆分为模块,因为应用程序的各个部分不应相互依赖。调查the principles of OO design可能会在这里提供帮助。
例如,如果您要将数据库逻辑从主应用程序中分离出来,您应该能够这样做,因为数据库逻辑不应依赖于 app
或 io
- 它应该能够独立工作,并且您需要
将其添加到应用程序的其他部分中才能使用它。
这是一个相当基本的示例 - 它更多是伪代码而不是实际代码,因为重点是通过示例演示模块化性,而不是编写工作应用程序。这也只是您决定构建应用程序的众多方法之一。
// =============================
// 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 的文档进行了最少的检查,但我希望它为您如何从应用程序中提取模块埋下了种子。
关于node.js - 将Node App分成不同的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52338866/