我正在学习代码here设置一个简单的 Node 服务器。我已经多次看到并使用过这种将数据 block 保存在数组中并最终将它们连接在一起的习惯用法。
http.createServer(function(request, response) {
var body = [];
request.on('data', function(chunk) { body.push(chunk); });
request.on('end', function() { body = Buffer.concat(body).toString();
...
chunk
的类型是什么? Documentation说它是Buffer
或string
,但哪个呢?调用
Buffer.concat(body)
是否安全,其中body
是一个字符串数组? Documentation ofBuffer.concat(list)
说list
应该是 Buffer 实例的列表。字符串是“缓冲区实例”吗?
最佳答案
同一文档还指出:
The listener callback will be passed the chunk of data as a string if a default encoding has been specified for the stream using the
readable.setEncoding()
method; otherwise the data will be passed as aBuffer
.
因为您的代码没有调用 setEncoding
,chunk
将是一个 Buffer。
Is it safe to call
Buffer.concat(body)
wherebody
is an array of strings?
> Buffer.concat(['foo', 'bar', 'xxx'])
TypeError: "list" argument must be an Array of Buffers
所以没有。但是由于 body
将是一个 Buffer 数组,Buffer.concat(body)
应该可以正常工作。
关于node.js - Node http请求中数据 block 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44208829/