0

/Most recent instantaneous value: ([^ ]+) /最初の一致のみが必要な 文字列の両方の出現を返す理由がわかりません。

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);
});
4

1 に答える 1

0

「データ」イベントが何度も発生しています。

最後の部分を次のように変更することで修正できます。

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);
});
于 2012-04-04T19:11:21.697 に答える