usersam
usersam

Reputation: 1235

socket.io is not refreshing data

I am trying to display filesize on with socket.io with every time file changes. Here is my js code.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
    res.sendfile('index.html');
});
var fs = require("fs");
var filesize;
var filename = 'D:\\test.txt';

fs.watchFile(filename, function() {
    fs.open(filename, 'r', function(err, fd) {
        fs.stat(filename, function(err, stat) {
            if(err) { console.log('error');  }
            console.log(stat.size);
            filesize = stat.size;
        });
    })
});

io.on('connection', function(socket){
    console.log('A user connected');
    socket.emit('testerEvent', { description: prntarr});
    socket.on('clientEvent', function(data){
        console.log(data);
    });
    socket.on('disconnect', function () {
        console.log('A user disconnected');
    });

});

http.listen(3000, function(){
    console.log('listening on localhost:3000');
});

The problem is , socket is not refreshing data but console shows changed size. It refreshes only when i reload the page. Please suggest where i am making mistake and how to fix it.

thanks in advance.

Upvotes: 0

Views: 752

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22949

You need to do a socket.emit() inside your fs.watchFile() callback. You're not emitting anything when the file changes at the moment


  • When a user connects, push his socket in an Array.
  • Inside the watchFile callback, iterate through the connected sockets Array and .emit() what you want to send.
  • Don't forget to remove from that Array any sockets that have disconnected

Upvotes: 2

Related Questions