Node.js Module class returns undefined - javascript

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

Related

get a callback from a seperate file in node js

I have two file in my node js app server.js and database.js
//server.js
var db = require('./database.js');
var express = require('express');
var app = express();
var server = app.listen(8081, '000.00.00.000',function(){
var host = server.address().address;
var port = server.address().port
console.log('App listening');
})
app.get('/',function(req,res){
res.end("Hello Jamian");
})
app.get('/insertuser',function(req,res){
console.log("insert user called")
var result = new db.insertUser();
console.log("result " + result)
});
and
//database.js
var mysql = require('mysql');
var con = mysql.createConnection({
host:"localhost",
user:"0000",
password:"0000",
database: "aaaa"
});
con.connect(function(err){
if(err) throw err;
console.log("DB Connected");
});
module.exports = {
insertUser: function () {
console.log("module exported");
var SQL_insert_user = "insert into users(username,useremail,usermobile,userpassword,activetoken) values('darren','darren#yahoo.in','980000000','password','ASKDO5615F')";
con.query(SQL_insert_user,function(err,result){
if(err) throw err;
console.log("data inserted");
return result;
});
},
bar: function () {
console.log("bar called")
}
};
I need a callback from the insertUser function in database.js so i can call a res.end("data inserted"). however it seems con.query is going async, hence I am getting a blank value when I try to log result in server.js from get/insertuser in server.js
data inserted
insert user called
module exported
result {}
data inserted
Use promises. Either native or from a library.
Here's how you could do it with a promise:
insertUser: function(){
return new Promise(function(reject, resolve){
var SQL_insert_user = "insert into users(username,useremail,usermobile,userpassword,activetoken) values('darren','darren#yahoo.in','980000000','password','ASKDO5615F')";
con.query(SQL_insert_user,function(err,result){
if(err) reject(err);
else resolve(result);
});
});
},
Then you can use it your other file like this:
insertUser()
.then(function(result){
// do something with the result
})
.catch(function(err){
// Oh no! there was an error!
});
in your server js do
app.get('/insertuser',function(req,res){
console.log("insert user called")
var result = new db.insertUser(function(result) {
console.log("result " + result)
});
});
and in your database do
module.exports = {
insertUser: function (cb) {
console.log("module exported");
var SQL_insert_user = "insert into users(username,useremail,usermobile,userpassword,activetoken) values('darren','darren#yahoo.in','980000000','password','ASKDO5615F')";
con.query(SQL_insert_user,function(err,result){
if(err) throw err;
console.log("data inserted");
cb(result);
});
},
bar: function () {
console.log("bar called")
}
};

Passing variable from one js to another js file in nodejs

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);
});

node.js and routing: emit by class

newbie question is following:
I'm having a hard time to get the EventEmitter to work. I already considered the documentation and several best-practive tutorials like this one: https://code.tutsplus.com/tutorials/managing-the-asynchronous-nature-of-nodejs--net-36183
The problem is, that within the user.js (Class) this.emit() hits nothing. userRoutes.js doesn't trigger any user.on(), and I really don't know why..
Any suggestions are appreciated. Hints for better structuring also. My goals are centralized endpoints (well-readable) and reusing the code for every module (like user or products/orders) within different modules, e.g. calling to update an order out of the user-endpoint.
So, let's assume, you have your node.js-Server with a module configuration, router and several classes, like this:
/server.js
global.__base = __dirname + "/";
var server = require("http").createServer();
var routes = require("./v2");
var initialize = require(global.__base + "config");
var app = initialize.globalModules();
app.use('/api/v2', routes);
app.listen('8090');
/config.js
var db;
module.exports = {
globalModules: function() {
// load the global modules
var app = require("express")();
var bodyParser = require("body-parser");
//setUp app
app.use(bodyParser.json());
return app;
},
db: function() {
var mysql = require('mysql');
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'node_docx'
});
db.connect(function(err) {
if (err) throw err;
});
return db;
}
};
/v2/index.js (routes)
var userRoutes = require('./userRoutes');
var routes = require('express').Router();
routes.use("/user", userRoutes);
//routes.use("/product", productRoutes);
//routes.use("/order", orderRoutes);
//...
routes.use('*', function(req, res) {
res.status(404).send({code: 404, message: 'ERR', data: "Unknown target."});
});
module.exports = routes;
/v2/userRoutes.js
var User = require("./routes/user.js");
var user = new User();
var route = require('express').Router();
route.get("/", function(req, res) {
user.on('error', function(err) {
res.status(400).send({code: 900, message: 'ERR', data: err});
});
user.on('failure', function() {
res.status(404).send({code: 901, message: 'ERR', data: "User not found!"});
});
user.on('success', function(result) {
res.status(200).send({code: 200, message: 'OK', data: result});
});
user.getAll();
});
module.exports = route;
/v2/routes/user.js
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var initialize = require(global.__base + "/config");
var db = initialize.db();
function User() {
EventEmitter.call(this); //edit: added, but has not solved the problem
var self = this; //solved it!
function _checkForErrors(error, rows, reason) {
if (error) {
self.emit('error', error);
return true;
}
if (rows.length < 1) {
self.emit('failure', reason);
return true;
}
return false;
}
function _getData(error, rows) {
if (_checkForErrors(error, rows)) {
return false;
} else {
self.emit('success', rows);
}
}
function getAll() {
db.query("SELECT * FROM patient", _getData);
}
this.getAll = getAll;
}
util.inherits(User, EventEmitter);
module.exports = User;
It's quite simple, you forgot EventEmiter.call(this) in function User.
function User() {
EventEmitter.call(this);
var self = this;
function _checkForErrors(error, rows, reason) {
if (error) {
self.emit('error', error);
return true;
}
if (rows.length < 1) {
self.emit('failure', reason);
return true;
}
return false;
}
function _getData(error, rows) {
if (_checkForErrors(error, rows)) {
return false;
} else {
self.emit('success', rows);
}
}
function getAll() {
db.query("SELECT * FROM patient", _getData);
}
this.getAll = getAll;
}

in node.js with express req.session is undefined inside my require() module

I'm wondering why req.session.username is undefined in the tag >>>DOESNT WORK<<< while it does work in the tag >>>THIS DOES WORK<<< . I brought in req as an argument to my module but it seems I'm supposed to do something else? The /ajax route is accessed via a ajax call and it does set the session variable in >>>THIS DOES WORK<<<
//index.js file
var express = require('express');
var router = express.Router();
var app = express();
var functions = require('../public/javascripts/functions.js');
router.post('/ajax', function(req, res , next){
var username = req.param("username");
var password = req.param("password");
var operation = req.param("operation");
else if (operation === "validate")
{
async.series([
function()
{
functions.validate(username, password, req);
}
], function(err,result)
{
if (err)
return console.log(err);
console.log(result);
});
//req.session.username = "yaryar"; >>>THIS DOES WORK<<<
}
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
module.exports = router;
functions.js file:
module.exports = {
validate: function(username, password, req) {
var url = 'mongodb://localhost';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
MongoClient.connect(url, function(err, db)
{
assert.equal(null, err);
console.log("Connected correctly to server.");
var cursor = db.collection('users').find({username : username});
cursor.each(function(err,doc,req)
{
assert.equal(err, null);
if (doc != null)
{
console.log("user found: " + doc.username);
req.session.username = "ttyy"; // >>>DOESNT WORK<<<
return true
}
else
{
console.log("user not found");
return false;
}
});
//db.close();
});
}
};
you're overwriting req by doing cursor.each(function(err,doc,req) change it to cursor.each(function(err,doc,arr) and it will work

Use database in child_process

I try to execute in another process some database operations, so I used child_process for that.
But I cannot update my database from this process: there is no connection.
app.js
...
mongoose.connect(mongodb://localhost/myDb);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database');
});
// When the connection is disconnected
db.on('disconnected', function () {
console.log('disconnected');
});
child_express.exec('node ' + __dirname + '/path/to/my/my-service.js', (err, stdout, stderr) => {
if(err) console.error(stderr);
else console.log(stdout);
});
my-service.js
MyModel = require('../models/my-model');
...
myModel.updateBook(book);
my-model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// console.log(mongoose.connection.readyState); => 0
var bookSchema = new Schema({..});
var Book = mongoose.model('Book', bookSchema);
exports.updateBook = function(book) {
Book.find({ bookId: book.bookId }, function (err, book) {
console.log(book);
});
};
How can I get the connection from child_process?

Categories