I am currently working on adding a real-time chat into a particular website. I am using Express JS package and the initialization information (i.e. start/listen server, etc.) is located in 'www/bin' (by default).
So, this is my init file (i.e. 'www/bin'):
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('nodeblog:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen to Sockets
*/
var io = require('socket.io').listen(server);
app.set('socketio', io); // FIXME: Cannot app.get('socketio') w/out req
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
And the thing is that I cannot 'get' this SocketIO declaration as I need in one of the router files to exchange messages between client/server.
Here is this route file:
var express = require('express');
var router = express.Router();
var app = express();
// Models
var auth = require('../models/auth');
var io = app.get('socketio');
router.get('/', auth.ensureAuthenticated, function(req, res, next) {
res.render('chat', {
title: 'Chat'
});
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg) {
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
module.exports = router;
So, when I try to app.get('socketio)' it returns undefined
Do you know how do I need to correctly declare this app.get('socketio',io)
so that I can access it anywhere (but not into the request methods)
via alwaysone
No comments:
Post a Comment