通过websockets的Node.js JSON格式化问题

我有以下Node.js代码,调用天气web服务来获得json repsonse:

var reqGet = https.request(optionsgetmsg, function(res) { console.log("statusCode: ", res.statusCode); // uncomment it for header details // console.log("headers: ", res.headers); res.on('data', function(d) { console.info('GET result after POST:\n'); process.stdout.write(d); console.info('\n\nCall completed'); }); return d; }); 

当我使用process.stdout.write(d)到terminal的输出是相当JSON格式的文本,如下所示:

 { "response": { "version":"0.1", "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", "features": { "geolookup": 1 , "conditions": 1 } } , "location": { "type":"CITY", "country":"US", "country_iso3166":"US", "country_name":"USA", "state":"IN", "city":"Indianapolis", "tz_short":"EDT", "tz_long":"America/Indianapolis" } } 

但是,当我尝试使用socket.io发射d时,在chrome开发工具中查看对象时会变成一堆数字。

 io.sockets.on('connection',function(socketWeather){ socketWeather.emit('weather', { weather: d }); }); 

Chrome控制台输出(包含8616个随机数字的巨大数组):

 Object {weather: Array[8616]} 

我怎样才能得到漂亮的JSON格式文本正确推送到我的客户端?

更新:我只注意到,虽然process.stdout.write(d)给了我很好的JSON, console.info(d)console.log(d)都在terminal打印出来:

 <Buffer 0a 7b 0a 20 20 22 72 65 73 70 6f 6e 73 65 22 3a 20 7b 0a 20 20 22 76 65 72 73 69 6f 6e 22 3a 22 30 2e 31 22 2c 0a 20 20 22 74 65 72 6d 73 6f 66 53 65 72 ...> 

您遇到的问题是数据正在从stream中返回。 stdout支持stream,所以它看起来应该是这样。 console.log另一方面在每个实例之后都附加一个换行符,以便在将streampipe道输出到标准输出之前中断stream,以便直接写入缓冲区。

而不是logging每个数据,甚至build立数据到一个variables,并在结束事件处理输出。

  var response = ''; res.on('data', function(d) { response += data; }); res.on('end', function(d) { console.log(response); // now you can do what you need to with it including passing it to the socket }); 

作为替代scheme,您可以在浏览器端通过将stream缓冲区转换为string来处理它,但个人而言,我宁愿将该逻辑保留在后端。