如何模块化nodejs + expressjs代码 [英] How to modularize nodejs+expressjs code

查看:85
本文介绍了如何模块化nodejs + expressjs代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的nodejs-expressjs应用程序中将server.js作为主文件。在客户端,我使用角度js进行模板化(不在服务器端使用JADE / EJS)。我想在服务器上模块化这个server.js文件,因为我的应用程序增长可能不太好。

  var express = require('express'); 
var app = express();
var fs = require(fs);

/ **
*会话
* /
var session = require('express-session');
app.use(session({secret:'!23',resave:false,saveUninitialized:false}));


var bodyParser = require('body-parser');
var mysql = require('mysql');
var async = require('async');

/ **
*连接到MySQL
* /
var config = require(./ config);
var db = config.database;
var connection = mysql.createPool(db);

app.use(bodyParser.json());

//创建应用程序/ x-www-form-urlencoded解析器
var urlencodedParser = bodyParser.urlencoded({extended:false});

/ **
*提供web目录
* /
app.use(express.static('public'));


app.post('/ abc',function(req,res){
// code
});
app.post('/ xyz',function(req,res){
// code
});
app.post('/ test',function(req,res){
// code
});
var server = app.listen(config.port);

假设我想在分离文件中添加以下方法,可以说test.js.我该怎么做?

  app.post('/ test',function(req,res){
// code
});


解决方案

在主模块server.js中:
删除:

  app.post('/ abc',function(req,res){
// code
});
app.post('/ xyz',function(req,res){
// code
});
app.post('/ test',function(req,res){
// code
});

并更改为

  app.use(要求( ./路由器)); 

在同一目录中创建文件router.js,并在其中添加:

  var express = require('express'); 
var router = new express.Router();
router.post('/ abc',function(req,res){
// code
});
router.post('/ xyz',function(req,res){
// code
});
router.post('/ test',function(req,res){
// code
});
module.exports = router;



Edit1:

您可以将路由分割成多个文件应用程序可能有几百条路线)。有几个策略如何使它,我显示一个:



创建新的文件,您配置更多路由(例如routes / route1.js,routes / route2.js) :
在router.js中添加:

  router.use(require(./ routes / route1)) ; 
router.use(require(./ routes / route2));

在route1.js和route2.js中创建与router.js类似的结构:

  var express = require('express'); 
var router = new express.Router();
//路线的地方
module.exports = router;

编辑2:OP在评论中提出问题:


但是如果我连接到sql并在每个模块中使用查询,那么为什么我要
需要在每个模块中添加mysql连接代码? blockquote>

当我们将代码分解成多个模块时,我们应该尝试尽可能少的依赖。但是,每个模块或其他资源饥饿任务中的多个连接可能是一个不好的选择。



我们可以在多个模块中共享公共资源实例。有多种方式可以完成这项任务。



我将向您显示基本的(我将忽略全局变量污染):



假设我们拥有对象 myCommonObjectInstance ,我们需要将其传递给主模块()中的多个模块



1) server.js ):

  app.set('someName',myCommonObjectInstance); 

现在您可以做的路线:

  router.post('/ test',function(req,res){
var myCommonObjectInstance = req.app.get('someName');
//其他代码
});主模块( server.js )中的

2)可以创建中间件添加新的要素到req或res:

  app.use(function(req,res,next){
req .myCommonObjectInstance = myCommonObjectInstance;
next(); //非常重要!!!
});

现在在路由模块中:

  router.post('/ test',function(req,res){
var myCommonObjectInstance = req.myCommonObjectInstance;
//其他代码
} );

3)第三种流行的方法是注入模块,查看此文章了解更多详细信息: https://stackoverflow.com/a/9700884/4138339

简而言之,您可以使用参数创建模块和导出函数。当您在主模块中导入功能时,您传递参数。



您的一个模块

  module.exports = function(myCommonObjectInstance ){
//你的代码,你可以访问myCommonObjectInstance
};

在主模块

 要求( './ yourmodule')(myCommonObjectInstance); 


I've server.js as main file in my nodejs-expressjs application. In client side I am using angular js for templating(not using JADE/EJS on server side). I want to modularise this server.js file on the server as it may not be good if my application grows.

var express = require('express');
var app = express();
var fs = require("fs");

/**
 *  Session
 */
var session = require('express-session');
app.use(session({secret: '!23',resave: false,saveUninitialized:false}));


var bodyParser = require('body-parser');
var mysql      = require('mysql');
var async      = require('async');

/**
 * Connect to MySQL
 */
var config = require("./config");
var db = config.database;
var connection = mysql.createPool(db);

app.use( bodyParser.json() );  

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

/**
 *  Provide web directory
 */
app.use(express.static('public'));


app.post('/abc', function (req, res) {
   //code 
});
  app.post('/xyz', function (req, res) {
   //code 
});
 app.post('/test', function (req, res) {
   //code 
});
var server = app.listen(config.port);

Suppose I want to add following method in seperate file lets say test.js. How would I do that?

 app.post('/test', function (req, res) {
       //code 
    });

解决方案

In your main module server.js: remove :

app.post('/abc', function (req, res) {
   //code 
});
  app.post('/xyz', function (req, res) {
   //code 
});
 app.post('/test', function (req, res) {
   //code 
});

and change to

app.use(require("./router"));

create file router.js in same directory and add there:

var express = require('express');
var router = new express.Router();
router.post('/abc', function (req, res) {
   //code 
});
router.post('/xyz', function (req, res) {
   //code 
});
router.post('/test', function (req, res) {
   //code 
});
module.exports = router;

Edit1:

You can split your routes into multiple files (in big application there may be hundreds routes). There are few strategies how to make it, I show one:

Create new files where you config more routes (e.g. routes/route1.js, routes/route2.js): In router.js add:

router.use(require("./routes/route1"));
router.use(require("./routes/route2"));

In route1.js and route2.js create similar structure to router.js:

var express = require('express');
var router = new express.Router();
//place for routes
module.exports = router;

Edit2: OP asked a question in comment:

but if i connect to sql and use queries in every module then why do i need to add mysql connection code in every module?

When we split code into multiple modules we should try to have as little dependence as possible. But multiple connections in each module or other resource hungry tasks may be a poor choice.

We can share common resource instances in multiple modules. There is a large variety of ways how to accomplish this task.

I will show you just the basic ones (I will ignore globals pollution ):

Lets assume that we have object myCommonObjectInstance, and we need to pass it to multiple modules

1) in main module (server.js):

app.set('someName',myCommonObjectInstance);

Now in routes you can do:

router.post('/test', function (req, res) {
   var myCommonObjectInstance = req.app.get('someName');
  //other code
});

2) in main module (server.js) lets create middleware which add new propery to req or res:

app.use(function(req,res,next){
  req.myCommonObjectInstance = myCommonObjectInstance;
  next();//very important!!!
});

and now in your route modules:

router.post('/test', function (req, res) {
   var myCommonObjectInstance = req.myCommonObjectInstance; 
  //other code
});

3)Third popular method is injection to module, check this post for more details: https://stackoverflow.com/a/9700884/4138339
In short you create module and export function with arguments. When you import function in your main module you pass arguments.

one of yours modules

module.exports = function (myCommonObjectInstance) {
//your code and you have access to myCommonObjectInstance
};

In main module

require('./yourmodule')(myCommonObjectInstance);

这篇关于如何模块化nodejs + expressjs代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆