Search code examples
node.jsexpresswebsocketfilesystemwatcher

express-ws how to periodically check a custom event and take action automatically


I am using express-ws https://www.npmjs.com/package/express-ws (API which helps creating server for express and websocket clients).

app.ws('/', function(ws, req) {
  console.log("New connection")
  if (content.length > 0) {
    console.log(content)
    ws.send(content)
  }
  ws.on('message', function(msg, flags) {
    console.log("Received "+ msg);
  });
  ws.on('data', function(msg, flags) {
    var data = []; // List of Buffer objects
    res.on("data", function(chunk) {
      data.push(chunk); // Append Buffer object
      console.log(data)
    })
  })
});

Now as you can see with code above, whenever a connection is created it checks length of content and sends conetent to client if more than 0.

Following router code, on web request, updates the file. Issue with this if sometime after connection creation if this file was modified, this connection doesn't know about it and hence send function is not called. I also tried fs.watch but i am not able to make it to work.

router.post('/run_restart', function(req, res, next) {
  text = '{"to_do": "run_test", "devices":"all", "argv": { "test": "' + req.body.cmd + '", "cycles": "' + req.body.cycles + '", "awake_for": "' + req.body.wt + '" }}'
  path = process.env['HOME']+'/Desktop/automation/Stressem/StressemWeb/bin/task.txt'
  fs.writeFile(path, text)
  res.render('home.jade', { title: 'Stressem' });
});

fs.watch(file, function (event) {
  fs.stat(file, function (err, stats) {
    if(stats.size>80){
      console.log("Event: " + event);
      fs.readFile(file, 'utf8', function (err, data) {
        if (err) throw err;
        content = data.toString();
      });
    }
  });

What i would like is whenever the file is updated, ws.send can be called for one of the websocket connection.


Solution

  • solved this with something like this

    var conn_array = [];
    app.ws('/', function(ws, req) {
        conn_array.push(ws)
        console.log("New connection")
    
        fs.readFile(file, 'utf8', function (err, data) {
            if (err) throw err;
            content = data.toString();
            if (content.length > 0) {
                console.log(content.length)
                conn_array[0].send(content)
            }
        });
    
    
        ws.on('message', function(msg, flags) {
            console.log("Received "+ msg);
        });
    
        ws.on('data', function(msg, flags) {
            var data = []; // List of Buffer objects
            res.on("data", function(chunk) {
                data.push(chunk); // Append Buffer object
                console.log(data)
            })
        })
    });
    
    function readFile(){
        console.log("I am here")
        fs.readFile(file, 'utf8', function (err, data) {
            if (err) throw err;
            content = data.toString();
            if (content.length > 0 && conn_array.length>0) conn_array[0].send(content);
        })
    }
    
    var interval = setInterval(readFile, 100000);
    

    for now i have assumed there is just one client