0

I'm trying to use socket.io with express, i used the express generator. I cannot view any log from console.

Before write this i Followed the most voted solution from Gabriel Hautclocq on Using socket.io in Express 4 and express-generator's /bin/www

My code:

app.js

var express = require('express');
var socket = require('socket.io');
var app = express();
var io = socket();
app.io = io;
// var for routes
var index = require('./routes/index')(io);
// Routes
app.use('/', index);

module.exports = app;

bin/www

var server = http.createServer(app);
var io = app.io;
io.attach(server);

routes/index.js

var passport = require('passport');
/* GET home page. */
module.exports = function(io){
  var app = require('express');
  var router = app.Router();
  var controller = require('../controllers/indexController');
  router.get('/', controller.plain);
  /*socket*/
  io.on('connection', function(socket){
    console.log('conectado desde index.js');
    console.log('conectado desde index.js');
    console.log('conectado desde index.js');
  });
  return router;
}

controllers/indexController.js

Edit with full content from indexController.js

var Account = require('../models/accounts');
var Fav = require('../models/favs');
var Project = require('../models/projects');
var Message = require('../models/messages');
var mongoose = require('mongoose');

module.exports = {
    plain : function (req, res) {
      Project.find(function(err, projects){
        Account.find(function(err, userOwner){
          if(req.user)
            Fav.find({'favUserId': req.user.id},function(err, favs){
              res.render('index',{
                title: "myAplication",
                user: req.user,
                listProjects : projects,
                listUsers : userOwner,
                listFavs : favs
              });
            });
          else
            res.render('index',{
              title: "myAplication",
              listProjects : projects,
              listUsers : userOwner,
            });
        });
      });

    },
};
Community
  • 1
  • 1
Marcos R. Guevara
  • 5,258
  • 6
  • 19
  • 44

1 Answers1

0

you can do this:

//in app.js
app.set('socketio', io);

//in any route
app.get("/", (req, res) => {
    const io = req.app.get('socketio');
})
Shahar Eliyahu
  • 116
  • 1
  • 3