node.js中的块数据记录 [英] chunk data logging in node.js
问题描述
我在http.request()中的node.js中有以下函数
I have following function in node.js inside a http.request()
res.on('data', function (chunk) {
var sr="response: "+chunk;
console.log(chunk);
});
我在控制台得到这个
<Buffer 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f
64 69 6e 67 3d 22 75 74 66 2d 38 22 20 3f 3e 3c 72 65 73 75 6c 74 3e 3c 73 75 63
...>
但是当我使用它时:
res.on('data', function (chunk) {
var sr="response: "+chunk;
console.log(sr);
});
我得到一个正确的xml响应:
I get a proper xml response like this:
responose: .....xml responose.....
我不明白为什么我需要附加一个字符串来输出正确的响应。第一个代码中生成的响应是什么意思?
I don't understand why i need to append a string to output the proper response. And what is meant by the response generated in the first code?
推荐答案
chunk
是缓冲区,这是Node存储二进制数据的方式。
chunk
is a Buffer, which is Node's way of storing binary data.
因为它是二进制数据,所以在正确显示之前需要将其转换为字符串(否则, console.log
将显示其对象表示)。一种方法是将其附加到另一个字符串(第二个示例就是这样),另一种方法是调用 toString()
:
Because it's binary data, you need to convert it to a string before you can properly show it (otherwise, console.log
will show its object representation). One method is to append it to another string (your second example does that), another method is to call toString()
on it:
console.log(chunk.toString());
但是,我认为当 chunk $时,这可能会失败c $ c>包含不完整的字符(UTF-8字符可以包含多个字节,但是你不能保证
chunk
不会在这样一个字节串的中间)。
However, I think this has the potential of failing when chunk
contains incomplete characters (an UTF-8 character can consist of multiple bytes, but you don't get the guarantee that chunk
isn't cut off right in the middle of such a byte string).
这篇关于node.js中的块数据记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!