node.js - Node http请求中数据 block 的类型

标签 node.js

我正在学习代码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();
  ...
  1. chunk 的类型是什么? Documentation说它是 Bufferstring,但哪个呢?

  2. 调用 Buffer.concat(body) 是否安全,其中 body 是一个字符串数组? Documentation of Buffer.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 a Buffer.

因为您的代码没有调用 setEncodingchunk 将是一个 Buffer。

Is it safe to call Buffer.concat(body) where body 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/

相关文章:

node.js - 全局安装 NPM 包时行为不一致

node.js - 来自 mongoDB 的空 [] 响应是 Node.js express get 函数的结果?

javascript - 无法使用 node.js v0.12.7、express 4、body-parser、bootstrap 3 检索 POST 数据

javascript - Puppeteer Bright Data 代理返回 ERR_NO_SUPPORTED_PROXY 或 CERT 错误

javascript - JavaScript 中的模式匹配

javascript - 构造函数的继承属性

使用 HTTP Range header 的 Node.js 脚本请求导致字节数多于请求的字节数。

javascript - Node.js 使用哪种线程模型?

node.js - 使用 sockjs 设置 SSL

node.js - Jest : how to restore to a previous mocked implementation (not the original)