为什么使用`Buffer.concat(body).toString();`而不是`Uint8Array / Buffer.toString()`

时间:2016-10-25 10:53:20

标签: javascript node.js

我正在阅读有关收集请求数据的this article,并提供了以下示例:

var body = [];
request.on('data', function(chunk) {
  body.push(chunk);
}).on('end', function() {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

其他教程建议采用这种方式:

var total = [];
request.on('data', function(chunk) {
  total += chunk;
}).on('end', function() {
  body = total.toString();
  // at this point, `body` has the entire request body stored in it as a string
});

他们似乎是等同的。为什么要使用更精细的Buffer.concat(body).toString();呢?

1 个答案:

答案 0 :(得分:3)

  

为什么使用Buffer.concat(body).toString();代替UintArray8.toString()

因为他们正在做totally different件事。但这不是你真正的问题,chunkBuffer而不是Uint8Array

  

收集请求数据的两种方式似乎是等效的。有什么区别?

第二段代码绝对是可怕的代码。不要使用它。首先,它应该是这样写的:

var total = "";
request.on('data', function(chunk) {
  total += chunk.toString();
}).on('end', function() {
  // at this point, `total` has the entire request body stored in it as a string
});

如果你正在对数组进行字符串连接,那么从数组开始是绝对无意义的,total.toString()仅在没有data事件的情况下是必需的。从一开始就total最好是一个字符串。在chunk.toString()中,显式方法调用是不必要的(省略它会导致它被隐式调用),但我想展示这里发生的事情。

现在,如何将chunk缓冲区转换为字符串并将它们连接起来,不同于收集数组中的缓冲区,将它们连接到一个大缓冲区并将其转换为字符串?

答案是多字节字符。根据编码和正文文本,可能存在由多个字节表示的字符。可能会发生这些字节跨越两个块的边界(在后续的data事件中)。使用分别解码每个块的代码,在这些情况下,您将得到无效结果。

相关问题