将变量从一个js传递到nodejs中的另一个js文件

时间:2017-08-23 03:38:17

标签: javascript mysql node.js

我刚刚开始使用Nodejs,所以请耐心等待我

我将数据库设置存储在第一个JS connect.js

var mysql = require('mysql');

module.exports = function(connectDB) {
  var connectDB = {};

  connectDB.connection = mysql.createConnection({
    //db params
  });

  connectDB.connection.connect(function(err) {
    if (err) {
      console.error('error connecting: ' + err.stack);
      return;
    }

    console.log('connected as id ' + connection.threadId);
  });

return connectDB;
};

然后我将查询存储在另一个JS文件中,我们称之为dbManager.js

var db = require('./connect')(connectDB);

var test_connection = connectDB.connection.query('SELECT * FROM `test`', function (error, results, fields) {
  console.log(results);
});

exports.test = test_connection;

我的目标是将connection变量从connect.js传递到dbManager.js,这样我就可以用它来运行一些查询。

上面的代码返回一个错误,表示该变量未成功传递给dbManager.js

ReferenceError: connectDB is not defined

提前致谢

4 个答案:

答案 0 :(得分:1)

语法错误是因为您无法使用var在对象文字中定义变量。

例如,您无法执行以下操作,

var t = {
    "r": 4,
    var g = 5;
};

你可以这样做,

var t = {
    "r": 4,
    "g" : 5
};

要访问您可以执行的对象的属性,

console.log(t["r"]);
console.log(t.g);

在您的代码中,问题是在对象文字中声明变量。哟可以做,

var connectDB = {};
connectDB.connection = mysql.createConnection({
  //DB params
});
connectDB.connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connectDB.connection.threadId);
});

return connectDB;

Edit1 根据OP的评论,

<强> connect.js: - 更改 - 不需要使用module.exports功能的connectDB参数。

  var mysql = require('mysql');
  var connectDB = {};

  connectDB.connection = mysql.createConnection({
    //db params
  });

  connectDB.connection.connect(function(err) {
    if (err) {
      console.error('error connecting: ' + err.stack);
      return;
    }

    console.log('connected as id ' + connectDB.connection.threadId);
  });

module.exports = connectDB;

<强> dbManager.js: -

var db = require('./connect');//removed the parameter
//use db variable to process queries as returned from the above require statement.
var test_connection = db.connection.query('SELECT * FROM `test`', function (error, results, fields) {
  console.log(results);
});

exports.test = test_connection;

答案 1 :(得分:1)

         **you can do it like this
            connection.js**


         var mysql=require('mysql');
         // Database Connection
         var connection = mysql.createConnection({
              host     : hostname,
              user     :username,
              password : password,
              database : databasename,
              multipleStatements:true
         });
         try {
                connection.connect();

             } catch(e) {
                  console.log('Database Connetion failed:' + e);
                    }

       module.exports=connection;


       **you can use this connection file in your dbmanager file like 
         this..**

         var db = require('./connection.js');var test_connection = 
               connection.query('SELECT * FROM test', function(err,result) { 
                         console.log(result);
                   });

答案 2 :(得分:0)

这样的事情对你有用吗?您可以拥有一个从池中返回连接对象的文件:

var mysql = require('mysql');

module.exports = function() {
    var dbConfig = {...};
    var database = mysql.createPool(dbConfig);

    return {
        getConnection: function(callback) {
            // callback(error, connection)
            database.getConnection(callback);
        }
    };
};

无论您何时需要使用它,都可以按如下方式要求:

var connector = require('./db-connector')();

然后像这样使用它:

connector.getConnection(function(error, connection) {
    // Some code...

    // Be sure to release the connection once you're done
    connection.release();
});

答案 3 :(得分:0)

这是我存储配置数据以在我的节点服务器上传递的方式。我称之为config.js和.gitignore。我保留了一个名为config.sample.js的样本副本

let config = {};
config.mysql-host='localhost' || process.env.MYSQL_HOST;
config.mysql-user='me' || process.env.MYSQL_USER;
config.mysql-secret='secret' || process.env.MYSQL_SECRET;
config.mysql-database='my_db' || process.env.MYSQL_DB;
module.exports = config; //important you don't have access to config without this line.

要使用它,我会执行以下操作。

const config = require('./config');
const mysql = require('mysql');

const connection = mysql.createConnection({
host: config.host,
user: config.user,
password: config.password,

});

connection.connect((err) => {
  if(err) {
  console.error(`error connecting: ${err.stack});
  return;
  }
  console.log(`connected`);
});

const test_connection = connectDB.connection.query('SELECT * FROM `test`'(error, results, fields) => {
  console.log(results);
});