2017-12-23 9 views
0

2つのAPIからデータを収集し、レスポンスをファイルに格納するスクリプトがあります。毎分実行されるので、最初のレスポンスをキャッシュし、2番目のレスポンスの一部が同じでないことを確認してファイルを保存することで、スクリプトを最適化しようとしています。ノード:メモリキャッシュの比較

キャッシュを読み込み可能なものに変換する際に問題が発生しています。私は複数回呼び出されるres.on('data' ...を使用しています。

保存する前に2つの応答を比較するより良い方法はありますか? 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); 

答えて

0

1あなたは体の内容を比較する前に、あなたは、APIのレスポンスヘッダからcontent-lengthを比較することができますか?

2の場合、buf.compare()を使用してエンコード前の内容を比較できます。

3,https.getは非同期で、コードとしてcachedResponseは2つの要求でインターリーブされます。

希望している方が便利です。

関連する問題