title: Node JS mysql database disconnect
body: <p>I am using Node JS and I am trying to connect to a mysql database. It keeps getting disconnected due to a timeout so I wrote a function to reconnect if it does timeout. Although I need it to be a continuous connection or references in my code won't work. Here is my relevant code:</p>
  
  <pre><code>var mysql = require('mysql');
  var connection = mysql.createConnection({
      host     : '.........', // MySQL Host
      user     : '.........', // MySQL User
      password : '.........', // MySQL Password
      database : '.........' // MySQL Databse
  });
  
  // MYSQL INFO
  
  //connection.connect();
  
  function replaceClientOnDisconnect(connection) {
    connection.on("error", function (err) {
      if (!err.fatal) {
        console.log('Databse Error, error not fatal');
        return;
      }
  
      if (err.code !== "PROTOCOL_CONNECTION_LOST") {
        throw err;
        console.log('PROTOCOL_CONNECTION_LOST Error: Reconnecting to database...');
      }
  
      setTimeout(function () {
          connection.destroy();
          connection = mysql.createConnection(connection.config);
          replaceClientOnDisconnect(connection);
          connection.connect(function (error) {
            if (error) {
              process.exit(1);
            } else {
                console.log('Reconnected to database!');
            }
      }, 1000); // 1 sec
      });
    });
  }
  
  // And run this on every connection as soon as it is created.
  replaceClientOnDisconnect(connection);
  </code></pre>