-
Notifications
You must be signed in to change notification settings - Fork 0
/
outside_temperature.js
55 lines (52 loc) · 1.5 KB
/
outside_temperature.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
var zlib = require("zlib");
var http = require("https");
module.exports = function (ctx, cb) {
var parse_weather = function(page) {
var pageRE = /temp_now:\s*'([\d\.]+)\s+°(F|C)'/;
var matches = page.match(pageRE);
if(matches) {
cb(null, { 'success': true, 'temperature': matches[1] + matches[2]})
} else {
cb(null, { 'success': false, 'error': "Could not find the temperature." } )
}
}
var zip = ctx.data.zip;
if(!zip) {
cb(null, { 'success': false, 'error': "no zip code specified" } );
return;
}
else {
var options = {
host: 'www.wunderground.com',
port: 443,
path: '/q/' + zip
};
http.get(options, function(res) {
var chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
var page_data = "";
var buffer = Buffer.concat(chunks);
var encoding = res.headers['content-encoding'];
if (encoding == 'gzip') {
zlib.gunzip(buffer, function(err, decoded) {
page_data = decoded.toString();
parse_weather(page_data);
});
} else if (encoding == 'deflate') {
zlib.inflate(buffer, function(err, decoded) {
page_data = decoded.toString();
parse_weather(page_data);
})
} else {
page_data = buffer.toString();
parse_weather(page_data);
}
})
}).on('error', function(e) {
cb(null, "Got error: " + e.message);
});
}
}