node.js – 表示如何定期检查自定义事件并自动执行操作

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

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

现在您可以看到上面的代码,无论何时创建连接,它都会检查内容的长度,并在超过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();
      });
    }
  });

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

由于您的服务器是更改文件的服务器,因此您无需使用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
  }
});

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

本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院