I am getting closer I think to understanding how global and local objects work in node.js but I am getting tripped up when it comes to something more complex like a server.
In my understanding in node.js a server is accessed by many but should only be instanced once so this confuses the hell out of me, I don't know how other servers behave (I'm using a web sockets server https://npmjs.org/package/ws)
I also understand:
var _global='global';function testing(){ var _local='local'; console.log(_global+'& '+_local);// 'global & local' return;}testing();console.log(_global+'& '+_local);// 'global & undefined'
Now in node.js if I declared that _local var inside a server would that mean that it's a unique variable for each person?
If I create a global server:
var wss=new WebSocketServer({host:port});wss.on('connection',function(soc){ soc['uid']=Math.floor(Math.random()*101); console.dir(soc); });
navigate to the page that connects to the server, I see (on my putty ssh client) the websocket object with the attached id.
Then if a second user visits that page I see (in ssh) that the websocket object now looks like a new object no old id just a new one I don't see two connections...
So I was thinking
Should I make this socketserver local by putting it in a http.server and call the server with ajax?
client:
var xhr=XHRobject();xhr.open("POST","mysite.com:8005",true);xhr.setRequestHeader("Content-Type","text/csv");xhr.send('create server');
server:
var http = require('http');http.createServer(function(req,res){ req.on('data',function(chunk){ chunk=chunk.toString('utf8'); if(chunk==='create server'){ wss=new WebSocketServer({host:port});//etc.. } }); });
This would create a problem though I think as the WebSocketServer has a list wss.clients list of connected websockets that needs to be accessed so I don't think that I should have more than one server...?
If I declaire a variable (var localisedsocket) and put the wss.on('connection',function(soc){soc=localisedsocket;}); inside the http server, then would every user that opens the WebSocketServer no-longer be writing over the socket object?
Am I getting this theory right?