Reputation: 1235
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
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
socket
in an Array. watchFile
callback, iterate through the connected sockets Array and .emit()
what you want to send. sockets
that have disconnectedUpvotes: 2