具有更新的变量的文件,以及其他文件看到的更改

File with variable that gets updated, and other files see that change?

本文关键字:文件 及其他 更新 变量      更新时间:2023-09-26

我正在尝试构建一个简单的工具,它ping一堆url来监控它们的状态,并根据每个应用程序的状态更新一个变量。

我还有另一个文件,我希望能够随时执行它,从该变量中获取每个应用程序的当前状态。

这是我的主文件,您可以看到有两个导出-start和getStatues。

index.js

'use strict';
const rest = require('restler');
const time = require('simple-time');
const seconds = time.SECOND;
// The list of apps to check if are running
var apps = {
  myApp: {
    url: 'http://myUrl.com',
    status: null,
    lastUpdatedAt: new Date()
  }
};
/**
 * Loop through and check the status of every app
 */
function checkAllStatuses() {
  for (var name in apps) {
    if (apps.hasOwnProperty(name)) {
      var app = apps[name];
      console.log('app = ', app);
      checkAppStatus(name, app);
    }
  }
}
/**
 * Checks the status of an app
 *
 * @param name  - The name of the app
 * @param app   - The app that we're checking the status of
 */
function checkAppStatus(name, app) {
  var req = rest.get(app.url);
  req.on('complete', function(result, response) {
    if(response.statusCode !== app.status) {
      updateStatus(name, response.statusCode);
    }
  });
  req.on('error', function(e) {
    console.log('ERROR: ' + e.message);
  });
  req.on('timeout', function(data, response) {
    console.log('Request timed out');
  });
}
/**
 * Updates the status of an app
 * 
 * @param app     - The app to update the status of
 * @param status  - The status to update the app to
 */
function updateStatus(name, status) {
  apps[name].status = status;
  apps[name].lastUpdatedAt = new Date();
}
function getStatuses() {
  return apps;
}
function start() {
  // Check every 5 seconds
  setInterval(checkAllStatuses, 5*seconds);
}
module.exports.start = start;
module.exports.getStatuses = getStatuses; 

然后我有一个文件,它开始了这个过程:

start.js

'use strict';
const status = require('./index');
status.start();

然后我有一个文件,我想执行以获得应用程序的当前状态:

consumer.js

'use strict';
const status = require('./index');
console.log(status.getStatuses());

问题是consumer.js只显示index.js中初始app变量中的内容,即:

{
      myApp: {
        url: 'http://myUrl.com',
        status: null,
        lastUpdatedAt: new Date()
      }
    };

而运行CCD_ 2命令的进程正在显示非空的更新状态。

如何使consumer.js能够看到start.js正在更新的变量的值?

如果可能的话,我希望不必使用数据存储。最糟糕的情况是,我写入一个文件,运行redis、mongo或其他数据存储,但我试图避免这种情况,使这个应用程序尽可能简单。

start.jsconsume.js中使用相同的代码index.js,但在运行每个文件时创建两个独立的实例。也就是说,apps变量在start.js创建的实例中发生变化,但consume.js中没有任何内容告诉您的代码更改apps变量。

如果您没有保存状态的历史记录,或者没有将数据保存到数据存储,那么启动例程有什么意义?您可以调用checkAllStatuses,然后在希望使用数据时返回结果。

编辑以下是将两个文件(start.jsconsume.js)组合为一个文件的示例。它还添加了一个示例socket.io实现,因为您已经说过,通过websocket向客户端提供状态是最终目标。

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
//// Your status library
var status = require('./index');
//// Start getting statuses
status.start();
app.listen(80);
//
// This is just the default handler
//   in the socket.io example
//
function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}
io.on('connection', function (socket) {
  // Someone wants the list of statuses
  //   This uses socket.io acknowledgements
  //   to return the data. You may prefer to use 
  //   `socket.emit` instead or an altogether different socket library.
  socket.on('status_fetch', function (data, callback_fn) {
    callback_fn( status.getStatuses() );
  });
});