Learn about the DataView object and its usage
The DataView object is a view into an ArrayBuffer, similar to Typed Arrays. However, the items in the array can have different sizes and types. Let’s explore how to use it with an example:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
When creating a DataView, we can specify the starting byte and the length of the view:
const view = new DataView(buffer, 10) //start at byte 10
const view = new DataView(buffer, 10, 30) //start at byte 10, and add 30 items
If no additional arguments are provided, the view starts at position 0 and includes all the bytes in the buffer.
To add data into the buffer, the DataView object provides a set of methods:
- setInt8()
- setInt16()
- setInt32()
- setUint8()
- setUint16()
- setUint32()
- setFloat32()
- setFloat64()
Here’s an example of how to use one of these methods:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
view.setInt16(0, 2019)
By default, data is stored using big endian notation. If you want to use little endian instead, you can add a third parameter with the value true
:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
view.setInt16(0, 2019, true)
To retrieve data from the DataView, you can use the following methods:
- getInt8()
- getInt16()
- getInt32()
- getUint8()
- getUint16()
- getUint32()
- getFloat32()
- getFloat64()
Here’s an example of how to retrieve data from the view:
const buffer = new ArrayBuffer(64)
const view = new DataView(buffer)
view.setInt16(0, 2019)
view.getInt16(0) //2019
Since a DataView is an ArrayBufferView, it has three read-only properties:
- buffer: points to the original ArrayBuffer
- byteOffset: the offset on that buffer
- byteLength: the length of the content in bytes
It’s important to note that Typed Arrays do not allow us to control the endianness as they use the endianness of the system. If you need to have control over the endianness, the DataView object is the perfect choice.