I am new to Node.js / Express and I use it as a backend for an AngularJS application. I looked at StackOverflow for some help on my problem, but I cannot figure out how to port sentences to my code.
My application works as follows:
- The lengthy Scala process periodically sends my Node.js. application log messages He does this by sending to the HTTP API
- When a message is received, my application writes a log message to MongoDB
- Log messages are then sent in real time to the Angular client.
I have a problem with Node modules, since I cannot figure out how to access the socket instance in the Express controller.
As you can see, socket.io is created there in server.js. However, I would like the controller itself, logs.js, to be able to emit a socket.io instance.
How can I access io in the controller? I'm not sure how to pass the io instance to the controller so that I can send messages?
Here is the Node code:
server.js
var app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); require('./lib/config/express')(app); require('./lib/routes')(app); server.listen(config.port, config.ip, function() { console.log('Express server listening on %s:%d, in %s mode', config.ip, config.port, app.get('env')); }); io.set('log level', 1);
routes.js
var logs = require('./controllers/logs'), middleware = require('./middleware'); module.exports = function(app) { app.route('/logs') .post(logs.create); }
logs.js
exports.create = function(req, res) { // write body of api request to mongodb (this is fine) // emit log message to angular with socket.io (how do i refer to the io instance in server.js) };
source share