简体   繁体   中英

Express 4 : I have a variable set up in app.js and I need to send it to my routes

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM