javascriptnode.jsbufferuint8array

Node.js - Buffer vs Uint8Array


In the documentation 1 of the fs module, we can read (for the writeFile method):

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

In the same documentation 2 it is said:

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

So if the Buffer class implements a Unint8Array, could you enlighten me why we need to convert to an Unint8Array from a Buffer?


Solution

  • Uint8Array is a general-purpose byte-array that’s available in both nodejs and browsers. Buffer is a subclass of Uint8Array that’s only available in Node.js (for historical reasons). both are primarily used for manipulating binary (byte) data.

    historically, when Node.js first came about, general-purpose Uint8Arrays didn’t exist, so it had to invent its own “Buffer” type for handling binary-data. after general-purpose Uint8Arrays were introduced with ES6, Node.js (after version 4.0) decided to migrate Buffer over from a separate data-type -> subclass of Uint8Array (to try and make it more browser-compatible with Uint8Array).

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