Passing variable from one js to another js file in nodejs - javascript

I'm just getting started with Nodejs, so please bear with me
I store my DB setting on the first 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 :
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.
The above code return an error, which said the variable is not passed successfully to 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.
e.g., 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,
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,
connect.js:-
Changes- No need of the connectDB param, using module.exports functionality.
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;

**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. I keep a sample copy called 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);
});

Related

How to use .then method for promises with mySQL?

I know that mongodb has their own way of handling native promises with no rejection issues but I guess it doesnt work the same here with mysql. Is there anyway I can use .then in mysql? I was able to do it using more callbacks but I would like to use promises to make the solution cleaner or even use async/await if that makes it simpler too. I need to use a callback to jump to my server file, I have all my methods defined in my db file.
Server file:
app.get('/api/cows', (req, res) => {
db.reqMethods.getAll((err, data) => {
if (err) {
res.send('Error');
} else {
res.send(data);
}
});
});
db file:
const mysql = require('mysql');
const http = require('http');
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'cowlist'
});
connection.connect((err) => {
if (err) {
console.log(err);
} else {
console.log('Connected to MySQL!')
}
});
// Your Database Queries Here!!
module.exports.reqMethods = {
// GET All Cow Info
getAll: function (callback) {
const query = connection.query('SELECT * FROM cows;');
query.then(data => callback(null, data));
});
};
// callback solution that I'd like to simplify:
// getAll: function (callback) {
// connection.query('SELECT * FROM cows;', (err, data) => {
// if (err) {
// callback(err, null);
// } else {
// console.log("DATA: \n", data);
// callback(null, data);
// }
// });
// }
Yes, this is possible by using mysql2 npm package.
So in your database.js file, use this method.
const mysql = require('mysql2');
var pool_connection = mysql.createPool({
host: '127.0.0.1',
port: 3306,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 10,
multipleStatements: true
});
pool_connection.getConnection((err) => {
if (err) console.log(JSON.stringify(err));
else {
console.log('Connected!')
}
});
module.exports = pool_connection.promise();
And in your models, you require the connection as follows and make use of async-await in a try-catch block.
const con = require('/path/to/your/database_file');
module.exports = class Messages {
constructor() { }
static async getMessage(arguments_here) {
const query = "some query here with params if required. Use ? for placing params and do not use string literal to embed params.";
try {
const [response] = await con.execute(query, [params]);
return response;
} catch (error) {
console.log(error);
return null;
}
}
}
And in your controller,
const Messages = require('../models/Messages');
const someFn = async (req, res) =>{
try {
const result = await Messages.getMessages('sample_arguments');
//do something with result
}
catch(err){
console.log(err);
}
}

Node JS : use mongodb on imported module

I have a app.js that connect to a mongodb database an display it with express.My app.js is starting to be quite long. So I'm trying to do "modular design". I need to do a "timer.js" that will do some stuff in my mongodb with a timer.
I want to import this function from "checking.js" but this file require mongodb, some constant from DOTENV etc. so I need a import/export relation between them. How to do it ?
App.js (main file)
require('dotenv').config()
const POWER = process.env.POWER;
var mongoDb = require('mongodb');
var mongoClient = mongoDb.MongoClient;
const serverUrl = process.env.ENV_SERVEUR_MONGO_URL;
const useDB = process.env.ENV_MONGO_DATABASE;
app.get('/top', function (req, res) {
var resultArray = [];
mongoClient.connect(serverUrl, function (err, client) {
var db = client.db(useDB);
if (err) throw err;
var cursor = db.collection('top').find().sort({ _id: -1 });
cursor.forEach(function (doc, err) {
resultArray.push(doc);
}, function () {
client.close();
res.render('pages/top', { items: resultArray })
});
});
});
var checking = require('./checking')
Checking.js
function checkingdatabase() {
// ERROR require mongodb, variable undefined etc.
mongoClient.connect(serverUrl, function (err, client) {
var db = client.db(useDB);
if (err) throw err;
//do stuff
});
}
setInterval(checkingActiveOffer, 5000);
module.exports = Object.assign({ checkingdatabase })```
create DB.js file and share MongoDB connection
mongoose.connect(process.env.ENV_SERVEUR_MONGO_URL;, { useFindAndModify: false, useUnifiedTopology: true, useNewUrlParser: true })
.then(function (res) {
console.log('Succeeded connected to: ' + process.env.ENV_SERVEUR_MONGO_URL;);
exports.isReady = true;
exports.connection = res;
exports.con = res.connection
})
Checking.js
var db = require('./DB')
app.get('/top', function (req, res) {
db.con.collection('top').find().sort({_id:-1}).toArray()
.then(r=>{
res.render('pages/top', { items: resultArray })
})
})
You can do it in two different ways:
1 - You pass the values you need as a prop to Checking function. So this way you would pass your envs and your mongo client when you invoke Checking function. Not advisable
2 - You can, and should, declare the things you need inside the Checking file. Your envs and mongoClient can just be required there, and it will make your code cleaner.
Take a look at this code and see if that suits your use case.

Node.js Module class returns undefined

This is my database class which I want to exist only once because I want only one connection for the application and not multiple connections.
var mysql = require('mysql');
var fs = require("fs");
var eventEmitter = require("./events.js");
function Database() {
this.connection;
this.poolCluster;
var host;
var username;
var password;
var db;
var config;
var clusterConfig = {
removeNodeErrorCount: 5,
restoreNodeTimeout: 1000,
defaultSelector: 'ORDER'
};
var poolConfig = {
acquireTimeout: 10000,
waitForConnections: false,
connectionLimit: 10,
queueLimit: 0
};
this.connect = function() {
this.connection = mysql.createConnection({
host: config.mysqlHost,
user: config.mysqlUsername,
password: config.mysqlPassword,
database: config.mysqlDb
});
this.connection.connect(function(err) {
if(err) {
console.error("Connection couldn't established at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")"
+ "\nError: " + err);
return;
}
console.log("Connected to mysql server at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")");
this.poolCluster = mysql.createPoolCluster(clusterConfig);
this.poolCluster.add("APP", poolConfig);
this.poolCluster.add("ACCOUNTS", poolConfig);
this.poolCluster.add("GAME", poolConfig);
console.log("Created Connection Clusters\n- APP\n- ACCOUNTs \n- GAME");
eventEmitter.emit("MysqlConnectionReady");
});
};
this.getMainConnection = function() {
return this.connection;
};
this.getAppConnection = function() {
this.poolCluster.getConnection("APP", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
this.getAccountsConnection = function() {
this.poolCluster.getConnection("ACCOUNTS", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
this.getGameConnection = function() {
this.poolCluster.getConnection("GAME", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
fs.readFile(process.cwd() + "/config.json", 'utf8', function(err, data) {
if(err) throw err;
config = JSON.parse(data);
this.connect();
});
}
module.exports = Database:
In my code I set module.exports = Database;
When I want to use Database in another file its undefined. I want to use this in another file and I want to use only instance of that because I want only one connection for the app Im running.
But if I use require('./Database.js'j; and use the var it returns undefined
To use the pseudo-classical OOP approach, where you define a Class as a JS function (as shown in your snippet), you would instantiate an object with the new keyword.
Instead of module.exports = Database, try creating the instance and exporting that as the module, like this:
const db = new Database();
module.exports = db

node js server: issue passing a variable to a function

I am building my first node.js server to perform a mysql query and return results from the database. Everything works but now I cannot find the right way to pass a value from the url (query section) to the function that performs the query (the PollingLoop function). No problems to retrieve the url and to get the parameter in the handler function but to move it to pollingLoop I have tried almost all I know about javascript (not enough I see). This is my code now that fails to run because of the reference error in pollingLoop for hwkey that is not defined.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url'),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'flipper',
database: 'oclock',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
if (err) {
console.log(err);
}
});
// creating the server ( localhost:8000 )
app.listen(8000);
function handler(req, res) {
console.log("INCOMING REQUEST: "+req.method+" "+req.url);
req.parsed_url = url.parse(req.url, true);
var getp = req.parsed_url.query;
var hwkey = getp.hk;
console.log(hwkey);
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
function pollingLoop(){
// Doing the database query
var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs WHERE hwk="'+hwkey+'"'),
//var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs'),
flashmsgs = []; // this array will contain the result of our db query
// setting the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);
})
.on('result', function(flashmsg) {
// it fills our array looping on each user row inside the db
flashmsgs.push(flashmsg);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
flashmsgs: flashmsgs
});
} else {
console.log('The server timer was stopped because there are no more socket connections on the app')
}
});
};
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
console.log('Number of connections:' + connectionsArray.length);
// starting the loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect', function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socketID = %s got disconnected', socketIndex);
if (~socketIndex) {
connectionsArray.splice(socketIndex, 1);
}
});
console.log('A new socket is connected!');
connectionsArray.push(socket);
});
var updateSockets = function(data) {
// adding the time of the last update
data.time = new Date();
console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};
console.log('Please use your browser to navigate to http://localhost:8000');
just bring on hwkey variable out from handler
var hwkey;
function handler(req, res) { hwkey = ... }
pollingLoop(){console.log(hwkey);}

hapi and mysql on nodejs

When I run the server there are no error. But when I visit the site it starts to give out an error TypeError: Converting circular structure to JSON
my database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
module.exports = {
connection: connection
}
My products.js
var db = require('../database');
function getProducts(request) {
var product = db.connection.query('SELECT * from products', function(err) {
// connected! (unless `err` is set)
});
request.reply(product);
}
I just started with node.
update
db.connection.query('SELECT * from products', function(err, results) {
if (err) throw err;
console.log(err);
var products = results;
});
returning null on console.
update
var query = db.connection.query('SELECT * from products;', function(error, rows, fields) {
console.log(rows);
var products = rows;
});
it seems like adding ; to the end of the query did it.
Another thing is now products is not defined
function getProducts(request) {
if (request.query.name) {
request.reply(findProducts(request.query.name));
}
else {
request.reply(products);
}
}
As for the answer of the last question:
var products = query._results;

Categories