O
O
Oleg Abarmov2015-02-03 10:44:17
Node.js
Oleg Abarmov, 2015-02-03 10:44:17

Is the server constantly crashing on node.js?

//-----------------------------------------------
var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'track',
    password : '***********',
  database :'TRACK'
});

//----------------------------------------------
var net = require('net');

var HOST = '***.***.**.**';
var PORT = 8888;


net.createServer(function(sock) {
    
    sock.on('data', function(data) {
      var date = new Date();
    var sDate= date.getSeconds()+":"+date.getMinutes()+":"+date.getHours()+" "+date.getDate()+"."+(date.getMonth()+1)+"."+date.getFullYear();
   	
       
        console.log('DATA :' + sDate +  " : " + sock.remoteAddress + ': ' + data);
        sock.write('You said "' + data + '"');
        
    var sSQL="insert into `track` (`text`) values ('" + data + "')";
    connection.query(sSQL, function(error, result, fields){   
  
    });
    });
    
    sock.on('close', function(data) {
      //  console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });
    
}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

Here is the server code, I run it through the
screen node server.js Works
for 10-20 hours and then crashes.
Please help me understand what is the reason.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
O
Oleg Abarmov, 2015-03-13
@XProx

the forever module helped forever
var forever = require('forever-monitor');
//------------------------------------------------ ------------
var child = new (forever.Monitor)('/var/www/nj/server.js',
{
'minUptime': 50,
'spinSleepTime': 10,
'logFile ': '/var/www/nj/log_fr.txt', // Path to log output from forever process (when daemonized)
'outFile': '/var/www/nj/out_fr.txt', // Path to log output from child stdout
'errFile': '/var/www/nj/err_fr.txt' // Path to log output from child stderr
}

A
Alexander Prozorov, 2015-02-03
@Staltec

I can assume that the process crashes due to a disconnection due to a timeout from the mySQL side if there has been no activity on the connection for a long time. In this case, the exception looks like this:

Error: Connection lost: The server closed the connection.
    at Protocol.end (*path_to_project*/node_modules/mysql/lib/protocol/Protocol.js:103:13)
    at Socket.<anonymous> (*path_to_project*/node_modules/mysql/lib/Connection.js:88:28)
    at Socket.emit (events.js:117:20)
    at _stream_readable.js:944:16
    at process._tickCallback (node.js:442:13)

It is cured by setting a timeout for connecting to mySQL manually:
mysqlConnection.query("SET SESSION wait_timeout = 604800"); // 7 days timeout
In general, of course, you need to run the node process under the supervisor (pm2, forever, supervisor) and wrap the error stream in the corresponding error.log. There you will immediately see with which exception the process has failed. Otherwise, with such questions, contact the battle of psychics.

T
Timur Shemsedinov, 2015-02-03
@MarcusAurelius

In general, you need to log the output, it does not just fall, but says something, for sure, or an error or memory is over. Most likely, your connection disappears and the following requests do not go through, you need to reconnect, put the connection in function openConnection and hang the event, something like this connection.on('error', function(err) { if (err.code === 'PROTOCOL_CONNECTION_LOST ') openConnection(); });
And please don't glue SQL from strings, use query parameters. Here is my old library, it contains examples and additional conveniences: https://github.com/tshemsedinov/node-mysql-utilities

S
Sergey Sulakov, 2020-03-02
@web-verzus-team

Another option: create not a connection, but a pool

const pool = mysql.createPool({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'chat'
});

and then "get" the connection:
pool.getConnection(function(err, connection) {
  if(err) {
    console.log(err);
  }
  let sql = "SELECT * FROM `table`";
  connection.query(sql, [], function(err, results) {
    connection.release(); // always put connection back in pool after last query
    console.log(results);
    if(err) {
      console.log(err);
    }
  });
});

A
AlSutman, 2018-07-20
@AlSutman

I solved the problem in the following way: I installed pm2, it is a process manager, and I started my application through pm2 start npm -- start and every time something crashes, it just restarts, it has never failed, I highly recommend it.

A
Aziz Mamoyan, 2018-11-12
@Aziz87

Делайте собственную функцию для запросов. 
Если запрос не прошел - Пробуем подключиться к базе еще раз и затем заново выполнить запрос.
Если вторая попытка тоже не прошла - возвращаем пустой ответ, чтобы не было ошибок на стороне сервера и он не крахнулся.


let mysqldb = require("mysql");
let mysql = null;

function connect(callback=null){
    console.log("MYSQL TAKE CONNECT");
    mysql=mysqldb.createConnection({host: "localhost", user: "*", password: "*", database:"*"});
    mysql.on('error', function(err) {
      console.log("---" +err.message);
      console.log("---" +err.code);
    });
  if(callback)setTimeout(callback,100);
}

connect();//Первичное подключение


//Функция для запросов к базе
function my_mysql_query_function(q, paramas, callback=null, reconnect=true){
//Пробуем сделать запрос
    mysql.query(q,paramas,function(err,rows){
      if(err){//Запрос не прошел
        console.log("mysql_query failed! calling again...");
        if(reconnect)//Если разрешено  повторить попытку
          connect(function(){ //Переподключаемся к базой
           my_mysql_query_function(q,params,callback,false);//Повторяем заново с меткой false == больше не пробовать 
          });
        else callback([]); //Если нельзя больше пробовать подключаться - возвращаем пустой массив ответа
      }else{
        if(callback) callback(rows); // если запрос успешный то возвращаем массив ответа
      }
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question