chunk data logging in node.js

2019-05-29 05:14发布

I have following function in node.js inside a http.request()

       res.on('data', function (chunk) {
    var sr="response: "+chunk;
    console.log(chunk);
    });

I get this in console

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

But when i use this:

res.on('data', function (chunk) {
    var sr="response: "+chunk;
    console.log(sr);
    });

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?

2条回答
男人必须洒脱
2楼-- · 2019-05-29 05:54

Chunk is just a buffer where the data is stored in Binary, so you could use utf8 for the character encoding as well which will output the data as String, and this you will need to do when you are creating the readStream.

var myReadStream = fs.createReadStream( __dirname + '/readme.txt', 'utf8');

myReadStream.on('data', function(chunk){
    console.log('new chunk received');
    console.log(chunk);
})
查看更多
爷、活的狠高调
3楼-- · 2019-05-29 06:15

chunk is a Buffer, which is Node's way of storing binary data.

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

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

查看更多
登录 后发表回答