Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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
}
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)
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
Another option: create not a connection, but a pool
const pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'chat'
});
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);
}
});
});
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.
Делайте собственную функцию для запросов.
Если запрос не прошел - Пробуем подключиться к базе еще раз и затем заново выполнить запрос.
Если вторая попытка тоже не прошла - возвращаем пустой ответ, чтобы не было ошибок на стороне сервера и он не крахнулся.
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 questionAsk a Question
731 491 924 answers to any question