Cain Nuke
Cain Nuke

Reputation: 3079

How to use a global variable in a function if the variable has not been defined yet

I have a socket application with this file structure defined in app.js:

require("../chat/variables");
require("../chat/functions");
require("../chat/connect");

app.get('/', function (req, res, next) {
 res.sendFile(__dirname + '/index.html');
});

httpServer.listen(port, () => {
 console.log(`Socket.IO server running`);
});  

The variables file looks like this:

// server
app = require("express")();
httpServer = require("https").createServer({},app);
io = require("socket.io")(httpServer, {      //socket server path
  path: "/"
});

The functions file is something like this:

makesession = function(vdata) {   //store user data for this session
    if(socket) {
     socket.userid = vdata.userid;
     socket.username = vdata.name;
    }
   });

the file that performs the connection for each user looks like this:

io.on('connection', (socket) => {   //user connects to socket
   memberdata().then(v => {
    makesession(v);
   });
});   

However, I'm getting an error at the functions file saying that socket is not defined. Why is that? I thought it was enough with using the if condition so it only triggers after socket is defined.

Upvotes: 0

Views: 37

Answers (1)

jdigital
jdigital

Reputation: 12276

Try adding socket as a parameter to makesession, like this:

makesession = function(socket, vdata) {   //store user data for this session
    if(socket) {
     socket.userid = vdata.userid;
     socket.username = vdata.name;
    }
   });


io.on('connection', (socket) => {   //user connects to socket
   memberdata().then(v => {
    makesession(socket, v);
   });
});

In your original code, socket isn't defined in makesession because socket is a local (not a global) variable in the callback. Javascript uses lexical scoping, not dynamic scoping, so the variable in the callback is not visible in makesession.

Upvotes: 1

Related Questions