1

I have a small project with NodeJS Express server and Angular2 frontend. The server has an API interfaces. The main part of this is: /api/alert. I want to do the following: If the /api/alert get an request then socket.io broadcast an event to all connected clients.

My server structure is the following:

server.js

var http        = require('http'),
    express     = require('express'),
    app         = module.exports.app = express(),
    port        = process.env.PORT || 3000,
    mongoose    = require('mongoose'),
    bodyParser  = require('body-parser'),
    db          = require('./config/db'),
    path        = require('path');

mongoose.Promise = global.Promise;
mongoose.connect(db.url);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'dist')));

var routes = require('./server/routes/index');
routes(app);

var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(port);

console.log('Server started on: ' + port);

server/routes/index.js

const deviceRoute   = require('./devicesRoute');
const alertRoute    = require('./alertsRoute');

module.exports = function(app) {
    deviceRoute(app);
    alertRoute(app);
}

server/routes/alertRoute.js

'use strict';
module.exports = function(app) {

    var alertsService = require('../services/alertsService');

    app.route('/api/alert')
        .post(alertsService.createAlert);
};

server/service/alertService.js

'use strict';

exports.createAlert = function(req, res) {
    // do something in database

    // I want to broadcast to all client HERE
};

I can't pass the io and server variables to the function (from server.js). How can I do that? What is the easiest way?

Thank you!

1 Answer 1

4

First you would want to export both the app and server objects from server.js and pass your socket to your response in middleware as follows:

var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);

app.use(function(req, res, next){
    res.io = io;
    next();
});

...

module.exports = {app: app, server: server};

You can then require the server instance you created in server.js (depending on where you are requiring it from) as

var server = require('../server').server;

Since you added socket.io to the response object, you can use it in your services as

'use strict';

exports.createAlert = function(req, res) {
    // do something in database

    // I want to broadcast to all client HERE
    res.io.emit("broadcast", "clients");

};
2
  • 3
    what if I want to emit to a specific connected client?
    – Ayyash
    Commented Oct 22, 2018 at 8:27
  • 1
    @Ayyash you will have to use like res.io.to(socketId).emit(), for more info socket.io/docs/v4/emit-cheatsheet Commented Mar 26, 2022 at 2:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.