最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

节点:在内存缓存比较中

运维笔记admin14浏览0评论

节点:在内存缓存比较中

节点:在内存缓存比较中

我有一个脚本,它从2个API收集数据并将响应存储在一个文件中。它每分钟运行一次所以我现在尝试通过缓存第一个响应来优化我的脚本,并在保存文件之前检查第二个响应的任何部分是不一样的。

我遇到了将缓存转换为可读内容的问题。我正在使用被称为不止一次的res.on('data' ...

在保存之前有没有更好的方法来比较两个响应?我可以在不使用res.on('data'的情况下将数据转换为人类可读的内容吗?

谢谢你的帮助!

var https = require('https');
var fs = require('fs');

var cachedResponse;

function cash(res) {
  return new Promise(function(resolve, reject) {
    var data = '';
    res.setEncoding('utf8');
    res.on('data', function(chunk) {
      data += chunk;
    });

    res.on('end', function() {
      cachedResponse = data;
      resolve(cachedResponse);
    });
  });
}

function download(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = https
    .get(url, function(res) {
      var oldCache = cachedResponse;
      cash(res).then(res => {
        console.log('CACHED', oldCache, res);
        // check that new response doesn't equal oldCache before saving
         res.pipe(file);
         file.on('finish', function() {
           file.close(cb); // close() is async, call cb after close completes.
         });
      });
    })
    .on('error', function(err) {
      // Handle errors
      fs.unlink(dest); // Delete the file async. (But we don't check the result)
      if (cb) cb(err.message);
    });
}

var downloadStationAndPoints = function() {
  var timestamp = new Date().getTime();
  var stationsUrl = 'https://url/stations/stations.json';
  var pointsUrl = 'https://url/scores';
  var stationsDest = `${__dirname}/data/stations_${timestamp}_.json`;
  var pointsDest = `${__dirname}/data/points_${timestamp}_.json`;
  var cb = function(err) {
    if (err) {
      console.log('error in download at time:', timestamp, ', message:', err);
    }
  };
  download(stationsUrl, stationsDest, cb);
  download(pointsUrl, pointsDest, cb);
};

// run

setInterval(() => {
  downloadStationAndPoints();
}, 5000);
回答如下:

1,在比较身体内容之前,你能比较apis响应头中的content-length吗?

2,你可以使用bufpare()来比较编码前的内容。

3,https.get是异步的,因为你的代码,cachedResponse可能会写入两个请求交错。

希望这些对您有用。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论