var config = require('./config');
var net = require('net');
var mysql_driver = require('mysql');
var mysql = mysql_driver.createConnection(config.db);
mysql.connect();
var cache = {};
// Build the cache
var csql = "SELECT * FROM (SELECT accountID, deviceID, uniqueID FROM Device ORDER BY uniqueID DESC) sub GROUP BY uniqueID";
mysql.query(csql, function(err, rows, fields) {
for (key in rows) {
cache[rows[key].uniqueID] = {};
cache[rows[key].uniqueID].accountID = rows[key].accountID;
cache[rows[key].uniqueID].deviceID = rows[key].deviceID;
}
});
运行这个udp-parse.js后,如果在运行期间,接收到缓存里没有的uniqueID,会导致udp-parse.js程序停止运行,不知道可否定期查询一下上面的代码。
var account = cache[datum.uniqueID].accountID; ^ TypeError: Cannot read property ‘accountID’ of undefined at Socket.recvMsg (/home/node/NodeJS-Server/udp-parse.js:170:54) at Socket.EventEmitter.emit (events.js:99:17) at UDP.onMessage (dgram.js:353:8) DEBUG: Program node udp-parse.js exited with code 1
DEBUG: Starting child process with ‘node udp-parse.js’
got message from 119.142.84.130:10000
6 回复
这个属于代码结构不严谨的原因,如果没有,你可以返回一个空对象而不是定期查询将简单的事情复杂化例如这样:
var account = datum.uniqueID ? (cache[datum.uniqueID].accountID ? cache[datum.uniqueID].accountID : {}) : {};
找个一个简单的办法:
var minutes = 1, the_interval = minutes * 60 * 1000;
setInterval(function() {
console.log("query db account every 1 min");
var csql = "SELECT * FROM (SELECT accountID, deviceID, uniqueID,smsEmail FROM Device ORDER BY uniqueID DESC) sub GROUP BY uniqueID";
mysql.query(csql, function(err, rows, fields) {
for (key in rows) {
cache[rows[key].uniqueID] = {};
cache[rows[key].uniqueID].accountID = rows[key].accountID;
cache[rows[key].uniqueID].deviceID = rows[key].deviceID;
cache[rows[key].uniqueID].smsEmail = rows[key].smsEmail;
}
});
}, the_interval);