express-ws如何定期检查自定义事件并自动执行操作

bru*_*ker 6 filesystemwatcher websocket node.js express

我正在使用express-ws https://www.npmjs.com/package/express-ws(有助于为express和websocket客户端创建服务器的API).

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)
    })
  })
});
Run Code Online (Sandbox Code Playgroud)

现在您可以看到上面的代码,无论何时创建连接,它都会检查内容的长度,并在超过0时向客户端发送conetent.

遵循路由器代码,在Web请求上更新文件.如果在连接创建后的某个时间(如果此文件被修改),此连接不知道它,因此不会调用此函数,因此不会调用send函数.我也试过fs.watch但是我无法让它工作.

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();
      });
    }
  });
Run Code Online (Sandbox Code Playgroud)

我想要的是每当文件更新时,可以为其中一个websocket连接调用ws.send.

Rud*_*ing 5

由于您的服务器是更改文件的服务器,因此fs.watch您无需使用文件更改时的已知信息.剩下要做的就是遍历打开的连接列表并向它们发送新内容.

var connections = []; // Keeps track of all connections
app.ws('/', function(ws, req) {
   console.log("New connection")
   connections.push(ws); // Add the new connection to the list

  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)
    })
  })
  // TODO: Make sure you remove closed connections from `connections`
  // by listening for the ws `close` event.
});

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' });

  connections.forEach(function(c){
    c.send(text); // Send the new text to all open connections
  }
});
Run Code Online (Sandbox Code Playgroud)

请注意:如果您有多个进程或服务器,这将不起作用,但由于您正在写入本地文件系统而不是数据库,我认为这不是必需的.


bru*_*ker 2

用这样的东西解决了这个问题

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);
Run Code Online (Sandbox Code Playgroud)

现在我假设只有一个客户