how to push a message from web server to browser using node js

You can achieve it using node js. Following is a working code example.
Node js : index.js

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

app.get("https://stackoverflow.com/", function (req, res) {
    res.sendFile("index.html", {root: __dirname});
});
io.on("connection", function (socket) {
    socket.on("notify", function (notification_request) {
        io.emit('notify', JSON.stringify(notification_request));
    });
});
http.listen(3000, function () {
    console.log('listenting on 3000');
});

your frontent index.html before </body>

<script>
    var socket = io();
    $('button').click(function () { //notify event triggered
        socket.emit('notify', {notification-1: "message1", notification-2: "message2", notification-3: "message3"});
        return false;
    });
    socket.on('notify', function (notification) {
        var notifications = JSON.parse(notification); //process notication array
        $('#notification-div').append(notifications); //display the notification here which is going to be reflected for all clients
    });
</script>

Run your index.js file on terminal or CLI to activate server. And Don’t forget to install following node modules

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

Leave a Comment