patrick hollweck patrick hollweck - 3 months ago 18
Node.js Question

How can I organize a web and a socket.io server?

I have a question about node.js

Is it possible to have multiple server.js files

Like: You have one "main" server.js which routes you to another directory and there is another server.js handling socket.io or stuff like that?

To be more specific :

I want to build a Game with WebSocket's and want to have one server.js which routes you to the game page and then on the "Game Page" I want it to connect it to "another" server.js and handle stuff like websockets, login and stuff like that. Or do i have to have everything in one server.js file

I heard about the modules.export function but I don't think this is what I am looking for.

Answer

Both are possible. If I understood right, you want to have a web server, and a socket.io server.

You can either do both in the same file:

'use strict';
const express = require('express'),
    socket= require('socket.io'),
    app = express(),
    io = socket();

//...

app.listen(80);
io.listen(12345);

In different files:

web.js:

'use strict';
const express = require('express'),
    app = express();

//...

app.listen(80);

io.js:

'use strict';
const socket= require('socket.io'),
    io = socket();

//...

io.listen(12345);