Premium lesson

Manipulating Bytes in Node.js

Node.js4 min readJan 1, 2025

In Node.js, a Buffer is a built-in object of fixed length that provides a way to store and work with data, similar to an array in JavaScript.

However, unlike arrays, buffers are more suitable for dealing with binary data for operations such as reading from or writing to non text-based files (e.g., images, audio files) and manipulating low-level network data (e.g., network packets).

Note that while the Buffer class is available within the global scope, it is still recommended to explicitly reference it via a require or import statement.

// CommonJS syntaxconst { Buffer } = require('node:buffer');// ECMAScript syntaximport { Buffer }  from 'node:buffer';

Character encodings

馃摎 Definition: In programming, character encoding is a system that maps characters to specific values, to ensure that text data is displayed correctly across different systems.

For example, in the UTF-8 encoding, the letter 'A' is encoded as the decimal value 65 (or 41 in hexadecimal).

In Node.js, the Buffer class is a subclass of the Uint8Array class, which means that it can only store 8-bit unsigned integers from 0 to 255.

By default, bytes are encoded in UTF-8 and represented in hexadecimal.

For example, the following buffer contains the hexadecimal values of the UTF-8 encoded string 'hello':

<Buffer 68 65 6c 6c 6f>
icon light bulb key

Unlock the Build CLI Apps in JavaScript & Node.js module

Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.

You get immediate access to:

  • 45 focused lessons across JavaScript, Node.js, npm, and Git
  • 17 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module