在不同文件nodeJs之间共享对象

时间:2016-05-07 15:02:01

标签: javascript node.js

我在app.js和导入文件之间共享对象时遇到问题。

app.js

'use strict';

module.exports = require('./lib/express');

var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var sql = require('./lib/sqlRequete');
var app = express();

// Init database
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'master2i'
});
connection.connect();

app.post('/ajaxRequete', urlencodedParser, function(req,res){
    sql.formerSql(req.body);
});

app.listen(port,function(){
    console.log("Le serveur est lancé et écoute sur le port "+port);
});

sqlRequete.js

'use strict';

var exports = module.exports = {};

exports.formerSql=function(req){

  var SQL;

  switch(req.action){
    case 'login':
      SQL = "SELECT * FROM users WHERE pseudo ='" + req.pseudo + "' AND pass = '" + req.psw + "'";
      this.executeSql(SQL,'SELECT');
      break;
  }
}

exports.executeSql=function(requete, type){

  switch(type){

    case 'SELECT':
      connection.query(requete, function(err,rows,fields){
         if (err){
          throw err;
        }else{
          console.log('The solution is: ',rows);
        }
      });
      break;
  }
}

sqlRequete.js 无法从 app.js 访问变量和对象。 例如,我无法访问connection 有什么解决方案?我应该如何构建我的代码?

2 个答案:

答案 0 :(得分:2)

通常您将使用第三个文件(在您的情况下)。

结果文件夹结构如下:

- index.js
- lib/
|__ orm.js
|__ app.js
|__ sqlRequete.js

orm.js文件正在创建连接时返回实例:

var mysql      = require('mysql');
module.exports = function () {
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'master2i'
    });
    connection.connect();

    // IMPORTANT
    // here is where you're sharing variables between files!
    return connection;
}

但是,特别针对您的示例,我只是将SQL实例的初始化移至sqlRequete.js文件。

exports.start = function () {
    // Init database
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'master2i'
    });
    connection.connect();
}

并在app.js

上提出申请
var app = express();

sql.start();

答案 1 :(得分:2)

您可以通过以下方式将对象从app.js传递到sqlRequete.js

<强> sqlRequete.js

module.exports = function(connection){
   function formerSql(req){
     var SQL;
     switch(req.action){
        case 'login':
          SQL = "SELECT * FROM users WHERE pseudo ='" + req.pseudo + "' AND pass = '" + req.psw + "'";
          this.executeSql(SQL,'SELECT');
          break;
     }
   }

   function executeSql(requete, type){
     switch(type){
       case 'SELECT':
          connection.query(requete, function(err,rows,fields){
          if (err){
            throw err;
          }else{
            console.log('The solution is: ',rows);
          }
       });
       break;
     }
   }  
   return { 
      formerSql : formerSql,
      executeSql : executeSql
   }
}

app.js 中,传递连接对象

 var mysql      = require('mysql');
 var connection = mysql.createConnection({
   host     : 'localhost',
   user     : 'root',
   password : '',
   database : 'master2i'
 });
 connection.connect();
 var sql = require('./lib/sqlRequete')(connection);