<?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>Forem: Keval Rakholiya</title>
    <description>The latest articles on Forem by Keval Rakholiya (@iserioton).</description>
    <link>https://forem.com/iserioton</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%2F939624%2F898ae215-ade2-4ab2-bf91-57bec81c326c.jpeg</url>
      <title>Forem: Keval Rakholiya</title>
      <link>https://forem.com/iserioton</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/iserioton"/>
    <language>en</language>
    <item>
      <title>Event Driven Programming in Node.js</title>
      <dc:creator>Keval Rakholiya</dc:creator>
      <pubDate>Thu, 23 Feb 2023 11:23:23 +0000</pubDate>
      <link>https://forem.com/iserioton/event-driven-programming-in-nodejs-975</link>
      <guid>https://forem.com/iserioton/event-driven-programming-in-nodejs-975</guid>
      <description>&lt;h2&gt;
  
  
  What is Event-driven programming?
&lt;/h2&gt;

&lt;p&gt;Event-driven programming is a popular paradigm in modern software development that allows developers to write efficient and scalable applications. Node.js is an ideal platform for event-driven programming, as it has a built-in event-driven architecture. In this blog post, we will explore event-driven programming in Node.js and why it is a popular choice for modern web applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding Event-driven Programming
&lt;/h2&gt;

&lt;p&gt;Before we dive into event-driven programming in Node.js, let's first understand the basics of this programming paradigm. In event-driven programming, the flow of the program is determined by events. An event is an occurrence that happens within the program, such as a user input or a change in a variable's value. When an event occurs, the program executes a specific set of instructions that are associated with that event.&lt;/p&gt;

&lt;p&gt;Event-driven programming is often used in applications that require asynchronous processing. In traditional programming models, the program waits for a task to complete before moving on to the next task. However, in event-driven programming, tasks can be executed in parallel, allowing for faster and more efficient processing.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does Node.js enable Event-driven programming?
&lt;/h2&gt;

&lt;p&gt;Node.js is built on top of Google's V8 JavaScript engine and provides a non-blocking I/O model that makes it well-suited for event-driven programming. In Node.js, all I/O operations, such as file system access, network requests, and database queries, are asynchronous and non-blocking, meaning that they do not block the main thread of execution.&lt;/p&gt;

&lt;p&gt;Node.js uses an event-driven architecture to handle asynchronous I/O operations. When a function is called that performs an I/O operation, it registers a callback function to be called when the operation completes. While waiting for the I/O operation to complete, Node.js continues to execute other tasks, such as processing incoming requests or handling other events. Once the I/O operation is complete, Node.js triggers the callback function, passing any relevant data as arguments.&lt;/p&gt;

&lt;p&gt;Node.js provides an event emitter class that can be used to emit and listen for events. An event emitter is an object that emits named events and allows callbacks to be registered for those events. When an event is emitted, all registered callbacks are called synchronously.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why use Event-driven Programming in Node.js?
&lt;/h2&gt;

&lt;p&gt;Node.js is an ideal platform for event-driven programming due to its non-blocking I/O model. This model allows Node.js to handle multiple requests simultaneously without blocking the execution of other requests. This makes Node.js a great choice for building real-time web applications that require fast and responsive processing.&lt;/p&gt;

&lt;p&gt;In Node.js, events are handled using the EventEmitter class. This class allows developers to create custom events and attach event listeners to handle those events. For example, let's say we want to handle a 'click' event on a button in a web application. We can create an event listener for that event using the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const button = document.querySelector('#myButton');

button.addEventListener('click', () =&amp;gt; {
  console.log('Button clicked!');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are attaching an event listener to the 'click' event of a button with the ID 'myButton'. When the button is clicked, the console will log the message 'Button clicked!'. This is just a simple example, but it demonstrates the basic concept of event-driven programming.&lt;/p&gt;

&lt;h2&gt;
  
  
  Building Event-driven Applications in Node.js
&lt;/h2&gt;

&lt;p&gt;Now that we understand the basics of event-driven programming and why it is a popular choice for web applications in Node.js, let's take a look at how we can build event-driven applications in Node.js.&lt;/p&gt;

&lt;p&gt;In Node.js, we can use the EventEmitter class to create custom events and attach event listeners. Let's say we want to create a custom event for a database connection. We can create the event using the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const EventEmitter = require('events');

class Database extends EventEmitter {
  connect() {
    // Connect to the database
    this.emit('connect');
  }
}

const db = new Database();

db.on('connect', () =&amp;gt; {
  console.log('Database connected!');
});

db.connect();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are creating a custom event for a database connection using the EventEmitter class. We then attach an event listener to the 'connect' event and log a message to the console when the event is triggered. Finally, we call the 'connect' method of the Database class, which triggers the 'connect' event and logs the message to the console.&lt;/p&gt;

&lt;p&gt;This is just a simple example, but it demonstrates how we can use event-driven programming in Node.js to create efficient and scalable applications.&lt;/p&gt;

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

&lt;p&gt;In conclusion, event-driven programming is a popular paradigm in modern software development that allows developers to write efficient and scalable applications. Node.js is an ideal platform for event-driven programming, as it has a built-in event-driven architecture that allows for fast and responsive processing. By using the EventEmitter class, developers can create custom events and attach event listeners to handle those events. Node.js is a powerful platform that enables developers to create fast and scalable network applications using event.&lt;/p&gt;

&lt;p&gt;I hope this will help and fulfill your requirements for all the developers who want to achive event deriven programming. This blog is generated by AI. Suggestions are most Welcome. Reach me at &lt;a href="https://github.com/iserioton" rel="noopener noreferrer"&gt;Github&lt;/a&gt;.&lt;/p&gt;




</description>
      <category>githubcopilot</category>
      <category>tooling</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Debouncing in the Javascript</title>
      <dc:creator>Keval Rakholiya</dc:creator>
      <pubDate>Tue, 21 Feb 2023 06:10:40 +0000</pubDate>
      <link>https://forem.com/iserioton/debouncing-in-the-javascript-544n</link>
      <guid>https://forem.com/iserioton/debouncing-in-the-javascript-544n</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this post, I'll explain how to achieve denounce of the actions in javascript. We will use a timer and callback functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisite
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Good knowledge of &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout" rel="noopener noreferrer"&gt;setTimeout&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function" rel="noopener noreferrer"&gt;Callbacks&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why Does it Matter?
&lt;/h2&gt;

&lt;p&gt;Improving speed and performance is a big challenge these days. Users are getting more modern and everyone wants to be done their tasks quickly. To improve the speed of the web pages we are optimizing the javascript of the web. Here is one more solution to improve the performance of the web page by implementing the debounce on the events.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the hack is Debounce?
&lt;/h2&gt;

&lt;p&gt;In computer engineering, the Debounce is a pattern or a programming approach where the program collects similar events from the inputs and reacts to only the last event in a given period of time. By this, the program doesn't need to react for every event and because of this it may save memory and improve CPU efficiency.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's understand the problem!
&lt;/h2&gt;

&lt;p&gt;Let's assume, we have a function called runme that makes an API call and calculates a ton of data in the backend. We have a button that triggers the runme function on the click event. Now if the user clicks three times on the button back to back the runme will call and execute three times which is unnecessary. To overcome this problem we use Debouncer.&lt;/p&gt;

&lt;p&gt;Now we will solve the above problem with the example. It's time to walk through the example for better understanding, Let's GOOO...&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const debouncer = (fn, time) =&amp;gt; {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(fn.bind({}, ...args), time);
    };
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above function takes two arguments, the first one is the function of which we want to make a bouncer function and the second argument is the delay time in ms. And the function returns a new function that will execute after a certain time period.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Runme without Debounce
function runme(temp) {
    console.log(temp);
}
replicaOfRunme(1);
replicaOfRunme(2);
replicaOfRunme(3);
/**
 * O/P: 1 2 3
 */

// Runme with Debounce
let replicaOfRunme = debouncer(runme, 2000);
replicaOfRunme(1);
replicaOfRunme(2);
replicaOfRunme(3);
/**
 * O/P: 1
 */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this will help and fulfill your requirements for all the developers who want to add Debounce to events. Suggestions are most Welcome. Reach me at &lt;a href="https://github.com/iserioton" rel="noopener noreferrer"&gt;Github&lt;/a&gt;.&lt;/p&gt;




</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>How to override XHR/fetch method in Javascript?</title>
      <dc:creator>Keval Rakholiya</dc:creator>
      <pubDate>Sun, 09 Oct 2022 07:18:28 +0000</pubDate>
      <link>https://forem.com/iserioton/how-to-override-xhrfetch-method-in-javascript-g44</link>
      <guid>https://forem.com/iserioton/how-to-override-xhrfetch-method-in-javascript-g44</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this post, I'll explain how to override XHR or fetch requests in javascript. We will use a Proxy object of javascript to add hooks in XHR or fetch requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisite
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Good knowledge of &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest"&gt;XMLHttpRequest&lt;/a&gt; and &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"&gt;Fetch request&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"&gt;Proxy&lt;/a&gt; object in javascript&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function"&gt;Callbacks&lt;/a&gt; and &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"&gt;Promise&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why Does it Matter?
&lt;/h2&gt;

&lt;p&gt;Sometimes when we are working with API requests on the front side. And we face a scenario like we want to send data to all requests or we want to filter all the response data. Or when we are working with a third-party website, for example, We are a third-party app for the Shopify store. On the front side, we want to display a popup when the product is added to the cart by the user. We can add a hook in API calls and monitor the activities of the customer.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to override XHR/fetch method in Javascript?
&lt;/h2&gt;

&lt;p&gt;We are going to use &lt;strong&gt;Proxy object&lt;/strong&gt; of javascript. &lt;br&gt;
The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Override XMLHttpRequest&lt;/strong&gt;&lt;br&gt;
XMLHttpRequest(XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XHR is a class base object. Here is the snippet for adding a hook in XHR.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;XMLHttpRequest = new Proxy(XMLHttpRequest, {
      construct: function (target, args) {
        const xhr = new target(...args);
        // Do whatever you want with XHR request
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 1) {
            // Before sent request to server
            xhr.setRequestHeader("Authorization", "XXXX-XXXX-XXXX-XXXX");
          }
          if (xhr.readyState === 4) {
            // After complition of XHR request 
            if (xhr.status === 401) {
              alert("Session expired, please reload the page!");
            }
          }
        };
        return xhr;
      },
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we created a new copy of XHR with our code and re-assigned it to the XHR. We added a new header to all the requests which will be submitted from our page. We can check the response data also when the XHR is completed. We successfully injected our code into XHR request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Override fetch API request&lt;/strong&gt;&lt;br&gt;
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. Fetch is a function base object. Here is the snippet for adding a hook in the fetch request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.fetch = new Proxy(window.fetch, {
      apply: function (target, that, args) {
        // args holds argument of fetch function
        // Do whatever you want with fetch request
        let temp = target.apply(that, args);
        temp.then((res) =&amp;gt; {
          // After completion of request
          if (res.status === 401) {
            alert("Session expired, please reload the page!");
          }
        });
        return temp;
      },
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above fetch example, we created a copy of the fetch using a proxy and re-assigned it to the original fetch request. apply property of proxy takes a function as a value. The passed function will execute whenever fetch will calls. We have our hook in fetch request. We can add a custom header we can add/update or delete the payload of the request. After the successful completion of the API, we can filter the response header, and we can add/update, or delete response data.&lt;/p&gt;

&lt;p&gt;I hope this will help and fulfill your requirements for all the developers who want to add hooks to API calls. Suggestions are most Wellcome. Reach me at &lt;a href="https://github.com/iserioton"&gt;Github&lt;/a&gt;.&lt;/p&gt;




</description>
      <category>javascript</category>
      <category>ajax</category>
      <category>fetch</category>
      <category>xmlhttprequest</category>
    </item>
  </channel>
</rss>
