I can't figure out why this is returning both occurrences of the string /Most recent instantaneous value: ([^ ]+) /
I only need the first match.
var http = require("http");
var options = {
host: 'waterdata.usgs.gov',
port: 80,
path: '/ga/nwis/uv?cb_72036=on&cb_00062=on&format=gif_default&period=1&site_no=02334400'
};
function extract (body, cb) {
if(!body)
return;
var matches=body.match(/Most recent instantaneous value: ([^ ]+) /);
if(matches)
cb(matches[1]);
}
http.get(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
extract(chunk, function(v){ console.log(v); });
});
}).on('error', function(e) {
console.log('problem with request: ' + e.message);
});
The 'data' event is being fired many times.
You can fix it by changing the last part to:
http.get(options, function(res) {
var responseText = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
responseText += chunk;
});
res.on('end', function() {
extract(responseText, console.log);
});
}).on('error', function(e) {
console.log('problem with request: ' + e.message);
});