javascript – Broadcast via a route in Express


I have an endpoint in a node application that when called should trigger a broadcast to the users connected to the node application. In other words, as soon as the user entered the system, he would connect through and would wait until an external agent called this route so that the message could be sent to whoever was connected. It is possible ? I don't know if I was clear enough. I'm using express and for this.


Without a doubt, it is possible. See an example:

On the server, app.js

var _   = require('lodash');
var app = require('express').createServer();
var io  = require('')(app);


var sockets = {};

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});'/oi', function(req, res) {

io.on('connection', guardaConexao);

function guardaConexao(socket) {
  socket.on('error', console.log);
  socket.on('disconnect', function() {
    delete sockets[];
  sockets[] = socket;

function enviaParaTodos(dados) {
  _.forOwn(sockets, function (socket, id) {
    socket.emit('oi', dados);

Client no, index.html

<script src="/"></script>
  var socket = io.connect('http://localhost');
  socket.on('oi', alert);
Scroll to Top