1

SITUATION (MAIN QUESTION START is under)

Recently, I practice Node.js web hosting.

I generate folder with express-generator, like under.

$ express --view=pug # default jade, change pug
$ npm install

$ ls
app.js bin node_modules package.json public routes views

For Create new page named chat.js, in app.js

var chatRouter = require('./routes/chat');

...

app.use('/chat', chatRouter);

and create /views/chat.pug, /routes/chat.js simply.


Now. I want to use socket.io.

Some sample codes leads me like under.

1. change app.js

var app = express(); # express generate this line
app.io = require('socket.io')();

...

app.io.on('connection', function(socket) {
  console.log('app.js connection');
});

2. change ./bin/www

var server = http.createServer(app); # express generate this line
app.io.attach(server);

3. change /views/chat.pug

    <script src="/socket.io/socket.io.js"></script>
    <script>
        $(function() {
            var io = socket();
        });
    </script>

When I run server with sudo node ./bin/www and connect page http://www.sample.com/chat, log app.js connection is comes out. Greatly.

MAIN QUESTION START

But, I want to seperate under codes NOT app.js, for example, /routes/chat.js or somewhere for make short app.js

app.io.on('connection', function(socket) {
  console.log('app.js connection');
});

I try like under, but it not works that I expected. In /routes/chat.js

var io = require('socket.io')(server);
io.on('connection', function(socket) {
  console.log('chat.js connection'); # NOT COMES HERE
});

Please help me to avoid make app.js longer.

Zem
  • 464
  • 3
  • 14
  • I type some piece of code, but If you need full source code, I'll change question codes. – Zem Mar 04 '20 at 01:54

1 Answers1

2

In the bin, import another module and pass app to it

// app.js
var app = express(); # express generate this line

app.io = require('socket.io')();
require('../new-file')(app)

// new-file.js
module.exports = (app) => {
   app.io.on('connection', function(socket) {
      console.log('app.js connection');
   });  
}
Zem
  • 464
  • 3
  • 14
zavr
  • 2,049
  • 2
  • 18
  • 28