Matthias
Matthias

Reputation: 1213

Javascript/NodeJS/Express scope confusion

I was looking through this repository and noticed that the author had declared a variable (io) in app.js:

/* Socket.io Communication */
var io = require('socket.io').listen(server);
io.sockets.on('connection', socket);

He refers to the variable again in public/js/app.js, but doesn't seem to refer to the outer javascript file at all as I would normally expect, so I'm surprised this doesn't result in a ReferenceError.

Could someone please clarify for me what it is about this example that allows this external reference to io to work? Many thanks in advance.

Upvotes: 1

Views: 40

Answers (1)

Kevin B
Kevin B

Reputation: 95062

public/js/app.js is client-side javascript and will run in the browser. If you look at index.html, you'll see the client version of socket.io is included at the bottom which defines a global io var.

https://github.com/DanialK/ReactJS-Realtime-Chat/blob/master/public/index.html#L12

Upvotes: 2

Related Questions