2017-05-26 29 views
1

我正在研究设置简单Node服务器的代码here。我已经看到并习惯了将数据块保存在一个数组中并最终将它们连接在一起的习惯用法。Node http请求中的数据块的类型

http.createServer(function(request, response) { 
    var body = []; 
    request.on('data', function(chunk) { body.push(chunk); }); 
    request.on('end', function() { body = Buffer.concat(body).toString(); 
    ... 
  1. 什么是chunk类型?Documentation说这是Bufferstring,但哪一个?

  2. 安全呼叫Buffer.concat(body)其中body是一个字符串数组吗?Documentation of Buffer.concat(list)表示list应该是Buffer实例的列表。字符串是“缓冲区实例”吗?

回答

2

相同的文档还指出:

如果默认编码已被使用readable.setEncoding()方法的流中指定的侦听器回调将被传递数据作为字符串的块;否则数据将作为Buffer传递。

因为你的代码没有调用setEncoding,所以chunk将是一个Buffer。

安全呼叫Buffer.concat(body)其中body是一个字符串数组吗?

> Buffer.concat(['foo', 'bar', 'xxx']) 
TypeError: "list" argument must be an Array of Buffers 

所以没有。但由于body将是缓冲区数组,Buffer.concat(body)应该工作得很好。