Monday, 26 August 2013

NodeJS merges objects

NodeJS merges objects

I'm working on NodeJS to create a way to send pictures to multiple
displays at once, currently my code has these statements:
var $ = require('jQuery');
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app, { log:false });
var fs = require('fs');
var Server = {
server_address : "XXX.XXX.XXX.XXX", // The server address
playing_now : Object // The playlist that are being synced
};
var Client = {
clients : Object
};
app.listen(1337);
console.log("App is running on port 1337...");
function handler(request, response) {
var ip_address = null;
try{ ip_address = request.header('x-forwarded-for'); }
catch(error){ ip_address = request.connection.remoteAddress; }
Client.clients[ip_address] = "X";
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
response.writeHead(500);
return response.end('Error loading index.html');
}
response.writeHead(200);
response.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on("RequestPlaylist", function(json){
Client.clients[json["Address"]] = json["PlayList"];
if(typeof Server.playing_now[json["PlayList"]] === 'undefined'){
$.ajax({
url : "http://" + Server.server_address +
"/buildPlayList.php",
type : "GET",
dataType : "jsonp",
method : "GET",
data : {RemoteIP : json["Address"], Name :
json["PlayList"]}
}).done(function(playlistJSON){
console.log("________________________________________");
console.log("Done");
console.log(Server.playing_now);
Server.playing_now[playlistJSON["playName"]] = playlistJSON;
console.log(Server.playing_now);
console.log("________________________________________");
})
}else{
console.log("________________________________________");
console.log("Redirect");
console.log(Server.playing_now);
console.log("________________________________________");
}
});
});
When a new clients connects, I store it's IP address on Client.clients,
and when I get the json containing the urls to the images, I store it on
Server.playing_now.
The problem is, when I output Server.playing_now, it includes the contents
of Client.clients:
Done
{ [Function: Object] 'XXX.XXX.XXX.XXX': 'Default Media' }
{ [Function: Object]
'XXX.XXX.XXX.XXX': 'Default Media',
'Default Media':
{ '1':
{ json: [Object],
duration: '5',
name: 'Slideshow',
type: 'Image',
sync: '1',
callback: 'jQuery17207063492417801172_1377555709748' },
playName: 'Default Media' } }
Nowhere in my code do I merge these two objects, if I comment out the
Client object, it does return only the contents of Server.playing_now.
Any idea what could be happening? Or is this behavior expected?

No comments:

Post a Comment