Online examples will usually include the socket.io library using
<script src="/socket.io/socket.io.js"></script>
However, I was wondering why this works even though I don't have a socket.io folder in my directory. Does running node index.js
automatically create this socket.io folder?
CodePudding user response:
The socket.io server listens for all incoming requests that start with /socket.io
and "steals" those requests for itself, keeping them from the regular http server that the socket.io server is sharing.
When the socket.io server sees that this is a request for the socket.io.js
file, the socket.io server then reaches into its own node_modules/socket.io/client-dist
directory to get the client-side socket.io.js
file and sends it back to the client.
If you look at what you will find in node_modules/socket.io/client-dist
directory, you will see the file socket.io.js
sitting there. That's the file that the socket.io server sends back to the client. This is client-side code, only on the server for the purposes of being sent to the client when it asks for it.
Keep in mind that responses to incoming paths with a nodejs http server are not necessarily about file directories on the server at all. If any code hooked up to the http server handles an incoming request, it can decide what it wants to send as the response, from anywhere in the server (whether from a file or not). Only specific middleware tools like express.static()
look on the server's hard disk for a directory that matches the incoming request.