Node.js - 缓冲区与 Uint8Array

Node.js - Buffer vs Uint8Array

在fs模块的文档1中,我们可以读到(对于writeFile方法):

const data = new Uint8Array(Buffer.from('Hello Node.js'));

在同一文档中 2 说:

With TypedArray now available, the Buffer class implements the Uint8Array API in a manner that is more optimized and suitable for Node.js.

所以如果 Buffer class 实现了一个 Unint8Array,你能告诉我为什么我们需要从 Buffer 转换成 Unint8Array 吗?

Uint8Array 是一个通用的字节数组,在 nodejs 和浏览器中都可用。 Buffer 是 Uint8Array 的子类,仅在 nodejs 中可用(出于历史原因)。两者都主要用于处理二进制(字节)数据。

从历史上看,当 nodejs 刚出现时,通用的 Uint8Arrays 并不存在,因此它必须发明自己的“Buffer”类型来处理二进制数据。在 es6 中引入了通用 Uint8Arrays 之后,nodejs(4.0 版之后)决定将 Buffer 从单独的数据类型迁移过来 -> Uint8Array 的子类(尝试使其与 Uint8Array 的浏览器更加兼容)。

https://www.quora.com/What-is-the-relationship-between-a-Buffer-and-an-Uint8Array-in-Node-js