1

Here's what I have added to my app.js page. (using express generator)

app.js

var express = require('express');
var socket_io = require( "socket.io" );

var app = express();

// Socket.io
var io = socket_io();
app.io = io;

Now if I were to do the following:

io.on('connection', function (socket) {
   console.log("connection made!");
});

This works nicely! But I'm wondering, how do I send socket_io to my route? For example I have a route called 'playground' and I would like to use socket_io specifically inside that route. I don't know how to do so! Any help would be great and I hope I was descriptive enough!

Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
Tony
  • 351
  • 3
  • 19
  • Can you elaborate your question? For example, why do you want to use socket_io in your normal routes? (you need to send messages to socketio clients from your normal routes or something else?). Depends on your requirements, there will be different solutions – Tan Nguyen May 18 '15 at 12:52
  • @TanNguyen I want to use socket.io on my playground.js page specifically as I work on a real-time chat app. Which will be located at localhost:8000/playground I'm just now getting into learning socket.io and node so I might be approaching this wrong for all I know. – Tony May 18 '15 at 12:55
  • Well, I am still not sure why you need to access socket_io (which is the socket io server instance itself). In case you need to access the client (connected to your socket.io server) you can check this answer http://stackoverflow.com/questions/9687561/is-it-possible-to-set-up-a-socket-io-client-running-server-side-on-a-node-js-s – Tan Nguyen May 18 '15 at 13:02

1 Answers1

2

There are many ways to do this.

You can pass io as a function argument to your route module:

app.js

var express = require('express');
var socket_io = require( "socket.io" );

var app = express();

// Socket.io
var io = socket_io();

var route = require('./route')(io);

route.js

module.exports = function(io) {
    io.on('connection', function (socket) {
       console.log("connection made!");
    });
};

Or you can export an init method:

route.js

module.exports.init = function(io) {
    io.on('connection', function (socket) {
       console.log("connection made!");
    });
};

Or you can define a constructor for your route:

app.js

var express = require('express');
var socket_io = require( "socket.io" );

var app = express();

// Socket.io
var io = socket_io();

var Route = require('./route');

var r = new Route(io);
r.doSomething();

route.js

var Route = function(io) {
    this.io = io;
    io.on('connection', function (socket) {
       console.log("connection made!");
    });
};

Route.prototype.doSomething = function() {
    console.log('hi');
};

// route.js
module.exports = Route;
Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50
  • When trying to pass the variable like you have in your first example I always get the error "cannot call method of 'IndexOf' undefined. – Tony May 19 '15 at 05:26