-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
76 lines (51 loc) · 1.73 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
var request = require('request');
var fs = require('fs');
var path = require('path');
function compareData(incomingjson){
// THE ARCHIVED FILE TO OPEN AND CHECK AGAINST...
var filePath = path.join(__dirname, 'my_file.txt');
// USE FS TO OPEN AND READ THE FILE CONTENT...
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (!err){
// IF THE READ FILES' CONTENT EQUALS THE
// JSON STRING PASSED INTO THIS FUNCTION...
if (data === incomingjson){
// IF THE DATA (STRINGS) DON'T MATCH...
console.log('MATCH, no update as of ' + new Date().toLocaleString());
} else {
// IF THEY DO MATCH...
console.log('**************************');
console.log('UPDATED DATA ' + new Date().toLocaleString());
console.log('**************************');
// SAVE THE NEW DATA TO THE LOCAL FILE FOR FUTURE COMPARISONS...
saveData(incomingjson);
}
} else {
// ERROR READING LOCAL FILE...
console.log(err);
}
});
};
function saveData(bodytext){
// SAVE THE DATA TO A LOCAL FILE
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
stream.write(bodytext);
stream.end();
});
};
function runLoop(){
// REPEATEDLY READ THE RESPONSE OF THE URL... PASSING IN THE REQUIRED FORM VARS...
request.post({url:'https://news.ycombinator.com', form: {
// IF I WANTED TO SEND POST VARS ALONG WITH THE REQUEST...
//key:'value'
}}, function(err,httpResponse,body){
//myArray = JSON.parse(body); // IF I WANTED TO PARSE THE JSON RESPONSE...
// RUN THE COMPARISON FUNCTION
compareData(body);
});
};
// START THE CHECK... DO RE-CHECK EVERY 5 SECONDS
setInterval(function(){
runLoop();
}, 5000)