gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:29:04 26 4
gpt4 key购买 nike

我有以下调用天气网络服务以获取 json 响应的 Node.js 代码:

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.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) 都在终端中打印出来:

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

作为替代方案,您可以在流缓冲区到达后将其转换为字符串,从而在浏览器端处理它,但就我个人而言,我宁愿将该逻辑保留在后端。

关于javascript - 通过 websockets 的 Node.js JSON 格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23570714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com