Matthew Arkin Matthew Arkin - 4 months ago 155x
Node.js Question

Use inside a express routes file

I'm trying to use with Node.js and emit to a socket within the logic of a route.

I have a fairly standard Express 3 setup with a server.js file that sits in the route, and then I have an index.js which sits in a routes folders that exports all the pages/publically accessible functions of the site. So they look like:

exports.index = function (req, res) {
res.render('index', {
title: "Awesome page"

with the routing defined in server.js like:


I'm assuming I have to create the object in the server.js, since it needs the server object, but how can I access that object and emit to it from the index.js export functions?


You can set up your routes file as a function, and pass the Socket.IO object when requiring the file.

module.exports = function(io) {
  var routes = {};
  routes.index = function (req, res) {
    res.render('index', {
      title: "Awesome page"
  return routes;

Then require routes like this:

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('').listen(server);
var routes = require('./routes')(io);