2017-12-23 9 views
0

2 개의 API에서 데이터를 수집하고 응답을 파일에 저장하는 스크립트가 있습니다. 그것은 1 분마다 실행되므로 첫 번째 응답을 캐시하고 두 번째 응답의 일부가 파일을 저장하기 전에 동일하지 않은지 확인하여 스크립트를 최적화하려고합니다.노드 : 메모리 캐시 비교시

캐시를 읽을 수있는 것으로 변환하는 데 문제가 있습니다. 두 번 이상 호출되는 res.on('data' ...을 사용하고 있습니다.

저장하기 전에 두 응답을 비교하는 더 좋은 방법이 있습니까? res.on('data'을 사용하지 않고 데이터를 사람이 읽을 수있는 것으로 변환 할 수 있습니까?

도움 주셔서 감사합니다.

API를 응답 헤더에서
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, 비교할 수있는 content-length 당신이 몸의 내용을 비교하기 전에 ?

2 인 경우 buf.compare()을 사용하여 인코딩 전에 내용을 비교할 수 있습니다.

3, https.get은 비동기 코드이며 cachedResponse은 두 요청으로 인터리브 될 수 있습니다.

희망 사항이 정보는 유용 할 것입니다.