Tuesday, December 22, 2020

Node.js Console - REPL

Node.js comes with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript code.

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.

Launch Node.js REPL

You can now test pretty much any Node.js/JavaScript expression in REPL. For example, if your write "10 + 20" then it will display result 30 immediately in new line.

> 10 + 20
30

The + operator also concatenates strings as in browser's JavaScript.

> "Hello " + "World"
Hello World

You can also define variables and perform some operation on them.

> var x = 10, y = 20;
> x + y
30

If you need to write multi line JavaScript expression or function then just press Enter whenever you want to write something in the next line as a continuation of your code. The REPL terminal will display three dots (...), it means you can continue on next line. Write .break to get out of continuity mode.

For example, you can define a function and execute it as shown below.

Node.js Example in REPL

You can execute an external JavaScript file by writing node fileName command. For example, assume that node-example.js is on C drive of your PC with following code.

node-example.js
console.log("Hello World");

Now, you can execute node-exampel.js from command prompt as shown below.

Run External JavaScript file

To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.

Quit from REPL

Thus, you can execute any Node.js/JavaScript code in the node shell (REPL). This will give you a result which is similar to the one you will get in the console of Google Chrome browser.

 Note:
ECMAScript implementation in Node.js and browsers is slightly different. For example, {}+{} is '[object Object][object Object]' in Node.js REPL, whereas the same code is NaN in the Chrome console because of the automatic semicolon insertion feature. However, mostly Node.js REPL and the Chrome/Firefox consoles are similar.

The following table lists important REPL commands.

REPL CommandDescription
.helpDisplay help on all the commands
tab KeysDisplay the list of all commands.
Up/Down KeysSee previous commands applied in REPL.
.save filenameSave current Node REPL session to a file.
.load filenameLoad the specified file in the current Node REPL session.
ctrl + cTerminate the current command.
ctrl + c (twice)Exit from the REPL.
ctrl + dExit from the REPL.
.breakExit from multiline expression.
.clearExit from multiline expression.

Setup Node.js Development Environment

 In this section, you will learn about the tools required and steps to setup development environment to develop a Node.js application.

Node.js development environment can be setup in Windows, Mac, Linux and Solaris. The following tools/SDK are required for developing a Node.js application on any platform.

  1. Node.js
  2. Node Package Manager (NPM)
  3. IDE (Integrated Development Environment) or TextEditor

NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0., so there is no need to install it separately.

Install Node.js on Windows

Visit Node.js official web site https://nodejs.org. It will automatically detect OS and display download link as per your Operating System. For example, it will display following download link for 64 bit Windows OS.

Download Node.JS Installer for Windows

Download node MSI for windows by clicking on 8.11.3 LTS or 10.5.0 Current button. We have used the latest version 10.5.0 for windows through out these tutorials.

After you download the MSI, double-click on it to start the installation as shown below.

Node.js Installation

Click Next to read and accept the License Agreement and then click Install. It will install Node.js quickly on your computer. Finally, click finish to complete the installation.

Verify Installation

Once you install Node.js on your computer, you can verify it by opening the command prompt and typing node -v. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below.

Very Node.js Installation
Verify Node.js Installation
ADVERTISEMENT

Install Node.js on Mac/Linux

Visit Node.js official web site https://nodejs.org/en/download page. Click on the appropriate installer for Mac (.pkg or .tar.gz) or Linux to download the Node.js installer.

Node Environment Setup

Once downloaded, click on the installer to start the Node.js installation wizard. Click on Continue and follow the steps. After successful installation, it will display summary of installation about the location where it installed Node.js and NPM.

Node.js Installation on OS X

After installation, verify the Node.js installation using terminal window and enter the following command. It will display the version number of Node.js installed on your Mac.

$ node -v

Optionally, for Mac or Linux users, you can directly install Node.js from the command line using Homebrew package manager for Mac OS or Linuxbrew package manager for Linux Operating System. For Linux, you will need to install additional dependencies, viz. Ruby version 1.8.6 or higher and GCC version 4.2 or higher before installing node.

$ brew install node

IDE

Node.js application uses JavaScript to develop an application. So, you can use any IDE or texteditor tool that supports JavaScript syntax. However, an IDE that supports auto complete features for Node.js API is recommended e.g. Visual Studio, Sublime text, Eclipse, Aptana etc.

Learn how to setup MS Visual Studio for Node.js development in the next section.

Node.js Process Model

In this section, we will learn about the Node.js process model and understand why we should use Node.js.

Traditional Web Server Model

In the traditional web server model, each request is handled by a dedicated thread from the thread pool. If no thread is available in the thread pool at any point of time then the request waits till the next available thread. Dedicated thread executes a particular request and does not return to thread pool until it completes the execution and returns a response.

traditional web server model
Traditional Web Server Model

Node.js Process Model

Node.js processes user requests differently when compared to a traditional web server model. Node.js runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms. All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request. So, this single thread doesn't have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then it processes the request further and sends the response.

An event loop is constantly watching for the events to be raised for an asynchronous job and executing callback function when the job completes. Internally, Node.js uses libev for the event loop which in turn uses internal C++ thread pool to provide asynchronous I/O.

The following figure illustrates asynchronous web server model using Node.js.

node.js process model
Node.js Process Model

Node.js process model increases the performance and scalability with a few caveats. Node.js is not fit for an application which performs CPU-intensive operations like image processing or other heavy computation work because it takes time to process a request and thereby blocks the single thread.

Node.js Tutorials

 

Node.js is an open-source server side runtime environment built on Chrome's V8 JavaScript engine. 

It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.

Node.js can be used to build different types of applications such as commandline application, web application, real-time chat application, REST API server etc. However, it is mainly used to build network programs like web servers, similar to PHP, Java, or ASP.NET.

How Js Engine work in Client Side






Advantages of Node.js

  1. Node.js is an open-source framework under MIT license. (MIT license is a free software license originating at the Massachusetts Institute of Technology (MIT).)
  2. Uses JavaScript to build entire server side application.
  3. Lightweight framework that includes bare minimum modules. Other modules can be included as per the need of an application.
  4. Asynchronous by default. So it performs faster than other frameworks.
  5. Cross-platform framework that runs on Windows, MAC or Linux




Monday, September 7, 2020

HackerRank :- Sock Merchant solution in c#

 John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are  socks with colors . There is one pair of color  and one of color . There are three odd socks left, one of each color. The number of pairs is .

Function Description

Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.

sockMerchant has the following parameter(s):

  • n: the number of socks in the pile
  • ar: the colors of each sock

Input Format

The first line contains an integer , the number of socks represented in .
The second line contains  space-separated integers describing the colors  of the socks in the pile.

Constraints

  •  where 

Output Format

Return the total number of matching pairs of socks that John can sell.

Sample Input

9
10 20 20 10 10 30 50 10 20

Sample Output

3

Explanation

sock.png

John can match three pairs of socks.

Solution :-

// Complete the sockMerchant function below.
    static int sockMerchant(int n, int[] ar) {
 var result = 0;          
            var dic = new Dictionary<int, int>();

            for (var i = 0; i < ar.Length; i++)
            {
                if (!dic.ContainsKey(ar[i]))
                {
                    var j = i;
                    var value = 0;
                    while (n > j)
                    {
                        if (ar[j] == ar[i])
                            value++;
                        if(ar.Length > j)
                          j++;
                    }
                    dic.Add(ar[i], value);
                }
            }

            if (dic != null)
            {
                foreach(var d in dic)
                {
                    result = result + d.Value/2;
                }
            }
            return result;

    }



Part 7 — Enterprise RAG Reference Architecture

  "Architecture is not about connecting components. It is about defining responsibilities that can evolve independently." Welcome ...