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

Node.js JSON formatting issue through websockets

本文关键字:JSON 格式 问题 js Node websockets 通过      更新时间:2023-09-26

我有以下Node.js代码,调用天气webservice以获得json响应:

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)时,输出到终端的是漂亮的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发出d时。当在chrome开发工具中查看对象时,它会变成一堆数字。

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

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

Object {weather: Array[8616]}

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

UPDATE:我刚刚注意到,虽然process.stdout.write(d)给了我很好的JSON, console.info(d)console.log(d)都在终端打印出这个:

<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 ...>

您遇到的问题是数据是从流返回的。Stdout支持流,因此它以应有的方式显示。另一方面,Console.log在每个实例后面附加一个换行符,这样它就可以在将流管道到stdout之前中断流,从而直接写入缓冲区。

不再记录每个数据,而是将数据构建到一个变量中,并在结束事件期间处理输出。

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

作为一种替代方法,你可以在浏览器端通过将流缓冲区转换为字符串来处理它,但我个人宁愿将该逻辑保留在后端