Express JS how to include node-mysql object from a different file - mysql

I want to include my mysql connection from the same file(in case I have to change sql password or anything I don't want to change in a many files).
Here is my mysql.js file:
module.exports = require('mysql').createConnection(
{
host : 'localhost',
user : 'admin',
password : 'xxxxxxxx',
database : 'database'
}
);
and I want to use like this:
var connection = require(__dirname + '/../../../mysql');
connection.connect();
.
.
.
My problem is it's working only once. When I start the server I can query without any issues, but in the second query I got the following error message in the console:
"Cannot enqueue Handshake after invoking quit."
Does anybody has an idea why not working?

Apparently you no longer need to call connect() after createConnection(), it'll be handled for you on query, if you like.
From the docs:
However, a connection can also be implicitly established by invoking a
query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) { // connected!
(unless err is set) });
Depending on how you like to handle your
errors, either method may be appropriate. Any type of connection error
(handshake or network) is considered a fatal error, see the Error
Handling section for more information.
Other than that, you may be calling connect() before calling end() on the same connection, you might want to check for that.

Thanks the help, but I found a solution for my problem. I just created the variables on my mysql.js file then I exported them like this:
var host = 'localhost';
module.exports.localhost = localhost;
After I can use it on another js file:
var connection = require(__dirname + '/../../../mysql');
connection.localhost;
I found it on this article:
http://openmymind.net/2012/2/3/Node-Require-and-Exports/

Related

How can I handle MySQL disconnection on NodeJS?

First of all, I'm a beginner on NodeJS. Well, I'm using a shared hosting to my project and when the database reaches 1 minute of inactivity, NodeJS crashes and disconnects me from MySQL. Since I'm using a shared hosting, I can't edit the idle time on the MySQL config and I'll need to handle it in code.
I'm using module.exports to handle my connection, as shown below. So how can I make an auto-reconnection script to take care of my issue? Thank you.
var mysql = require('mysql');
module.exports =
{
handle: null,
connect: function(call){
this.handle = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test',
timezone: 'utc',
charset : 'utf8'
});
this.handle.connect(function (err) {
if(err) {
console.log("[MySQL] Connection error: " + err.code);
} else {
console.log("[MySQL] Successfully connected");
}
});
}
};
The node mysql module that you are using also has a connection pooling mechanism.
Check out the docs at https://github.com/mysqljs/mysql#pooling-connections
Connection pools will make you task easier. You can then store the connection pool object and use its getConnection method to obtain a connection. Make sure that you release the connection when you are done with it.
If for some reason you cant use connection pooling then you will have to listen for error event on the connection and handle it accordingly. But I strongly recommend that you use connection pool.

How to use existing wamp's MySQL databases in node.js?

I already have WAMP server installed on my machine. Can I be able to access MySQL databases created on WAMP's MySQL using node-mysql module?
Actually, I tried this code, its running without errors but unable to fetch the database(or tables):
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "database_name"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM table_name', function (error, rows, fields) {
console.log('The first field is: ', rows[0].field);
});
});
}).listen(8001);
console.log("running on localhost:8001");
Try adding request.resume(); before your 'end' event handler.
In node v0.10+, streams start out in a "paused" state that allow you to .read() specific sized chunks or you can use them like the old streams by attaching a 'data' event handler which causes the stream to be continuously read from.
Calling request.resume(); will also switch to the old stream mode, effectively discarding the request data (because there are no 'data' event handlers) so that your 'end' event handler will be called.

Connection to Mysql from NodeJS on Heroku server

ANy idea how can I connect from NodeJs to the Mysql ClearDB on Heroku?
I was able to connect to the ClearDB Mysql runing on Heroku from Navicat, I even created a table called t_users. But I'm having problems connecting from NodeJs from Heroku.
This is my code, it is very simple: everything works find until it tries to connect to MySQL
web.js:
var express = require("express");
var app = express();
app.use(express.logger());
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'us-cdbr-east-04.cleardb.com',
user : '',
password : '',
database : ''
});
connection.connect();
app.get('/', function(request, response) {
response.send('Hello World!!!! HOLA MUNDOOOOO!!!');
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
response.send('The solution is: ', rows[0].solution);
});
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
This is what I got when I run on the command line: Heroku config
C:\wamp\www\Nodejs_MySql_Heroku>heroku config
=== frozen-wave-8356 Config Vars
CLEARDB_DATABASE_URL: mysql://b32fa719432e40:87de815a#us-cdbr-east-04.cleardb.com/heroku_28437b49d76cc53?reconnect=true
PATH: bin:node_modules/.bin:/usr/local/bin:/usr/bin:/bin
This is the LOG:
http://d.pr/i/cExL
ANy idea how can I connect from NodeJs to the Mysql ClearDB on Heroku?
Thanks
Try this. Hope this will help you
mysql://b32fa719432e40:87de815a#us-cdbr-east-04.cleardb.com/heroku_28437b49d76cc53?reconnect=true
var connection = mysql.createConnection({
host : 'us-cdbr-east-04.cleardb.com',
user : 'b32fa719432e40',
password : '87de815a',
database : 'heroku_28437b49d76cc53'
});
Use this details and connect it in mySQL work bench, and import your localhost db
The base code was ok, I missed some NodeJS code.
I did a video explaining how to connect to MySqlusing NodeJS on a Heroku server, take a look:
http://www.youtube.com/watch?v=2OGHdii_42s
This is the code in case you want to see:
https://github.com/mescalito/MySql-NodeJS-Heroku
createConnections accepts config as well as connectionString.
export function createConnection(connectionUri: string | ConnectionConfig): Connection;
So below solution would work.
var connection = mysql.createConnection('mysql://b32fa719432e40:87de815a#us-cdbr-east-04.cleardb.com/heroku_28437b49d76cc53?reconnect=true);
or you can set the connection url in environment variable DATABASE_URL
var connection = mysql.createConnection(process.env.DATABASE_URL);
One should need to use pool connection for database connection to handle better mysql conncurrent request as follows
var pool = mysql.createPool({
connectionLimit : 100,
host : 'us-cdbr-iron-east-05.cleardb.net',
user : 'b5837b0f1d3d06',
password : '9d9ae3d5',
database : 'heroku_db89e2842543609',
debug : 'false'
});
It just because pool maintain the connection.release() on its own , so you do not have to bother where you should need to release the connection.
On the other hand you should need to provide user, password and database name as i mentioned in my code.
When u get provisioned from heroku then you get a cleardb database name.
on clicking clear db database button you will find username and password.
and to get database url you have to run the following commands in terminal as follows;
heroku login
heroku app -all (it shows the app list name )
heroku config --app appname (it will provide the database url).
Rest you would need to worry, just add all dependency into your package.json before pushing to heroku master.
After then you will have no problem on deploying nodejs application to heroku server.
Looking at the log timestamps, it seems like your connections are timing out. Either create a wrapper for 'getConnection' that checks the connection health and re-establishes if necessary, or try to use the mysql Connection Pool feature, which can do that for you.

How I can write this code to work properly in nodejs

I have config.js in my nodejs project
var mysql = require('mysql');
var db_name = 'node';
var client = mysql.createClient({
user: 'root',
password: 'pass',
});
client.query('USE '+db_name);
I have used it as config file for the project. How I can use this code to call a mysql query.
I have this code in user.js
var global = require('./config.js');
this.CheckUserValid = function (login, pass) {
var sql = "SELECT * FROM `user` WHERE login = ? AND pass= ?";
global.client.query(sql, [login, pass], function selectResutl(err, results, fields) {
if (!err) return results;
else
throw err;
});
}
TypeError: Cannot call method 'query' of undefined
at Object.CheckUserValid (C:\wamp\www\Node\user.js:6:19)
Can someone help me to let me know how I can do this in better way.Actually I am using asp.net mvc in my past so I have tried it. Do someone tell me the better way to write code in nodejs.
When you require() a file/module, the result you get is whatever the module is exporting through the exports property. Anything else is encapsulated in the module and cannot be accessed from the outside. In your case, at the end of config.js you can add:
exports.client = client;
This way it will be accessible whenever you require() your config.js.
This way of creating modules is defined in the CommonJS spec:
http://commonjs.org/specs/modules/1.0/
http://wiki.commonjs.org/wiki/Modules/1.1
edit: and since commonjs.org seems to be down, here is another link with information about this type of module: http://dailyjs.com/2010/10/18/modules/

nodejs and mysql connection failing?

var mysql = require('mysql');
var client = mysql.createClient({
user: 'myusername',
password: 'mypassword',
});
client.query('USE mydb');
A simple setup like this using node's mysql is returning an ECONNREFUSED error, although the credentials are correct and permissions are updated. I have even used a different node module to successfully connect/query the database using the same credentials, but the syntax of this module is in my opinion far superior.
Anyone have an idea whats causing this to go wrong?
Error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect ECONNREFUSED
In mysql.conf, comment skip-networking.
For creating the database you need to use the command CreateConnection and not createClient, make the necessary changes and that should work !
var mysql = require('mysql');
var client = mysql.createConnection({
host: 'localhost',
user: 'myusername',
password: 'mypassword',
});
client.query('USE mydb');
Note that you have not mentioned which database you are accessing !
Source for this solution:: Check NODEJS Github here