Node events.js:174 throw er; // Unhandled 'error' event - javascript

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.

Related

Unable to catch ECONNRESET error and it is causing app to crash

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);
});

npm-mysql crashes overnight

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.

PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR nodejs mysql

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????

How to fix MaxListenersExceededWarning error?

In my Node.js http web server I use ssh2-sftp-client library to load csv files from remote SFTP server. It raise error when user try to load several files and I don't understand how to fix it?
CODE:
router.post('/', (req, res) => {
const fileName = req.body.file_name
const remotePath = '/reports/' + fileName
const localePath = path.join(process.env.HOME || process.env.USERPROFILE, 'Downloads/' + fileName)
sftp.connect(config.sftpServer, 'on').then(() => {
sftp.fastGet(remotePath, localePath, {}).then(() => {
res.header('Content-type', 'text/csv; charset=windows-1251')
res.sendFile(localePath)
sftp.end()
}).catch((err) => {
sftp.end()
console.log(err, 'fastGet method error')
})
}).catch((err) => {
sftp.end()
console.log(err, 'connect method error')
})
})
ERROR:
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Finally I found the problem. Instead of on method you need to use once method.
sftp.connect(config.sftpServer, 'once').then(() => {
// CODE
}

connection error while connecting mongodb to node application

after I started server at port 27017, opened another window and run my server program it is showing the connection error as follow
C:\node-mongodb\node_modules\mongodb\lib\server.js:242
process.nextTick(function() { throw err; })
^
AssertionError: { [MongoError: connect UNKNOWN 127.0.0.1:27017 -
Local(undefined:undefined)]
name: 'MongoError',
message: 'connect UNKNOWN == null
at C:\node-mongodb\simple-server.js:8:12
at C:\node-mongodb\node_modules\mongodb\lib\mongo_client.js:330:20
at C:\node-mongodb\node_modules\mongodb\lib\db.js:231:14
at null.<anonymous> (C:\node-mongodb\node_modules\mongodb\lib\server.js:240:9)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous(C:\nodemongodb\node_modules\mongodb\node_modules\mongo
db-core\lib\topologies\server.js:218:12)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
I tried removing lock file repairing mongodb and other solutions that are given for other similar questions but they are not working.
please tell my why this error is coming and how I can resolve it.
I am running on windows xp(32-bit).
This is the simple-server.js file:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(err,null);
console.log("Connected correctly to server");
var collection = db.collection("dishes");
collection.insertOne({name: "nerd21", description: "test"},
function(err,result){
assert.equal(err,null);
console.log("After Insert:");
console.log(result.ops);
collection.find({}).toArray(function(err,docs){
assert.equal(err,null);
console.log("Found:");
console.log(docs);
db.dropCollection("dishes", function(err, result){
assert.equal(err,null);
db.close();
});
});
});
});
screenshot of command prompt is as follows:enter image description here

Categories

Resources