I am trying to write a database manager module in node.js for some of the common queries I am going to use in a server app. I want to test the module. However, my code does not connect to the database before I do the queries. How can I arrange my code in such way, it connects to db before the queries, not after them?
Code:
var mysql = require('mysql');
var conn = mysql.createConnection(
{
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
conn.connect(function(error)
{
if ( error) throw error;
console.log('->connected to database');
});
// user as json
getUserData = function(username)
{
conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username +
'\"' , function (error, result, fields)
{
if (error) throw error;
return result;
});
}
console.log('result->' + JSON.stringify(getUserData('eness')));
conn.end();
Output:
result->undefined
->connected to database