The class:
const mysql = require('mysql');
module.exports = function () {
this.connection = mysql.createConnection({
host : 'localhost',
user : 'USER',
password : 'PASSWORD',
database : 'DATABASE',
multipleStatements: true
});
this.query = (sql, args) => {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err );
resolve( rows );
});
});
};
this.close = () => {
return async () => {
try {
this.connection.end(err => {
if (err) throw err;
return;
});
} catch(e) {
return e;
}
}
};
};
In index i call it like this:
const Database = require('./server/modules/mysql'),
connection = new Database();
The problem:
Overnight mysql crashes:
[nodemon] starting `node index.js`
listening on port 420
events.js:292
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
[... lines matching original stack trace ...]
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
[nodemon] app crashed - waiting for file changes before starting...
I'm using Nodemon and a simple restart to the application solves the issue until the next morning (or next long period of not coding.)
I'm not really using close() anywhere or after anything since in the docs it says it's not needed, just query().
but clearly i get a timeout somewhere somehow, like i should deal with the opening and closing of connection.
Do i need to close connections after making queries in my app?
Is there a way to set the timeout limit or dealing with him?
Am i just setting it up wrong or using wrong/outdated tool?
Thanks.
Related
I need help with socket.io-redis-adapter as their document on Client Error Handling seems to be gone.
I do not know how this error with Redis occur, has it got to do with Redis pub/sub? My redis server is in working error through out.
I've searched through forums and github. I've followed the recommended actions as follows. However, I'm still not able to catch the errors below, and it's causing my app to crash. My redis servers are all well and not disconnected at that time as I have other services using same server.
Can anyone provide me with some directions?
"#socket.io/redis-adapter": "^7.0.0",
"#socket.io/redis-emitter": "^4.1.0",
Catching error for both sub and pub client - Done ✅
// I'm using ioredis and I believe ioredis will auto handle reconnection?
pubClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON pubClient %O`, err)
})
subClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON subClient %O`, err)
})
Catch error on adapter - Done ✅
// But i think this is not working to catch errors ❌❌❌
io.of('/').adapter.on('error', function(error){
debug('error: ', error);
});
Ping to keep connection alive - Done ✅
setInterval(() => {
// emitter.of('/user').emit("time", new Date);
io.of('/user').emit("time", new Date())
}, 300000);
I've also tried using both node-redis and ioredis and both end up with same error below Done ✅
Manage to catch this with redis on error event ✅
socket REDIS ADAPTOR DISCONNECTED ON pubClient Error: read ECONNRESET
socket at TCP.onStreamRead (internal/stream_base_commons.js:209:20) {
socket errno: -54,
socket code: 'ECONNRESET',
socket syscall: 'read'
socket } +5h
socket error: Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
} +0ms
// Unable to catch this event ❌❌❌
// I think this causes my app to crash
events.js:292
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on RedisAdapter instance at:
at Redis.onError (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/#socket.io/redis-adapter/dist/index.js:61:22)
at Redis.emit (events.js:327:22)
at Redis.EventEmitter.emit (domain.js:486:12)
at Redis.silentEmit (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/ioredis/built/redis/index.js:544:26)
at Socket.<anonymous> (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/ioredis/built/redis/event_handler.js:190:14)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:327:22)
at Socket.EventEmitter.emit (domain.js:486:12)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
}
This is snippet of how my server is created;
....server declaration codes
const { createAdapter } = require("#socket.io/redis-adapter");
const Redis = require("ioredis");
const pubClient = new Redis({
host: process.env.SOCKET_IO_REDIS_HOST,
port: process.env.SOCKET_IO_REDIS_PORT,
username: process.env.SOCKET_IO_REDIS_USER,
password: process.env.SOCKET_IO_REDIS_PASSWORD,
db: process.env.SOCKET_IO_REDIS_DB,
})
const subClient = pubClient.duplicate();
const adapter = createAdapter(pubClient, subClient)
io.adapter(adapter)
pubClient.on("ready", () => {
debug(`REDIS ADAPTOR CONNECTED`)
})
pubClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON pubClient %O`, err)
})
subClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON subClient %O`, err)
})
pubClient.on("end", (err) => {
debug(`REDIS ADAPTOR ENDED %O`, err)
})
setInterval(() => {
// emitter.of('/user').emit("time", new Date);
io.of('/user').emit("time", new Date())
}, 300000);
io.of('/').adapter.on('error', function(error){
debug('error: ', error);
});
I have restful api with express and nodejs but this api crashed every time.
So.. I have one function for datatime. This function will replace date in the url address everytime to current datetime.. Im not sure but may be when the current date is change with the new current date the API crashed..
I see this error message on the console:
events.js:187
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:201:27)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:426:8)
at Protocol.emit (events.js:210:5)
at Protocol._delegateError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:421:18)
at Socket.emit (events.js:210:5)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! express-api#1.0.0 start: `node server.js`
npm ERR!
npm ERR! Failed at the express-api#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2019-12-29T04_48_17_190Z-debug.log
So this is the code for api.. Its very simple.. but I dont know how to fix this error.
When I wake up and try to see the data from the API every time the API is crashed.
This is the code from the api:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.0.1",
port: "1234",
user: "username",
password: "password"
});
let aladinModel = '';
let aladinModelStations = '';
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
var dateNow = formatDate(Date());
app.route('/')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
const date = req.query.date;
const id = req.query.id;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('${dateNow}', ${id}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({ aladinModel })
} catch (error) {
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells;`;
con.query(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({ aladinModelStations })
} catch (error) {
console.log("Error query database!!!");
}
});
app.use(function (req, res) {
res.status(404);
});
I try to remove the cashe, to update npm, to restart the computer. But without the result.
With nodemon crashed the same..
What can I do ? How can to fix that ?
The error seems to be related to the connection to mysql.
As mysqljs documentation (https://github.com/mysqljs/mysql#error-handling):
Note: 'error' events are special in node. If they occur without an attached listener, a stack trace is printed and your process is killed.
You shuld intercept the connection error like this:
connection.on('error', function(err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
so you can investigate when and why the error occours and eventually you can recreate the connection when a problem occurs.
Move app.listen to the bottom of the file, after you declare all the routes and connect to the database.
Use app.get('route', function...) (more on that in the Express docs)
Move res.json() inside the callback function for each database query. The result will come back asynchronously so will not be accessible outside the function. If you’re new to async and callbacks in Javascript I’d recommend googling them and you’ll find a ton of reading materials.
Initialize your variables, e.g const aladinModel = ...
I'm using electron-vue build an APP. I need create a tcp connection, and I use net.Socket().But i get a no response when I set HOST.
I need use the socket global, so I create a class like this:
import crc16ccitt from 'crc/crc16ccitt';
const net = require('net');
class TcpClient {
tcp = null;
alive = false;
connect(options) {
return new Promise((resolve, reject) => {
this.tcp = new net.Socket();
this.tcp.connect(options, () => {
this.alive = true;
resolve();
console.log('connect server');
});
this.tcp.on('close', () => {
this.alive = false;
console.log('close');
reject();
});
this.tcp.on('error', () => {
console.log('error');
});
});
}
}
export default TcpClient;
and then I put it in the main.js like this:
Vue.prototype.$tcp = new TcpClient();
but when I use in vue instance like this:
this.$tcp.connect({ port: 8000, host: 127.0.0.1 });
Nothing happend, no errors, no result, but when I reload my page, I think connect a moment, and my server shows:
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
And if I don't set HOST, just port, it works well.
I am getting below error every day if I left the software for more than 2 to 4 hours.
{
code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
fatal: false
}
{ Error: Cannot enqueue Handshake after fatal error.
at Protocol._validateEnqueue (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:200:16)
at Protocol._enqueue (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:138:13)
at Protocol.handshake (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:118:18)
at connectMysql (/home/zubizi/retech_node_beta/index.js:38:14)
at Connection.<anonymous> (/home/zubizi/retech_node_beta/index.js:52:13)
at Connection.emit (events.js:182:13)
at Connection._handleProtocolError (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:425:8)
at Protocol.emit (events.js:182:13)
at Protocol._delegateError (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:390:10)
at Protocol.end (/home/zubizi/retech_node_beta/node_modules/mysql/lib/protocol/Protocol.js:116:8)
at Socket.<anonymous> (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:97:28)
at Socket.<anonymous> (/home/zubizi/retech_node_beta/node_modules/mysql/lib/Connection.js:502:10)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at args.(anonymous function) (/home/zubizi/.nvm/versions/node/v11.2.0/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:138:29)
at process.internalTickCallback (internal/process/next_tick.js:72:19) code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }
I tried below code to keep the connection alive. But the result is still the same.
// keep connection alive
setInterval(function () {
var datetime = moment.format('DD-MM-YYYY');
conn.query('SELECT 1');
console.log('Keep alive the connection. ' + datetime);
}, 10000);
I use this method to connect with MySQL
const conn = mysql.createConnection(config);
conn.connect(function (err) {
if (err) {
console.error(err);
// process.exit(1);
} else {
console.log(`DB Host: ${config.host}, DB: ${config.database}`);
console.log("Connected!");
}
});
and if any user logs in I change the database like this:
conn.changeUser({
database: req.session.dbname
}, function (err) {
if (err) {
console.log(err);
} else {
next();
}
});
Is the process is wrong or there is a solution for this????
I get an error when requesting an API and it crashes on any win server. Can anybody help, please?
This is part of my code:
app.get("/js/2806/api/products/getAllDrugs", (req, res) => {
const connection = getDBConnection()
const queryString = "SELECT * FROM tbl_drug";
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log("Failed to query for drugs: " + err);
// res.sendStatus(500);
res.json({
ErrorDetail: {
code: -1,
msg: err.code
}
});
res.end();
return
}
const drugs = rows.map((row) => {
return {
id: row.id,
storeId: row.drugStoreId,
drugName: row.drugName,
description: row.drugDsc,
drugUsing: row.drugUsing,
drugDoseId: row.drugDoseId,
categoryId: row.categoryId
};
})
res.json({
ErrorDetail: {
code: 0
},
Response: drugs
})
})
});
Error: Connection lost: The server closed the connection. at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:112:13) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:502:10) at Socket.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1125:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at Connection._handleProtocolError (C:\Users\Administrator\AppData\ ainCure\node_modules\mysql\lib\Connection.js:425:8) at Protocol.emit (events.js:189:13) at Protocol._delegateError (C:\Users\Administrator\AppData\Local\Ca node_modules\mysql\lib\protocol\Protocol.js:390:10) at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:116:8) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) I— lines matching original stack trace ...] at process._tickCallback Cinternal/process/next_tick.js:63:19> [nodemon I - wait in is (nodemon] si ing 'node app.js -erver is running on port: 3000 ode events.js:174 throw er; // Unhandled 'error' event is (nodemon] starting 'node app.js' -erver is running on port: 3000
Because of the server is already running on back so we do have to restart.
and if your using both iterm and the terminal so you need to make sure that the you use only one other one you have to close.