2013-05-07 6 views
0

Ниже приведен скрипт nodejs. Внезапно запуская его с: sudo NODE_ENV=test node server.js дает:running nodejs от cli дает ошибку ENOTFOUND

info - socket.io started 
{ [Error: getaddrinfo ENOTFOUND] 
    code: 'ENOTFOUND', 
    errno: 'ENOTFOUND', 
    syscall: 'getaddrinfo', 
    fatal: true 
} 

Что я могу сделать для отладки?

var iniparser = require('iniparser'); 
var config = iniparser.parseSync('../Config/init/db.ini'); 
var env = process.env.NODE_ENV || 'dev'; //startup nodejs with e.g: NODE_ENV=test forever start server.js 

var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    fs = require('fs'), 
    mysql = require('mysql'), 
    connectionsArray = [], 
    connection = mysql.createConnection({ 
     host: config[env]['host'], 
     user: config[env]['user'], 
     password: config[env]['pwd'].replace(/"/g, ''), 
     database: config[env]['dbname'] 
    }), 
    POLLING_INTERVAL = 1000, 
    pollingTimer; 

// If there is an error connecting to the database 
connection.connect(function (err) { 
// connected! (unless `err` is set) 
    console.log(err); 
}); 


// creating the server (localhost:8000) 
app.listen(1443); 

// on server started we can load our client.html page 
function handler(req, res) { 
    fs.readFile(__dirname + '/client.html', function (err, data) { 
     if (err) { 
      console.log(err); 
      res.writeHead(500); 
      return res.end('Error loading client.html'); 
     } 
     res.writeHead(200); 
     res.end(data); 
    }); 
} 

/* 
* 
* HERE IT IS THE COOL PART 
* This function loops on itself since there are sockets connected to the page 
* sending the result of the database query after a constant interval 
* 
*/ 
var pollingLoop = function() { 

// Doing the database query ap.line_state != 0 means busy 
    var query = connection.query('SELECT p.id, ap.* FROM active_player ap LEFT JOIN player p ON ap.dossier_id=p.dossier_id '), 

     players = []; // this array will contain the result of our db query 

// setting the query listeners 
    query 
     .on('error', function (err) { 
// Handle error, and 'end' event will be emitted after this as well 
      console.log(err); 
      console.log("ENDPOINT", this.request.httpRequest.endpoint); 
      updateSockets(err); 
     }) 
     .on('result', function (player) { 
// it fills our array looping on each user row inside the db 
      players.push(player); 
     }) 
     .on('end', function() { 
// loop on itself only if there are sockets still connected 

      if (connectionsArray.length) { 
       pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL); 
       updateSockets({players: players}); 
      } 

     }); 

}; 

function is(a, b) { 
    return a === b && (a !== 0 || 1/a === 1/b) // false for +0 vs -0 
     || a !== a && b !== b; // true for NaN vs NaN 
} 

// creating a new websocket to keep the content updated without any AJAX request 
io.sockets.on('connection', function (socket) { 

    console.log('Number of connections:' + connectionsArray.length); 
// starting the loop only if at least there is one user connected 
    if (!connectionsArray.length) { 
     pollingLoop(); 
    } 

    socket.on('disconnect', function() { 
     var socketIndex = connectionsArray.indexOf(socket); 
     console.log('socket = ' + socketIndex + ' disconnected'); 
     if (socketIndex >= 0) { 
      connectionsArray.splice(socketIndex, 1); 
     } 
    }); 

    console.log('A new socket is connected!'); 
    connectionsArray.push(socket); 

}); 

var updateSockets = function (data) { 
// adding the time of the last update 
    data.time = new Date(); 
// sending new data to all the sockets connected 
    connectionsArray.forEach(function (tmpSocket) { 
     tmpSocket.volatile.emit('notification', data); 
    }); 
}; 
+0

У вас есть тестовая среда в конфигурации? –

+0

Похоже, что ваша конфигурация db неверна. Я запускаю этот код с правильными учетными данными БД - работа права – Eugene

ответ

0

Для получения полностью информацию о исключения заменить

console.log(err); 

To:

console.err(err.stack) 

И добавить, если для ERR переменной в connecttion.connect функции обратного вызова.

Также вы можете добавить этот код для safy перехватывать все исключения:

process.on('uncaughtException', function globalErrorCatch(error, p){ 
    console.error(error); 
    console.error(error.stack); 
}); 
+0

Я добавил предлагаемый код отладки. Теперь я получаю: 'at Handshake.Sequence.end (/www/test-front/webroot/node_modules/mysql/lib/protocol/sequences/Sequence.js:66:24) на Protocol.handleNetworkError (/ www/test -front/webroot/node_modules/mysql/lib/protocol/Protocol.js: 230: 14) в Connection._handleNetworkError (/www/test-front/webroot/node_modules/mysql/lib/Connection.js:145:18) на Socket.EventEmitter.emit (events.js: 117: 20) at net.js: 807: 16' Он работает локально, учетные данные db в порядке. Может быть, nodejs или другой пакет повреждены? – Bart

+0

Попробуйте переместить io = require ('socket.io'). Listen (app) после app.listen(). Я использую этот порядок в своих приложениях – Eugene

+0

Кажется, WebSocket просто не пишет: 'отладки - очищаются сердцебиения тайма-аут для клиента f0PHApuqQsxAcNonF1UV отладки - установить интервал подтверждения для клиента f0PHApuqQsxAcNonF1UV отладки - излучающие сердцебиений для клиента f0PHApuqQsxAcNonF1UV отладка - WebSocket пишущих 2 :: debug - set heartbeat timeout для клиента f0PHApuqQsxAcNonF1UV debug - получил пакет пульса ' – Bart

Смежные вопросы