Course contentsShow
← Node.js
Lesson 393 of 1,9805. Streams and BackpressureFree lesson

Encoding and Decoding Streams

Transform binary stream payloads into readable strings or objects using the appropriate stream configurations.

In this lesson, you will learn how to seamlessly transform raw binary data flowing through your streams into readable strings or JavaScript objects.

The Bridge Between Bytes and Data

By default, Node.js streams operate on Buffer objects, which are essentially raw memory containing binary sequences. While efficient for the computer, this isn't very useful if you are trying to parse a JSON file, read a text log, or manipulate string content.

Instead of manually converting every chunk inside a data event, you can configure your streams to perform this translation automatically. This process is called "Encoding" and "Decoding."

Configuring Stream Encodings

The most straightforward way to handle this is by providing an encoding option when initializing a stream. By setting the encoding property (commonly to utf8), the stream internalizes the logic of turning binary Buffer fragments into usable strings before they ever reach your application code.

const fs = require('fs');

// By setting encoding to 'utf8', we receive strings instead of Buffers
const readable = fs.createReadStream('data.txt', { encoding: 'utf8' });

readable.on('data', (chunk) => {
  console.log(typeof chunk); // "string"
  console.log(chunk.toUpperCase());
});

From Strings to Objects

Often, the data you read isn't just a string—it is structured information like JSON. If you are dealing with a large stream of JSON objects, you don't want to receive fragmented strings that might break your parser.

In these cases, you would use a Transform stream. You can bridge the gap by creating a stream that buffers the incoming string chunks until a delimiter (like a newline) is reached, then parses that string into a JavaScript object. This transforms your stream from a "raw byte pipe" into a "data object pipeline," allowing you to work with high-level structures while maintaining the memory efficiency of streaming.

By offloading the decoding process to the stream configuration, you keep your event handlers clean and focused on business logic rather than buffer manipulation.

Key Takeaway: Setting the encoding option on a stream automates the conversion of binary chunks into readable strings, allowing you to process high-level data types directly in your stream pipeline.