node-mysql implodes without doing anything - mysql

I am trying to simply connect to a mysql db, then close the connection. My code is basically taken straight from node-mysql's guide.
require('fs').readFile('/etc/mysql/mysql-ssl-ca-cert.pem','utf8',function(err,caFile){
if(err){
console.error(err);
}else{
var connection = require('mysql').createConnection({
host : 'localhost',
user : 'root',
password : 'password',
ssl : { ca : caFile }
});
connection.connect(function(err){
if(err){
console.error(err);
}else{
console.log('connected');
}
});
connection.end(function(err) { if(err) console.error('Error On DB Close.'); });
}
});
I get the 'connected' message but then everything crashes, triggered by an uncaught error exception, what did I do wrong?
backtrace:
events.js:85
throw er; // Unhandled 'error' event
^
Error: shutdown ENOTCONN
at exports._errnoException (util.js:746:11)
at Socket.onSocketFinish (net.js:232:26)
at Socket.emit (events.js:104:17)
at finishMaybe (_stream_writable.js:484:14)
at endWritable (_stream_writable.js:493:3)
at Socket.Writable.end (_stream_writable.js:459:5)
at Socket.end (net.js:407:31)
at Protocol.<anonymous> (/Users/camdennarzt/Developer/JS/barcoding/node_modules/mysql/lib/Connection.js:85:27)
at Protocol.emit (events.js:129:20)
at Protocol.end (/Users/camdennarzt/Developer/JS/barcoding/node_modules/mysql/lib/protocol/Protocol.js:99:10)

Turned out to be a bug in node or node-mysql. See https://github.com/felixge/node-mysql/issues/1027

Related

NodeJS (Express) with MySQL - How to handle connection resets?

I'm running my website with NodeJS, I'm using the Express framework.
Since MySQL is the only database type at my hosting, I went with it.
I created a db.js file:
const mysql = require('mysql');
const con = mysql.createConnection({
host: .........
user: ...........
password: ............
database: ............
});
con.connect(function(err) {
if (err) {
//throw err;
console.error(err.message);
} else {
console.log('Connected Ro MySQL!');
}
});
module.exports = con;
And I using it like:
const db = require(path.join(__dirname, 'db'));
db.query('select * from table where name = ?', request.params.id, (error, result) => {
if (error) {
response.send(error.message);
} else {
//My Render Stuffs Here
});
}
});
My website works fine however sometimes let's say once every 2 weeks there is a MySQL connection reset, I think the database not available for a minute or so for some reason, and then my website crashes, I have to manually restart NodeJS what is very annoying.
Error in the console:
node:events:355
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
[...]
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
How should I change my codes to prevent crashing? I replaced throw err; with the console.error(err.message); but it only works when I start the website, not when a connection reset happens at runtime.
Found the solution: Replace createConnection with createPool and totally remove con.connect since createPool doesn't need it. That's it, now it's not crashes when the db unavailable.

Facing issue with mysql database with node js

i have created express app with mysql database.
when i call mysql query it works fine and then i call my view. loading view take few minute(2-3 min) and app crashed with bellow error.
events.js:287
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:310:20)
at Protocol.EventEmitter.emit (domain.js:482:12)
at Protocol._delegateError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (events.js:310:20)
at Socket.EventEmitter.emit (domain.js:482:12)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
[nodemon] app crashed - waiting for file changes before starting...
i already spend 8- 10 hours.
please help me to resolve this issue.
thanks
Update:
const options = {
user: config.get('MYSQL_USER'),
password: config.get('MYSQL_PASSWORD'),
database:config.get('DATABASE'),
host: config.get('HOST'),
port: 3306
}
const connection = mysql.createConnection(options);
connection.connect( function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:"); throw err;
} else {
console.log("Connection established.");
}
});
use below
const options = { connectionLimit :10, user:config.get('MYSQL_USER'), password: config.get('MYSQL_PASSWORD'), database:config.get('DATABASE'), host: config.get('HOST'), port: 3306 }
const connection_pool = mysql.createPool(options);
connection_pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
provide connectionLimit according to you use this is pool size of connection

The mysql server disconnects every night, how do I resolve it?

I leave my computer on 24 hours, but I still lose connection with the MySQL server. My WiFi runs smoothly and is never disconnected because I'm still able to use the internet along with my other electronics. The error message says
The server closed the connection.
Is this inferring a problem on my computer/connection or with MySQL? Or is it my codes? Please advise.
Error messages:
events.js:174
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:97:28)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:525:10)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at Connection._handleProtocolError (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:426:8)
at Protocol.emit (events.js:198:13)
at Protocol._delegateError (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:97:28)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:63:19)
My codes:
let con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: 'db',
dateStrings: 'date',
});
const handleDisconnect = () => {
con.connect(err => {
if (err) throw err;
console.log("Connected!");
});
con.on('err', err => {
console.log('db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();

Node.js server crashes after MySQL connection ends

I have a Node.js server that is hosting my webpage. I have recently set up a MySQL server and created a connection to the server. When accessing a certain page, it queries the SQL database.
My problem is that if I query the DB, it makes the connection just fine, but it will crash a little later when the server automatically closes the connection. I then tried to use con.end() after the query, but this crashes the second I access the DB. It throws the error below:
at Protocol._validateEnqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:203:16)
at Protocol._enqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:138:13)
at Connection.query (/home/pi/Documents/node_modules/mysql/lib/Connection.js:200:25)
at Handshake.con.connect (/home/pi/Documents/PageDB.js:26:9)
at Handshake.<anonymous> (/home/pi/Documents/node_modules/mysql/lib/Connection.js:502:10)
at Handshake._callback (/home/pi/Documents/node_modules/mysql/lib/Connection.js:468:16)
at Handshake.Sequence.end (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
at Handshake.Sequence.OkPacket (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)
at Protocol._parsePacket (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:278:23)
at Parser.write (/home/pi/Documents/node_modules/mysql/lib/protocol/Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
Close the database connection.
It seems to me that this is caused by the query executing after the con.end() runs. Can someone help me figure out a way to call the end function after the callback has returned with the SQL query data? Or otherwise, have my web server not crash when the connection to the DB is closed automatically? I'm open to either one. Thanks!
Code for the Node.js server is below:
//Create a connection to the db
const con = mysql.createConnection({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test',
});
router.get('/products',(req,res)=>{
con.connect((err) => {
if(err){
console.log('Error relating to connection: ' + err);
return;
}
console.log('Connection established');
con.query('SELECT * FROM ProductList',(err,rows,fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});
con.end(function(err) {
if (err) {
return console.log('error:' + err.message);
}
console.log('Close the database connection.');
});
});
Your problem is that you're con.end is being called right after you connect method. As JS is asynchronous, so it will not wait for connect to end and then continue to end instead it will call connect and put the callback on the event queue and continue to next statement where you are closing your connection. So, what you should do is move your end statement inside the callback. Try using the following code
//Create a connection to the db
const con = mysql.createConnection({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test',
});
router.get('/products', (req, res) => {
con.connect((err) => {
if (err) {
console.log('Error relating to connection: ' + err);
return;
}
console.log('Connection established');
con.query('SELECT * FROM ProductList', (err, rows, fields) => {
if (!err) {
res.send(rows);
con.end(function(err) {
if (err) {
return console.log('error:' + err.message);
}
console.log('Close the database connection.');
});
} else
console.log(err);
})
});
});

Connection timed out when using connection pooling

I get the following error when I get a connection object from a connection pool. It works sometimes but sometimes I get an error and the connection is undefined. I don't think I am supposed to get a connection timeout error because I'm using connection pool and in a connection pool you already have a few connections and you're not creating a new connection.
Can someone tell me how to handle this error and connect again.
The error at getConnection
{ [Error: connect ETIMEDOUT]
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }
The code:
var pool = mysql.createPool({
connectionLimit : 100, //important
host : '192.168.2.2',
user : 'testmysql',
password : 'test123',
database : 'tollsystem',
debug : false
});
I get the error here while using the pooled object:
app.get('/getClientList',function(req,res){
var data={
"error":1,
"clients":""
};
pool.getConnection(function(err,connection){
console.log(err);
connection.query("select * from mstrclient",function(err,rows,fields){
if(rows.length !=0){
res.json(rows);
}else{
data["error"]=1;
data["clients"]="no details found";
res.json(data);
}
connection.release();
})
});
});
The error:
connection.query("select * from mstrclient",function(err,rows,fields){
^
TypeError: Cannot read property 'query' of undefined
at D:\abhilash\Projects\Toll main aHosted\TollMain\server.js:415:15
at Handshake.onConnect (D:\abhilash\Projects\Toll main aHosted\TollMain\node
_modules\mysql\lib\Pool.js:58:9)
at Handshake.Sequence.end (D:\abhilash\Projects\Toll main aHosted\TollMain\n
ode_modules\mysql\lib\protocol\sequences\Sequence.js:85:24)
at D:\abhilash\Projects\Toll main aHosted\TollMain\node_modules\mysql\lib\pr
otocol\Protocol.js:399:18
at Array.forEach (native)
at D:\abhilash\Projects\Toll main aHosted\TollMain\node_modules\mysql\lib\pr
otocol\Protocol.js:398:13
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)