Scenario-based Learning - A New Learning Perspective. Node.js - Part 1
Tags: showdev, webdev, tutorial, beginners
Published: 2019-07-14 13:19:36

---
title: Scenario-based Learning - A New Learning Perspective. Node.js - Part 1
published: true
description: Scenario-based Learning - A New Learning Perspective. Node.js - Part 1
tags: showdev,webdev,tutorial,beginners
series : nodejs-scenario
canonical_url : https://cloudnweb.dev/2019/07/scenario-based-learning-a-new-learning-perspective-node-js-part-1/
---
<!-- wp:paragraph -->
<p> Welcome to this new Article series. Scenario-based Learning - A New Learning Perspective. Node.js - Part 1</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Whenever I want to learn new technology, I can able to find a lot of resources to learn the syntax of a particular programming language/technology.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But, I couldn't able to find resources which put me a production level problem scenario's, from which I can able to learn the technology.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>so, I thought why don't I create a one which will be helpful for developers like me to learn a programming language or technology by practicing a problem scenario.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>please do share it. <a href="http://eepurl.com/gvbr7j">Subscribe to my newsletter</a> for further updates .</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To Learn Javascript, read this article series  <a href="https://cloudnweb.dev/category/web-dev/">https://cloudnweb.dev/category/web-dev/</a> </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Why it is Important?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Every time, we learn something. we go and find something to implement it to get a good grasp of it. From, a beginner perspective of the technology. it is great.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But, there is a gap between a beginner who learns the technology to a person who works in the production level application. we really don't know what kind of a problem the particular technology solves in real industrial applications until we work for a company/ a freelancing project</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>What I am going to do is, I will be sharing all the problem scenarios that I faced in the production. So, the beginner for the particular technology can replicate the scenario on his own and learn from it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Basically, he/she is going to gain my experience through learning on his own. So, In the future, if he faces the same problem scenario, he/she can tackle it in an efficient way. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Node.js Experience</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This Blog series is from my Node.js Experience. Basically, I am a React,Node.js and MongoDB Developer.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Soon, I will share problem scenarios for React as well. I will start with a simple scenario this week. In upcoming articles, I will share more complex scenarios where you can learn from it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Scenario based Learning A New Learning Perspective</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Problem Scenario</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Recently, I faced a situation where I need to read a large sized file from internet and write it in my server.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To do this in Node.js, you can think of it like just read the file and write directly into the server. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But there is a problem with this approach, Let's say that we implement something like this</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const fs = require('fs');

fs.readFileSync('sample.mkv',(err,data) => {
    if(err) throw err;

    fs.writeFileSync('output',data,(err) => {
        if(err) throw err;
    })
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>the problem is,</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":983} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/07/bad_code.png" alt="" class="wp-image-983"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>There is a limit in <a href="https://nodejs.org/api/buffer.html">Node.js Buffer</a>, we can't store more than the Buffer size.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To address this problem, we need something called <a href="https://nodejs.org/api/stream.html">Stream</a> in Node.js.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Stream?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Storing a complete file in Memory is so expensive. also, we need to store the file without having this problem. To solve this, we use Stream which is nothing but processing the data in chunks.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Stream process the huge data in a chunk by chunk which store the chunk in memory one at a time.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Solution</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>we need to create a <strong>readable stream</strong> which reads the data from the source and <strong>writable stream</strong> which writes the data to the destination.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you are new to Node.js, I would suggest you watch some tutorials and try this problem scenarios.then, it will be easy to understand what is going on.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a href="https://www.youtube.com/watch?v=fBNz5xF-Kx4">Node.js Crash Course</a></li><li><a href="https://www.youtube.com/watch?v=TlB_eWDSMt4">Node.js Course - Mosh Hamedani</a></li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Solution Code</h4>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const fs = require('fs');
const stream = require('stream');

//creating a readable stream
const readable = fs.createReadStream('sample');

//creating a writable stream
const writable = fs.createWriteStream('output');

fs.stat('sample',(err,stats) => {

    this.filesize = stats.size;

    this.counter = 1;

    //this is an event which handles the data in chunks
    readable.on('data',(chunk) => {
        let percentageCopied = ((chunk.length * this.counter) / this.fileSize) * 100;
        process.stdout.clearLine(); 
        process.stdout.cursorTo(0);
        process.stdout.write(`${Math.round(percentageCopied)}%`);

        //writing the chunk into writable stream output
        writable.write(chunk);
        this.counter += 1;
    });


    readable.on('end', (e) => {
        console.log("Read is completed");
    });
    
    readable.on('error', (e) => {
        console.log("Some error occured: ", e);
    });
    
    writable.on('finish', () => {
        console.log("Successfully created the file copy!");
    });
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>It reads the data from the local file and writes it again from another local file. For the conceptual purpose, I have used the local file itself rather than a file from the internet.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There is also a problem with this approach, if you analyze the Memory Manager in your machine while this code runs. it will take a lot of memory.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The reason being is, Disk write will not cope up with a speed of Disk Read . Reading a disk will be faster than Writing into a disk.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Beauty is, we can solve this problem too.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Efficient Solution</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Node.js Stream has a solution for the above problem which is <strong><a href="https://nodejs.org/es/docs/guides/backpressuring-in-streams/">backpressure</a></strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>
const stream = require('stream');
const fs = require('fs');

let fileName = 'sample'

const readabale = fs.createReadStream(fileName);
const writeable = fs.createWriteStream("output");

fs.stat(fileName, (err, stats) => {
    this.fileSize = stats.size;
    this.counter = 1;
    this.fileArray = fileName.split('.');
    
    try {
        this.fileoutputName = "output" + "/" + this.fileArray[0] + '_Copy.' + this.fileArray[1];
    } catch(e) {
        console.exception('File name is invalid');
    }
    
    process.stdout.write(`File: ${this.fileoutputName} is being created:`);
    
    readabale.on('data', (chunk) => {
        let percentage = ((chunk.length * this.counter) / this.fileSize) * 100;
        process.stdout.clearLine();  // clear current text
        process.stdout.cursorTo(0);
        process.stdout.write(`${Math.round(percentage)}%`);
        this.counter += 1;
    });
    
    //Note this line : Read Stream pipes the Write Streams
    readabale.pipe(writeable);
    
    // In case if we have an interruption while copying
    writeable.on('unpipe', (e) => {
        process.stdout.write("Write Failed!");
    });
    
});;
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The only change that we did with the previous solution is to <strong>pipe</strong> the <strong>readable stream</strong> to the <strong>writable stream</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>it will automatically control the disk read and write speed, thus it will not choke the RAM.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>this is a simple solution to implement. This same concept can be used in some other Technical problem scenarios also</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Scenario #2</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>consider a system where we have implemented a crawler which feeds the data to the Kafka. we need to get the data from Kafka pipeline and store it to Database.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Scenario #3</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>A User is uploading a huge size of files, we need to store it but, we can't able to store the size after a certain file size limit. what we can do is, implement the stream which reads the data and compresses it. store it in the server.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That's it for this article, Hope you like this series. I am planning to write more articles on this series if I can get a good response from this initiative. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you find this useful, please do share it. <a href="http://eepurl.com/gvbr7j">Subscribe to my newsletter</a> for further updates. Scenario-based Learning - A New Learning Perspective. Node.js - Part 1</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Until then, Happy Coding :-)</p>
<!-- /wp:paragraph -->