1

I have a question regarding requiring scripts to the NodeJS / Socket.IO Server. In PHP I can add the line require('somefile.php'); Is there any option to include any JS files to the NodeJS/Socket.IO server? My server code currently has over 500 lines, I want to add a Require for each Socket.On to make it easier to read.

Is there a disadvantage?

Thanks, David :))

2
  • Maybe this can help w3schools.com/nodejs/nodejs_modules.asp Commented Jan 23, 2019 at 11:53
  • If a module is not included with node then you have to install that package, once its installed you can then include it with a require statement. Commented Jan 23, 2019 at 11:53

1 Answer 1

2

You can in this way,
Your IO Connection file,

var module1 = require('file1.js');
var module2 = require('file2.js');

io.on('connection', function (socket) {
    module1(socket);
    module2(socket);
})

file1.js,

module.exports = function (socket) {
    socket.on('createroom', function (data) {
        console.log("create room");
    });
}

file2.js,

module.exports = function (socket) {
    socket.on('play', function (data) {
        console.log("play");
    });
}
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.