vendredi 17 avril 2015

Sending multiple objects with node.js, mysql and socket.io

I am using node.js, mysql and socket.io and I would like to get a large amount of data from my mysql database. It will be a set of stars with xy location coords. I can get the data line by line as shown with the row var and it logs to the node.js console correctly. I am also able to get standard messages back to the client via the emit line. I can't however send star data to the client, it just returns a blank array if I try and use an array to store the row var each time.





function starUpdate(sessionid){
var query = "SELECT * FROM stars";
var conn = mysql.createConnection({
host : 'localhost',
user : 'dbuser',
password : 'dbpass',
database : 'dbname'
});
//console.log("Running query: " + query);
conn.query(query, function(err, rows, fields) {
if (!err)
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
console.log(row);
}
else
result = 'error';
});
conn.end();
console.log("Star data: " + result);
//server.to(sessionid).emit("starupdate",result);
}



When I do an individual output of "row" to the console I get this:





{ star_id: 1,
star_type: 1,
star_x: 200,
star_y: 200,
star_alpha: 1,
star_status: 1 }
{ star_id: 2,
star_type: 2,
star_x: 200,
star_y: 250,
star_alpha: 1,
star_status: 1 }
{ star_id: 3,
star_type: 3,
star_x: 200,
star_y: 300,
star_alpha: 1,
star_status: 1 }



How do I setup the result variable and enter the rows into it so my emit line transmits all the data to be processed on the client end?


Aucun commentaire:

Enregistrer un commentaire