2012-04-04 37 views
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); 
}); 
+0

我想,有几个是事件on'data':

您可以通过最后一部分改变来解决它。顺便说一句,你可以写'extract(chunk,console.log);' – kirilloid 2012-04-04 19:04:33

回答

0

'data'事件被多次触发。

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); 
}); 
相关问题