Friday, January 8, 2021

Improve NodeJS Performance using Cluster and PM2

NodeJS is single thread, meaning a request must be completed before it can execute another request. This example demonstrates how inefficient in NodeJS: https://github.com/htsiah/node-performance-using-cluster/tree/main/blocking-the-event-loop

To improve the performance, we can implement cluster where you can fork as many as child processes. The rule of thumb is the child can not more than logical CPU. You can download the cluster implementation here. https://github.com/htsiah/node-performance-using-cluster/tree/main/cluster-in-action

This article explains the number of child process and thread vs the logical CPU: https://dev.to/johnjardincodes/increase-node-js-performance-with-libuv-thread-pool-5h10

PM2 is a NodeJS cluster package. This package used in many production environments. I recommend  PM2 instead of reinventing the wheel. The above example is to let you understand how the cluster works.

First, you need to install PM in the global environment by using the command: npm install -g pm2

To start the application using pm2: pm2 start app.js -i -1 (-1 is maximum child process.)

To show all the process: pm2 list

To delete the process: pm2 delete app

More refer to https://www.npmjs.com/package/pm2

Thursday, November 26, 2020

Install NodeJS using Version Manager

Often Node.js can be installed with a particular Operating System's official or unofficial package manager. For instance apt-get on Debian/Ubuntu, Brew on macOs, Chocolatey on Windows. It is strongly recommended against using this approach to install Node. Package managers tend to lag behind the faster Node.js release cycle. Additionally, the placement of binary and config files and folders isn't standardized across OS package managers and can cause compatibility issues.

The popular version manager are nvm (macOS and Linux), nvm-windows (windows) and nvs (macOS, Linux and windows).

    https://github.com/nvm-sh/nvm

    https://github.com/coreybutler/nvm-windows

    https://github.com/jasongin/nvs

I prefer nvs because of cross-platform. I am a window user and my server is Ubuntu.

Comparing nvm and nvs, I have feedback from a developer saying that nvm is slower.


Wednesday, December 25, 2019

Deploying React App to Netlify

Typically we deploy ours react app locally. Now I am going to show you how to publish your react app to the internet.

You can use either Surge or Netlify. My preference is Netlify because whenever you update the source in Github, it automatically updates the internet site.

First, you need to create an account at Netlify and link your account to Github. At the dashboard, click on the "New site from git" button.

At the "Create a new site" page, click on GitHub. Select the repos you wish to publish.


Fill the setting. For react app, the setting will automatically be filled. Click on "Deployed site" once done.



Netlify will pull the source from Github and publish the site. An url will be generated as well.

My react todo application: https://laughing-snyder-9e6b8c.netlify.com/

References:

Tuesday, December 24, 2019

What is your first VS Code plugin?

Prettier enforces a consistent code style.



Other favourite plugins:

  1. Bracket Pair Colorizer
  2. Indent Rainbow
  3. Auto Rename Tag
What is your first VS Code plugin? Comment below.

Sunday, December 8, 2019

Quick Sort in Javascript

Quick sort is faster than bubble sort.

It uses the idea of divide and conquers. Divides the array into two halves using a pivot in such a way that elements in the left half are smaller than the pivot and elements in the right are greater than the pivot — then recursive using quick sort on the left and right parts.

I would recommend below youtube to understand Quick Sort:
https://www.youtube.com/watch?v=eqo2LxRADhU

Here is my implementation in javascript:
function quickSort(arr, start, end) {
  // Stop the recursion when the start equal or smaller to the end
  if (start >= end) { 
    return ; 
  };
  
  // Here is the magic happen
  let pivotIndex = partition(arr, start, end);
  
  // Recursion - quick sort the left part
  quickSort(arr, start, pivotIndex - 1);
  
  // Recursion - quick sort the right part
  quickSort(arr, pivotIndex + 1, end);
}

function partition (arr, start, end) {
  let pivotIndex = start; // Pivot location
  let pivotValue = arr[end]; // Use the last number  
  
  for (let i=start; i<end; i++) {
    // Move number that smaller than pivot value to the front.
    // Update pivot index
    if (arr[i] < pivotValue) {
      // Move to front
      swap(arr, i, pivotIndex);
      pivotIndex++;
    }
  }
  
  // Swap the pivot value to correct location
  swap(arr, end, pivotIndex);
  return pivotIndex;
}

function swap(arr, a, b) {
  let temp = arr[a];
  arr[a] = arr[b];
  arr[b] = temp;
}

let arr = [2 ,1, 4, 5, 3, 6, 6, 8, 1, 3];
quickSort(arr, 0, arr.length - 1);

Thursday, December 5, 2019

Bubble Sort in Javascript

Bubble soft is the most straightforward sorting algorithm that works by repeatedly swapping the elements if they are in wrong orders.

Example:

1. Swapping the first element.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

2. Swapping the second element.
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), No swap
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap

3. Pass the sorting criteris when there is no swapping.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap

Let write the code to do it:

let items = [1,2,3,5,4];

function bubbleSort(p_val){
  let sorted = p_val;
  
  for (let i=0, x=p_val.length; i<=x; i++){
      let isSwapRequired = false;
      for(let j=0; j<=x-i-1; j++){
        // compare items and only swap them if the second one's smaller
        if (sorted[j] > sorted[j+1]) {
          isSwapRequired = true;
          let first = sorted[j];
          let second = sorted[j+1];
          sorted[j+1] = first;
          sorted[j] = second
        }
    }
    // IF no two elements were swapped by inner loop, then break 
        if (!isSwapRequired) { break; };
  }
  
  return sorted;
}

document.write(bubbleSort(items));
The best case is when the array is already sorted, and worst case is the array is reverse sorted.

So that is the famous bubble sort. I will talk on other sorting algorithms next time.

Notes: There is a native javascript method to sort an array (Array.sort) that is more efficient and easier to use. This example is to demonstrate the bubble sort.

Wednesday, December 4, 2019

Recursion in Javascript

A recursive function is the ability to call itself and stop on matching the criteria.

For example, we could write a recursion to reverse a string from "ABC" to "CBA".

// Parameter: A string.
// Return: Last character of the string.

function reverseString(p_val){

  // Get the string's length
  var length = p_val.length;

  // Get the last character
  var lastchar = p_val.charAt(length - 1);

  if (length == 1) {

     // Return the last char
     return lastchar;

  } else {

    // Run the recursion
    return lastchar + reverseString(p_val.substring(0,length - 1))

  }

}

Let's say the parameter is "ABC". The process will be:
  1. Return: C + reverseString("AB") 
  2. Return: C + B + reverseString("A") 
  3. Return: C + B + A