I feel like this is a pretty stupid question, but I'm having trouble understanding why I'm seeing strange behavior in a callback function. I defined an array called clientList which I export and use in other files. This code here is run when a client connects to my server.
When I say clientList.splice or clientList.push, everything works as expected, and the clinetList array reflects my change in other files which require() it in. However, if I say assign ClientList directly (e.g. clientList = []) then that change is not reflected in other files. If I print the contents of ClientList inside the callback, the change is reflected either way.
var clientList = [];
module.exports.socketHandler = (socket) => {
var client = new Client(socket);
clientList.push(client);
socket.on('end',function(){
clientList = [] //This does not change the exported array
clientList.splice(0,1); //This does change the exported array
console.log("Client connection ended: "+clientList.length); //This always changes
});
}
module.exports.clientList = clientList;
//IN A DIFFERENT FILE
//This code is run every few seconds on a loop
var example = require('./sockets.js');
console.log("Array Size: "+example.clientList.length);
My question is why there is a difference here. I have a good understanding of javascript scope and asynchronous operations, but I'm having a hard time figuring out what's causing this behavior. Is this related to how the node module loader works? Or am I just missing something obvious? Any help would be appreciated.