我需要知道开发人员在nodeJS开发中使用的这两种方法之间的区别,以包括一个模块。
- 第一种方法(通过一次导入将其传递到应用程序中的模块,并通过将其作为参数传递或将其作为属性绑定到应用程序中来使用)
Server.js (应用入口)
let app = require('express').express();
let Router = require("./routes");
let SomeModule = require("./some-module");
.....
.....
Router.mountAPI("/api", app, SomeModule);
.....
....
routes.js (将预导入的模块传递给不同文件中的控制器)
let Ctrl1fun = require("./ctrl1");
let Ctrl2fun = require("./ctrl2");
exports.mountAPI = function(mount, app, SomeModuleToUseInController) {
app.use(mount + '/endpoint1', Ctrl1fun(SomeModuleToUseInController));
app.use(mount + '/endpoint2', Ctrl2fun(SomeModuleToUseInController));
};
ctrl1.js (端点1的控制器)
module.exports = function(SomeModule) {
....
....
//using SomeModule
}
// This file may contain some other controller function for simplicity i took only one
ctrl2.js (端点2的控制器)
module.exports = function(SomeModule) {
....
....
//using SomeModule
}
// This file may contain some other controller function for simplicity i took only one
2。第二种方法(每个控制器导入模块)
Server.js (应用入口)
let app = require('express').express();
let Router = require("./routes");
.....
.....
Router.mountAPI("/api", app);
.....
....
routes.js (在控制器中导入的模块)
let Ctrl1fun = require("./ctrl1");
let Ctrl2fun = require("./ctrl2");
exports.mountAPI = function(mount, app) {
app.use(mount + '/endpoint1', Ctrl1fun());
app.use(mount + '/endpoint2', Ctrl2fun());
};
ctrl1.js (端点1的控制器)
let SomeModule = require("./some-module");
module.exports = function() {
....
....
//using SomeModule
}
// This file may contain some other controller function for simplicity i took only one
ctrl2.js (端点2的控制器)
let SomeModule = require("./some-module");
module.exports = function() {
....
....
//using SomeModule
}
// This file may contain some other controller function for simplicity i took only one
如果我们考虑的话,女巫比较好
答案 0 :(得分:0)
在大小和性能方面的差异可以忽略不计。
第二种方法更简单,除非您需要将不同的模块注入相同的控制器类型(例如通过模型类型参数化的通用CRUD控制器