<?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: aquibzahidi</title>
    <description>The latest articles on DEV Community by aquibzahidi (@aquibzahidi).</description>
    <link>https://dev.to/aquibzahidi</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%2F550819%2F50644461-0ee8-4801-89eb-9bd833bb0dbc.jpg</url>
      <title>DEV Community: aquibzahidi</title>
      <link>https://dev.to/aquibzahidi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aquibzahidi"/>
    <language>en</language>
    <item>
      <title>Legendary methods of Array in JavaScript | Part 1 : forEach, find, filter and map</title>
      <dc:creator>aquibzahidi</dc:creator>
      <pubDate>Tue, 14 Feb 2023 09:12:36 +0000</pubDate>
      <link>https://dev.to/aquibzahidi/legendary-methods-of-array-in-javascript-part-1-foreach-find-filter-and-map-c1k</link>
      <guid>https://dev.to/aquibzahidi/legendary-methods-of-array-in-javascript-part-1-foreach-find-filter-and-map-c1k</guid>
      <description>&lt;p&gt;ForEach, Filter, Find, Map, Reduce, Some and Every are all JavaScript array methods that are used to manipulate arrays and perform various operations on them. In this blog, we will take a look at what each of these methods does, how they can be used and why they are useful for web developers.&lt;/p&gt;

&lt;p&gt;In this blog I will discuss forEach, find, filter and map.&lt;/p&gt;

&lt;h2&gt;
  
  
  .forEach 🔁
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;forEach&lt;/code&gt; method allows you to iterate over an array and perform a specific operation on each element in the array. It is similar to the &lt;code&gt;for&lt;/code&gt; loop, but it is more concise and easier to use.&lt;/p&gt;

&lt;p&gt;Here’s the syntax for using the &lt;code&gt;forEach&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;array.forEach(function(currentValue, index, arr) {
  // Your code here
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;forEach&lt;/code&gt; method takes a callback function as its argument. This callback function will be called once for each element in the array. The callback function takes three arguments:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;currentValue&lt;/code&gt;: the current element being processed in the array&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;index&lt;/code&gt;: the index of the current element&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;arr&lt;/code&gt;: the array that forEach was called upon&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here’s an example of using the &lt;code&gt;forEach&lt;/code&gt; method to log the name of each product in the &lt;code&gt;products&lt;/code&gt; array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let products = [
  { name: '🍎', inStock: true },
  { name: '🍌', inStock: false },
  { name: '🥕', inStock: true },
  { name: '🍩', inStock: true },
  { name: '🍆', inStock: false }
];

products.forEach(function(product) {
  console.log(product.name);
});

/*
🍎
🍌
🥕
🍩
🍆
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the forEach method is used to iterate over the products array. For each product in the array, the callback function logs the name of the product.&lt;/p&gt;

&lt;h2&gt;
  
  
  .find 🔎
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;find&lt;/code&gt; method is used to find the first element in an array that satisfies a given condition. It takes a callback function as an argument and returns the first element that passes the condition specified in the callback function.&lt;/p&gt;

&lt;p&gt;For example, if you have a 🧑🏻‍💼 list of customers and you want to find the first customer who spent more than $100, you can use the &lt;code&gt;find&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let customers = [
  { name: 'John Doe', orderAmount: 50 },
  { name: 'Jane Doe', orderAmount: 75 },
  { name: 'Jim Smith', orderAmount: 120 },
  { name: 'Jill Smith', orderAmount: 95 },
  { name: 'Jack Johnson', orderAmount: 75 }
];

let highOrderCustomer = customers.find(customer =&amp;gt; customer.orderAmount &amp;gt; 100);
console.log(highOrderCustomer);

/*
{ name: 'Jim Smith', orderAmount: 120 }
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  .filter 🔍
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;filter&lt;/code&gt; method is used to create a new array from an existing array, but with only elements that pass a certain test. This test is defined in a callback function that you provide as an argument.&lt;/p&gt;

&lt;p&gt;Let’s say you have a list of 🎥 movies and you want to create a new list that only includes movies that are rated G. You can use the &lt;code&gt;filter&lt;/code&gt; method to achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let movies = [
  { title: '🐭 The Lion King', rating: 'G' },
  { title: '🦖 Jurassic Park', rating: 'PG-13' },
  { title: '🚀 Space Jam', rating: 'PG' },
  { title: '🏰 Beauty and the Beast', rating: 'G' },
  { title: '🦸‍♂️ Shazam!', rating: 'PG-13' }
];

let kidsMovies = movies.filter(movie =&amp;gt; movie.rating === 'G');
console.log(kidsMovies);

/*
[
  { title: '🐭 The Lion King', rating: 'G' },
  { title: '🏰 Beauty and the Beast', rating: 'G' }
]
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;filter&lt;/code&gt; method iterates through the movies array and checks each movie's rating. If a movie is rated G, it gets included in the kidsMovies array.&lt;/p&gt;

&lt;h2&gt;
  
  
  .map 🔄
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;map&lt;/code&gt; method is used to create a new array from an existing array, by transforming each element in the original array into a new value. The transformation is defined in a callback function that you provide as an argument.&lt;/p&gt;

&lt;p&gt;Example 1: if you have a list of 🔢 numbers and you want to create a new list that contains the square of each number, you can use the &lt;code&gt;map&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(number =&amp;gt; number * number);
console.log(squares);

/*
[1, 4, 9, 16, 25]
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example 2: let’s say you have a list of 🍎 apples and you want to create a new list that shows the weight of each apple in grams. You can use the map method to achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let apples = [
  { type: 'Granny Smith', weight: 150 },
  { type: 'Red Delicious', weight: 120 },
  { type: 'Golden Delicious', weight: 130 },
  { type: 'Fuji', weight: 140 },
  { type: 'Gala', weight: 110 }
];

let appleWeights = apples.map(apple =&amp;gt; apple.weight + 'g');
console.log(appleWeights);

/*
[ '150g', '120g', '130g', '140g', '110g' ]
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;map&lt;/code&gt; method iterates through the apples array and transforms each apple's weight into a string with the units g. The result is a new array called appleWeights that contains the weights of each apple in grams.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Node.js Cluster Module: Scaling Your Applications</title>
      <dc:creator>aquibzahidi</dc:creator>
      <pubDate>Sun, 12 Feb 2023 21:07:32 +0000</pubDate>
      <link>https://dev.to/aquibzahidi/nodejs-cluster-module-scaling-your-applications-4och</link>
      <guid>https://dev.to/aquibzahidi/nodejs-cluster-module-scaling-your-applications-4och</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bLbBsMcc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zaikodu3xvqk8zpjxqnt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bLbBsMcc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zaikodu3xvqk8zpjxqnt.png" alt="Image description" width="638" height="359"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It’s essential to optimize your code to handle a large number of requests and ensure that your application performs optimally. One way to improve the performance of your Node.js application is by using the cluster module.&lt;/p&gt;

&lt;p&gt;In this blog, we’ll discuss what the Node.js cluster module is, how it works, and how you can use it to improve the performance of your applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the Node.js Cluster Module?
&lt;/h2&gt;

&lt;p&gt;The cluster module is a built-in module in Node.js that allows you to run multiple worker processes to handle the load of a single application. It enables you to take advantage of all the CPU cores of your system, resulting in better performance and scalability.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Does the Cluster Module Work?
&lt;/h2&gt;

&lt;p&gt;The cluster module works by forking multiple worker processes from a single master process. Each worker process runs as a separate instance of the application and is responsible for handling requests. The master process is responsible for monitoring the worker processes and forking new ones if necessary.&lt;/p&gt;

&lt;h2&gt;
  
  
  Imprementing Cluster Module with Express
&lt;/h2&gt;

&lt;p&gt;To use the cluster module with Express, you first need to import the necessary modules, including the cluster and express modules. Then, you can create an Express application and specify an endpoint to handle requests. In the endpoint, you can perform a CPU-intensive task to demonstrate the effectiveness of the cluster module.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the cluster module with Express:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cluster = require('cluster');
const express = require('express');
const numCPUs = require('os').cpus().length;
const app = express();

app.get('/', (req, res) =&amp;gt; {

  //cpu intensive task
  for(let i = 0; i &amp;lt; 1e8; i++){
    console.log(i)
  }
  res.send(`Hello World! from ${process.pid}`);
});

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);
  for (let i = 0; i &amp;lt; numCPUs; i++) {
    cluster.fork();
  }
  cluster.on('exit', (worker, code, signal) =&amp;gt; {
    console.log(`worker ${worker.process.pid} died`);
    cluster.fork()
  });
} else {
  app.listen(3000, () =&amp;gt; {
    console.log(`Server Worker ${process.pid} started`);
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;cluster.isMaster&lt;/code&gt; condition checks if the current process is the master process. If it is, the master process forks multiple worker processes using the &lt;code&gt;cluster.fork()&lt;/code&gt; method. If the current process is a worker process, the Express application listens to requests on port 3000.&lt;/p&gt;

&lt;p&gt;The master process also listens for the &lt;code&gt;exit&lt;/code&gt; event, which is emitted when a worker process dies. In this example, if a worker process dies, the master process forks a new one to replace it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Using the Cluster Module
&lt;/h2&gt;

&lt;p&gt;There are several benefits to using the Node.js cluster module, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Improved performance: By forking multiple worker processes, you can take advantage of all the CPU cores of your system, resulting in improved performance.&lt;/li&gt;
&lt;li&gt;Better scalability: By forking new worker processes as necessary, you can handle a large number of requests without sacrificing performance.&lt;/li&gt;
&lt;li&gt;Improved reliability: If a worker process crashes, the master process can automatically fork a new one, ensuring that your application remains available and reliable.&lt;/li&gt;
&lt;li&gt;Easy to implement: The cluster module is a built-in module in Node.js, so you don’t need to install any additional packages. Additionally, it’s straightforward to implement and can be added to your existing applications with minimal changes.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;In Conclusion, The Node.js cluster module is an excellent tool for improving the performance and scalability of your applications. By forking multiple worker processes, you can take advantage of all the CPU cores of your system and handle a large number of requests efficiently. Additionally, the cluster module provides improved reliability by forking new worker processes if a worker process crashes.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>programming</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Optimizing Node.js Performance with Redis Caching</title>
      <dc:creator>aquibzahidi</dc:creator>
      <pubDate>Thu, 26 Jan 2023 05:00:59 +0000</pubDate>
      <link>https://dev.to/aquibzahidi/optimizing-nodejs-performance-with-redis-caching-2olb</link>
      <guid>https://dev.to/aquibzahidi/optimizing-nodejs-performance-with-redis-caching-2olb</guid>
      <description>&lt;p&gt;Caching is necessary in Node.js because it can improve the performance and scalability of a web application. Caching allows frequently accessed data to be stored in a fast, in-memory store, so that it can be quickly retrieved without having to be recalculated or fetched from a slower, persistent storage layer. This can significantly reduce the load on the server, improve response times for users, and make the application more scalable by reducing the need for expensive database queries. Additionally, caching can also help to reduce the amount of data that needs to be transferred over the network, which can help to improve the overall user experience.&lt;br&gt;
One popular tool for implementing caching in Node.js is Redis, an in-memory data store. In this article, we’ll walk through the steps for implementing Redis caching in a Node.js application.&lt;/p&gt;

&lt;p&gt;Step 1: Install Redis server -&lt;br&gt;
Windows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Download the Redis Windows installer from the official website (&lt;a href="https://github.com/microsoftarchive/redis/releases"&gt;https://github.com/microsoftarchive/redis/releases&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Run the installer to install Redis on your system.&lt;/li&gt;
&lt;li&gt;Open the Command Prompt and Run the command redis-cli to start the Redis server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;macOS:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Install Redis using Homebrew by running the command brew install redis.&lt;/li&gt;
&lt;li&gt;Start the Redis server by running the command redis-server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To check if the Redis server is running correctly, type PING in the terminal. The server should respond with PONG, indicating that the server is up and running.&lt;/p&gt;

&lt;p&gt;Step 2: Install Redis Client for node.js&lt;/p&gt;

&lt;p&gt;To use Redis in a Node.js application, we’ll need to install the Redis client for Node.js.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i redis
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 3: Create a Redis client instance&lt;/p&gt;

&lt;p&gt;Next, we’ll create a Redis client instance in our Node.js application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const redis = require("redis");
const client = redis.createClient({
  host: "127.0.0.1",
  port: 6379,
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When creating a Redis client, it’s important to specify the host and port on which the server is running, so that the client can easily connect to the server.&lt;/p&gt;

&lt;p&gt;Step 4: Create middleware to handle caching&lt;/p&gt;

&lt;p&gt;We’ll create a middleware function to handle caching in our Node.js application. This function will check if the requested data is already stored in the cache, and if so, it will return the cached data to the user. If the data is not in the cache, the function will call the next middleware in the chain and store the response in the cache for future requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function cache(req, res, next) {
  const key = "__express__" + req.originalUrl || req.url;

  client.get(key).then(reply =&amp;gt; {

    if (reply) {
      res.send(JSON.parse(reply));
    } else {
      res.sendResponse = res.send;
      res.send = (body) =&amp;gt; {
        //expire in 1 min
        client.set(key, JSON.stringify(body), {'EX':60});
        res.sendResponse(body);
      };
      next();
    }
  }).catch(err=&amp;gt;{
    console.log(err);
    res.status(500).send(err)
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the cache function, we create a key based on the URL, so that we can retrieve and store data according to the URL and send the response. The function also sets a time-to-live (TTL) of one minute for the cached data, after which it will expire and the next request will have to retrieve the data again.&lt;/p&gt;

&lt;p&gt;Step 5: Use the caching&lt;/p&gt;

&lt;p&gt;middleware in your application&lt;br&gt;
To use the caching middleware in our application, we’ll need to add it to the Express middleware stack using the app.use() function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(cache);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 6: Use the cache&lt;/p&gt;

&lt;p&gt;In this example, we’ll use the caching middleware for a simple endpoint that generates a large amount of data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get("/data", (req, res) =&amp;gt; {
  let data = 0;
  for (let i = 1; i &amp;lt; 100000000; i++) {
    data += 1;
  }
  res.json(data);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 7: Connecting redis client with server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.listen(3000, () =&amp;gt; {
  console.log("Server listening on port 3000");
  client.connect().then(()=&amp;gt; {
    console.log('redis is connected')
  })
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Upon initiating the Express server, we established a connection between the Redis client and its corresponding server, ensuring seamless data storage and retrieval.&lt;/p&gt;

&lt;p&gt;Note:&lt;br&gt;
For a detailed, line-by-line implementation, be sure to check out our repository file on &lt;a href="https://github.com/aquibzahidi/Advance-NodeJs/blob/main/performance/redis.js"&gt;Caching in node.js&lt;/a&gt;&lt;br&gt;
For accessing more advance Node.Js topics, visit out repository on &lt;a href="https://github.com/aquibzahidi/Advance-NodeJs"&gt;Advance Node.js.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By implementing Redis caching, you can significantly improve the performance and scalability of your Node.js application. Caching is a powerful tool for reducing server load and improving response times, and Redis is a popular choice for implementing caching in Node.js. By following the steps outlined in this article, you can easily add Redis caching to your Node.js application and start reaping the benefits of improved performance and scalability.&lt;/p&gt;

</description>
      <category>caching</category>
      <category>node</category>
      <category>webdev</category>
      <category>redis</category>
    </item>
  </channel>
</rss>
