wBB
wBB

Reputation: 851

Where to end the mysql pool connection on nodejs?

I'm using MySQL on Nodejs. I'm using mysql pool to create the connection:

Var mysqk = require ('mysql');
Var pool = mysql.createPool ({my configs});

My question is: Where in the app will I use pool.end() as reported in the documentation?

For example: in my www file, I created a code to release other things as I have pointed in de code. Should I use pool.end() there?

var app     = require('../app');
var debug   = require('debug')('cancela:server');
var http    = require('http');
var port = normalizePort(process.env.PORT || '4000');
app.set('port', port);
var server = http.createServer(app);

// my app codes...
..
.
.

process.once('SIGTERM', end);
process.once('SIGINT', end);

function end() {

    server.close(function(err){

    if(err) throw err();

        // Should I end the Pool connection here?  <<<<<<===================================
        // pool.end(function (err) {
        //   // all connections in the pool have ended 
        // });

        console.log('Server endded!');        

        /* exit gracefully */
        process.exit();
    });
}

Upvotes: 4

Views: 5746

Answers (1)

Wing-On Yuen
Wing-On Yuen

Reputation: 667

Sometimes you want to manually release the connection pool for whatever reasons so you can use pool.end() before eventually recreating the pool.

Most of times you want to release it when your server is about to shutdown so you can do what you are thinking. Pay attention to the location of the function call process.exit(). It must be called after the connection release, otherwise the pool won't finish to release.

function end() {
    server.close(function (err) {
        if (err) throw err;
        console.log('Server endded!');

        pool.end(function (err) {
            if (err) throw err;

            process.exit();
        });
    });
}

Upvotes: 4

Related Questions