[英]Passing variable from one js to another js file in nodejs
I'm just getting started with Nodejs, so please bear with me 我刚刚开始使用Nodejs,所以请多多包涵
I store my DB setting on the first JS, connect.js
: 我将数据库设置存储在第一个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;
};
Then I stored my query in another JS file, lets call it dbManager.js
: 然后,我将查询存储在另一个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;
My goal is to pass the connection
variable from connect.js
to dbManager.js
, so I could use it for running some queries. 我的目标是将connection
变量从connect.js
传递给dbManager.js
,因此我可以使用它来运行一些查询。
The above code return an error, which said the variable is not passed successfully to dbManager.js
: 上面的代码返回一个错误,该错误表示该变量未成功传递给dbManager.js
:
ReferenceError: connectDB is not defined
Thanks in advance 提前致谢
The syntax error is because you cant define variables within an object literal using var
. 语法错误是因为您无法使用var
在对象文字中定义变量。
eg, you can't do the following, 例如,您不能执行以下操作,
var t = {
"r": 4,
var g = 5;
};
You can do this, 你可以这样做,
var t = {
"r": 4,
"g" : 5
};
And to access the properties of the object you can do, 要访问您可以执行的对象的属性,
console.log(t["r"]);
console.log(t.g);
In your code the problem is declaring a variable inside an object literal. 在您的代码中,问题是在对象文字内声明了一个变量。 Yo could do, could可以做的
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 As per OP's comments, Edit1根据OP的评论,
connect.js:- Changes- No need of the connectDB param, using module.exports
functionality. 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:- 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;
**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);
});
Will something like this work for you? 这样的事情对您有用吗? You can have a file that returns a connection object from the pool: 您可以拥有一个从池中返回连接对象的文件:
var mysql = require('mysql');
module.exports = function() {
var dbConfig = {...};
var database = mysql.createPool(dbConfig);
return {
getConnection: function(callback) {
// callback(error, connection)
database.getConnection(callback);
}
};
};
Wherever you need to use it, you can require it as follows: 无论何时需要使用它,都可以按以下要求进行使用:
var connector = require('./db-connector')();
Then use it like this: 然后像这样使用它:
connector.getConnection(function(error, connection) {
// Some code...
// Be sure to release the connection once you're done
connection.release();
});
This is how I store config data to pass around on my node server. 这就是我存储配置数据以在节点服务器上传递的方式。 I call it config.js and .gitignore it. 我称之为config.js和.gitignore。 I keep a sample copy called config.sample.js 我保留了一个名为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.
To use it I would do the following. 要使用它,我将执行以下操作。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.