I have installed Node.js as below:
root@server1:~#apt-get install nodejs
Then installed the npm as below:
root@server1:~#apt-get install npm
Then installed the MySQL module inside the server directory as below:
root@server1:~#cd /var/www/
root@server1:/var/www# npm install mysql
Below is the code for node.js server (server.js) (used correct credential instead of xxx):
var mysql = require('mysql');
var db_config = {
host : 'localhost',
user : 'xxx',
password : 'xxx',
database : 'xxx'
};
var connection;
function handleDisconnect(){
connection = mysql.createConnection(db_config);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
}
else{
throw err;
}
});
}
handleDisconnect();
When I run the Node.js server like below:
root@server1:~#node /var/www/server.js
I get general error! It is below:
error when connecting to db: { [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
fatal: true }
UPDATE:
I am able to connect to MySQL from PHP (Apache2) and MySQL is working fine on my Ubuntu 12.04 server as seen below:
root@server1:~# netstat -ltnp | grep 3306
Output:
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 556/mysqld
Would you please advise how to resolve this issue? The Node.js is working on different server but I don't know why it is not working here!
Thanks.