TL;DR You need to establish a new connection by calling the
createConnection method after every disconnection.
I was using the popular Mysql module for Node.js which is node-mysql and everytime, after the first page load was encountering a weird error with full stack trace.
Error: Cannot enqueue Handshake after invoking quit. at Protocol._validateEnqueue ...... ... ...
Basically, the problem is that, if you’ve terminated an existing connection object then that cannot be re-connected afterwards.
So the solution is to call the
createConnection method (followed by
connect()) to create a new connection whenever you have terminated the old/existing connection.
If you’re using the node-postgres module for postgresql support in Node, then you’ll have to do something similar, i.e., call the
connect method with the connection string to create new connections if you terminate the old connection (during the previous process/request) by calling
Note: If you’re serving web requests, then you shouldn’t be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the
error event to handle server disconnection and for reconnecting purposes. Full code here.
You can do something similar with the postgres module’s clients if you’re creating them manually using
pg.Client. Although when using the built-in pool approach to serve web requests, call
pg.connect() on every request and you should be fine. Just make sure you’ve attached an event handler on the
error event to prevent Node from crashing if the postgres server stops/restarts for some reason.
pg.connect() will retrieve an existing pooled client or create a new one ONLY if all the pooled clients are busy and the pool is NOT full.