NodeJS by Example: Read Streams
|
Read Streams allow you to efficiently read data from a source piece by piece, rather than loading everything into memory at once. This is essential for handling large files or continuous data sources. |
|
|
First, let's import the required modules. The fs module provides the createReadStream function, and we'll use Readable for creating custom streams. |
|
|
Creating a Read Stream from a File The simplest use case is reading a file. By default, streams emit Buffer chunks. We can specify an encoding to get strings instead. |
|
|
Handling Stream Events
Readable streams emit several important events:
|
|
|
Pausing and Resuming Streams can be paused and resumed. This is useful when you need to slow down data consumption, for example when writing to a slower destination. |
|
|
Using Async Iteration Modern Node.js supports async iteration on streams, providing a cleaner syntax using for-await-of loops. This is often the preferred approach. |
|
|
Creating Readable Streams from Iterables You can create readable streams from arrays, generators, or any iterable using Readable.from(). This is useful for testing or creating data pipelines. |
|
|
Reading in Paused Mode Streams operate in two modes: flowing and paused. In paused mode, you must explicitly call read() to get chunks of data. |
|
|
Stream Options
createReadStream accepts several useful options:
|
|
|
Create a sample file to test with |
|
|
Run the read streams example |
|