0

I am using node js, socket io, and express to create a multiplayer web game. When the server start I listen on port 2000. When I go to localhost:2000, the file lobby.html is sent using

//app.js
const express = require('express');
const app = express();
const serv = require('http').Server(app);
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/Client/lobby.html');
});
serv.listen(2000);
var io = require(socket.io)(serv, {});

I would include the js for the lobby.html file inside the html file instead of using <script src='lobby.js>.

I would also import socket io and the app.js file which is the server file in the lobby.html file. It looked like this:

<script src='https://cdn.socket.io/socket.io-1.4.5.js'></script>
<script src='../app.js'></script>

Since the js was written in the html file and socket io was included on that html page I could use var socket = io(); in my js so I can communicate with the server(app.js).

However, I want the js that was written in lobby.html to be moved to a file called lobby.js using <script src='lobby.js'> in the html file and also by using require(./lobby.js) in app.js. When I try to do var socket = io() in the lobby.js file, I get an error saying io() is not defined since the js file is separate from the html file.

How can I get socket io to work in the lobby.js file.

Incase you need the file structure, here it is:

-Game Folder
    -Client
        -lobby.html
        -lobby.js
    -app.js
    -package.json

1 Answer 1

1

Simply add another route in your express code:

//app.js

// root route
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/Client/lobby.html');
});

// add this
app.get('/app.js', function(req, res) {
    res.setHeader('Content-Type', 'application/javascript');
    res.sendFile(__dirname + '/Client/app.js');
});

and then add the script tag in your HTML:

<script src='/app.js'></script>

Remember that every page represents more than one request to the server. Every CSS file, javascript file, image adds another request that the server needs to know how to handle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.