<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: George Ferreira</title>
    <description>The latest articles on DEV Community by George Ferreira (@george_ferreira).</description>
    <link>https://dev.to/george_ferreira</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1744133%2F8a7a9c6d-9c78-448c-8944-5626f0ec256a.png</url>
      <title>DEV Community: George Ferreira</title>
      <link>https://dev.to/george_ferreira</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/george_ferreira"/>
    <language>en</language>
    <item>
      <title>Using Streams in Node.js: Efficiency in Data Processing and Practical Applications</title>
      <dc:creator>George Ferreira</dc:creator>
      <pubDate>Mon, 08 Jul 2024 22:34:48 +0000</pubDate>
      <link>https://dev.to/george_ferreira/using-streams-in-nodejs-efficiency-in-data-processing-and-practical-applications-2jig</link>
      <guid>https://dev.to/george_ferreira/using-streams-in-nodejs-efficiency-in-data-processing-and-practical-applications-2jig</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;We've all heard about the power of streams in Node.js and how they excel at processing large amounts of data in a highly performant manner, with minimal memory resources, almost magically. If not, here's a brief description of what streams are.&lt;/p&gt;

&lt;p&gt;Node.js has a package/library called &lt;code&gt;node:stream&lt;/code&gt;. This package defines, among other things, three classes: &lt;code&gt;Readable&lt;/code&gt;, &lt;code&gt;Writable&lt;/code&gt;, and &lt;code&gt;Transform&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Readable&lt;/strong&gt;: Reads data from a resource and provides synchronization interfaces through signals. It can "dispatch" the read data to an instance of Writable or Transform.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Writable&lt;/strong&gt;: Can read from a Readable (or Transform) instance and write the results to a destination. This destination could be a file, another stream, or a TCP connection.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Transform&lt;/strong&gt;: Can do everything Readable and Writable can do, and additionally modify transient data.
We can coordinate streams to process large amounts of data because each operates on a portion at a time, thus using minimal resources.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Streams in Practice
&lt;/h2&gt;

&lt;p&gt;Now that we have a lot of theory, it's time to look at some real use cases where streams can make a difference. The best scenarios are those where we can quantify a portion of the data, for example, a line from a file, a tuple from a database, an object from an S3 bucket, a pixel from an image, or any discrete object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Generating Large Data Sets
&lt;/h3&gt;

&lt;p&gt;There are situations where we need to generate large amounts of data, for example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Populating a database with fictional information for testing or presentation purposes.&lt;/li&gt;
&lt;li&gt;Generating input data to perform stress tests on a system.&lt;/li&gt;
&lt;li&gt;Validating the performance of indexes in relational databases.&lt;/li&gt;
&lt;li&gt;Finally using those two 2TB HDDs we bought to set up RAID but never used (just kidding, but seriously).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this case, we will generate a file with 1 billion clients to perform tests on a fictional company's database: "Meu Prego Pago" (My Paid Nail). Each client from "Meu Prego Pago" will have the following attributes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ID&lt;/li&gt;
&lt;li&gt;Name&lt;/li&gt;
&lt;li&gt;Registration date&lt;/li&gt;
&lt;li&gt;Login&lt;/li&gt;
&lt;li&gt;Password&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The main challenge of generating a file with a large volume of data is to do so without consuming all available RAM. We cannot keep this entire file in memory.&lt;/p&gt;

&lt;p&gt;First, we'll create a Readable stream to generate the data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { faker } from '@faker-js/faker';
import { Stream } from "node:stream"

function generateClients(amountOfClients) {

    let numOfGeneratedClients = 0;

    const generatorStream = new Stream.Readable({
        read: function () {
            const person = {
                id: faker.string.uuid(),
                nome: faker.person.fullName(),
                dataCadastro: faker.date.past({ years: 3 }),
                login: faker.internet.userName(),
                senha: faker.internet.password()
            };

            if (numOfGeneratedClients &amp;gt;= amountOfClients) {
                this.push(null);
            } else {
                this.push(Buffer.from(JSON.stringify(person)), 'utf-8');
                numOfGeneratedClients++;
            }
        }
    })

    return generatorStream;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;generateClients&lt;/code&gt; function defines a stream and returns it. The most important part of this function is that it implements the &lt;code&gt;read&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;read&lt;/code&gt; method controls how the stream retrieves data using &lt;code&gt;this.push&lt;/code&gt;. When there is no more data to be read, the read method invokes &lt;code&gt;this.push(null)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We also use the library &lt;code&gt;'@faker-js/faker'&lt;/code&gt; here to generate fictional client data.&lt;/p&gt;

&lt;p&gt;Node.js has numerous implementations of the stream classes. One of them is &lt;code&gt;fs.createWriteStream&lt;/code&gt;, which creates a Writable stream that writes to a file (as you may have guessed by the name).&lt;/p&gt;

&lt;p&gt;We will use this stream to save all clients generated by generateClients.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import fs from "node:fs"

import {generateClients} from "./generate-clients.js"

const ONE_BILLION = Math.pow(10, 9);

// output file
const outputFile = "./data/clients.csv"

// get the clients stream
const clients = generateClients(ONE_BILLION);

// erase the file (if it exists)
fs.writeFileSync(outputFile, '', { flag: 'w' })

// add new clients to the file
const writer = fs.createWriteStream(outputFile, { flags: 'a' });

clients.pipe(writer);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The "pipe" Method
&lt;/h2&gt;

&lt;p&gt;We can see that to connect the Readable stream and the Writable stream, we use the &lt;code&gt;pipe&lt;/code&gt; method. This method synchronizes the transfer of data between the read and write streams, ensuring that a slow writer isn't overwhelmed by a very fast reader and thus avoiding excessive memory allocation as a buffer for data transfer between streams. There are more implementation details here, but that's a topic for another time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Results
&lt;/h2&gt;

&lt;p&gt;Here we can see how this process consumes memory while generating the file:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdrfq3zxc2mbhtqa1hhzh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdrfq3zxc2mbhtqa1hhzh.png" alt="Image showing the memory usage of the node application generating the 1 billion lines file. It is a print screen from the HTOP Unix application" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As shown, the process consumes approximately 106MB of RAM consistently. We can alter this memory consumption by providing extra parameters to the streams during their creation or by creating our own streams.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We can use Node.js to handle large amounts of data. Even when creating files with gigabytes of information and millions of lines, we use only a small amount of memory.&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>performance</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
