Search

How to Install Angular 10 on MacOS

Angular 10 is the latest version in the Angular family. Angular applications are basically designed for Single Page Applications (SPAs), where all controls are required in single page architecture. Angular is an application-based design framework, which provides the Cross-Platform development environment for creating the most sophisticated SPAs. These SPAs are efficient enough for giving us a component to view the model environment, making it an MVC or MVVM application. Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App like experience with high-performance. Angular has zero-step installation, making its up- gradation using modern web capabilities possible, even if offline. Angular has the capability of making cross platform Desktop Apps. These can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP and many other servers by giving the output in HTML-CSS format. This even optimizes the App for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command Line tools, we can build and deploy apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests, making the applications made in Angular more stable. Introduction:In this Article we are going to talk about how to install Angular 10 in MAC OS.  We will be covering the following contents:  Pre-requisites The Pre-requisites for installation Download and Install Node.js The Download Site Address  Instructions to Install Node.js Test Installation of Node.js Install Angular CLI How Node.js helps in installing Angular CLI Testing the installation of Angular CLI Create New Angular Application A Basic Hello-World Application in Angular  Serve Angular Application Running the Hello-World Application Check the Output Check the Browser for the Output Conclusion  Pre-requisites: Mentioned below are the pre-requisites for the installation of Angular in MAC OS. The Pre-requisites are: MAC OS->10.10 plus installed in your PC At least 4 GB RAM A Hard drive memory of 10 GB free Administrator account for installing software in MAC OS or User account with privilege to install and unrestricted access to all related websites for Node.js and Angular. Download and Install Node.js Node.js is an open-source software which is used to run JavaScript code outside a browser. Node.js is cross-platform making it suitable for major operating systems. It helps developers to use JavaScript in Network Applications, Command Line Tools, normal Web Applications, Web APIs, and more. It provides Dev Tooling local Web Server for live reloading and development experience. Thus, Node.js is an Open-Source Server environment that allows developers to run JavaScript on the server. So, before installing Angular 10, we need to install Node.js in the System. Download Node.js Open the following site in the browser. (Download the Node.js source code or a pre-built installer for your platform, and start developing today). We get the site as follows: Download the LTS version of the software with the latest features. This gives us three versions for different operating systems: Windows Installer (.msi) :  32-bit (node-v14.15.0-x86.msi) 64-bit (node-v14.15.0-x64.msi) Windows Binary (.zip) 32-bit (node-v14.15.0-x86.zip) 64-bit (node-v14.15.0-x64.zip) macOS Installer (.pkg) 64-bit (node-v14.15.0.pkg) macOS Binary (.tar.gz) 64-bit (node-v14.15.0-darwin-x64.tar.gz) Linux Binaries (x64) 64-bit (node-v14.15.0-linux-x64.tar.xz) Linux Binaries (ARM) ARMv7 (node-v14.15.0-linux-armv7l.tar.xz) ARMv8 (node-v14.15.0-linux-arm64.tar.xz) Source Code node-v14.15.0.tar.gz SmartOS Binaries 64-bit (node-v14.15.0-sunos-x64.tar.xz) Docker Image Official Node.js Docker Image  Linux on Power LE Systems 64-bit (node-v14.15.0-linux-ppc64le.tar.xz) Linux on System z 64-bit (node-v14.15.0-linux-s390x.tar.xz) AIX on Power Systems 64-bit (node-v14.15.0-aix-ppc64.tar.gz) Download the macOS Installer (.pkg) : 64-bit (node-v14.15.0.pkg). This is the latest version of Node installable package. Install the .pkg in your operating system by clicking on the installer.  Once clicked, the .pkg file opens the installer wizard. Click on continue to move to the next page. Click on continue to continue to the next page with License Terms and Conditions.   You will be asked to accept the license, please do so by clicking on Agree, after reading the terms and conditions. Click on Continue to move to the next page.  Once you have clicked on continue, you will get the install now page:  Click on Install, and enter the login credentials, the username and password, and then click on Install Software:  Once successfully installed, Node.js shows the following summary of the installation:  Click on Close to close the wizard. Set the /usr/local/bin in your $PATH so that you can access the node and npm executable files. To verify the same open the terminal and type: Echo $PATH Test Installation of Node.js Once the package is installed, open the Terminal and type the following command: node –v You will get the version of Node.js displayed. v14.15.0 and  npm –v You get the version of npm displayed. 6.4.1 Install Angular CLI Angular CLI has a wide range of commands for Angular Applications. It helps us in managing, testing, and building Angular applications. Once Node.js is installed in our system, we can use npm to install software globally on our system. Use –g option in the npm command to install the Angular CLI tool globally. Once done so it will be accessible to all users and applications on the mac OS system.  To install Angular CLI with the Node.js npm tool, use the following command: $ sudo npm install -g @angular/cli This command will install the latest Angular CLI version available at Angular site on your macOS system.  If you require other than the latest version of Angular, then use the following command in your mac OS: For Angular 6: $ npm install -g @angular/cli@6#Angular 6 For Angular 7: $ npm install -g @angular/cli@7         #Angular 7 For Angular 8: $ npm install -g @angular/cli@8         #Angular 8 For Angular 9: $ npm install -g @angular/cli@9         #Angular 9 Testing the installation of Angular CLI Once the installation is successful, Angular CLI will provide a command ng to be used for command line operations.  Type the following command to check the version of Angular CLI: $ ng --version   Or $ ng version And we should get the following output: This completes your Angular installation. Now let us make a “Hello World” Application in Angular. Following section describes how to make a basic application in Angular. Create New Angular Application Create a folder for your application in the desired location on your system and open it on your favorite file browser.  A Basic Hello-World Application in Angular  Open a new terminal and move to your folder created for the application and type in the following command to create your app folder using ng create command as below.  $ ng create hello-world Or $ ng new hello-world For the Query “Would you like to add Angular Routing?” type Yes. For the Query “Which style sheet format would you like to choose?” move your cursor to point to “CSS” and click enter. Then it would take some time for further installation of the application folder, so we need to have patience in this respect. At last, when the command is executed successfully, Angular creates a skeleton application under the folder. It also includes a bunch of files and other important necessities for the application. Serve Angular Application Once our Hello-World project is created change the current directory to project directory by cd command and run application using ng serve command as shown below: $ cd hello-world  $ ng serve We can leave the ng serve command running in the terminal as it will automatically refresh the browser each time we make and save changes in our Angular application. This makes Angular development quick and iterative. Running the Hello-World Application Once run, you can access your Angular application on localhost port 4200, which is the default host and port used by any Angular application. To get the output, type in your favorite browser, address bar the following: http://localhostž4200 If another application is running on that address, you can simply run the command. $ ng serve--port It will generate a different port for you to navigate to through the web browser.  Check the Output Typically, the browser looks something like this: ConclusionThrough Angular 10 we can develop very dynamic applications. However, sometimes we may require to undo the installation of Angular CLI. We can uninstall angular cli through command terminal by using the npm tool. Run the following command in the terminal to Uninstall Angular: $ npm uninstall -g @angular/cli Angular applications are still SPAs or Single Page Applications in their Core. The loading of the Application is still triggered by a main request to the server. The command ng serve helps us to serve this request every time we make changes to our scripts. As our HTML or JavaScript changes, so does the new server request, sending the new changed response to the web browser. 

How to Install Angular 10 on MacOS

6K
How to Install Angular 10 on MacOS

Angular 10 is the latest version in the Angular family. Angular applications are basically designed for Single Page Applications (SPAs), where all controls are required in single page architecture. Angular is an application-based design framework, which provides the Cross-Platform development environment for creating the most sophisticated SPAs. These SPAs are efficient enough for giving us a component to view the model environment, making it an MVC or MVVM application. 

Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App like experience with high-performance. Angular has zero-step installation, making its up- gradation using modern web capabilities possible, even if offline. Angular has the capability of making cross platform Desktop Apps. These can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP and many other servers by giving the output in HTML-CSS format. This even optimizes the App for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command Line tools, we can build and deploy apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests, making the applications made in Angular more stable. 

Introduction:

In this Article we are going to talk about how to install Angular 10 in MAC OS.  We will be covering the following contents:  

  • Pre-requisites 
    • The Pre-requisites for installation 
  • Download and Install Node.js 
    • The Download Site Address  
    • Instructions to Install Node.js 
  • Test Installation of Node.js 
  • Install Angular CLI 
    • How Node.js helps in installing Angular CLI 
  • Testing the installation of Angular CLI 
  • Create New Angular Application 
    • A Basic Hello-World Application in Angular  
  • Serve Angular Application 
    • Running the Hello-World Application 
  • Check the Output 
    • Check the Browser for the Output 
  • Conclusion  

Pre-requisites: 

Mentioned below are the pre-requisites for the installation of Angular in MAC OS. 

The Pre-requisites are: 

  1. MAC OS->10.10 plus installed in your PC 
  2. At least 4 GB RAM 
  3. A Hard drive memory of 10 GB free 
  4. Administrator account for installing software in MAC OS or User account with privilege to install and unrestricted access to all related websites for Node.js and Angular. 

Download and Install Node.js 

Node.js is an open-source software which is used to run JavaScript code outside a browser. Node.js is cross-platform making it suitable for major operating systems. It helps developers to use JavaScript in Network Applications, Command Line Tools, normal Web Applications, Web APIs, and more. It provides Dev Tooling local Web Server for live reloading and development experience. 

Thus, Node.js is an Open-Source Server environment that allows developers to run JavaScript on the server. 

So, before installing Angular 10, we need to install Node.js in the System. 

Download Node.js 

Open the following site in the browser. 

(Download the Node.js source code or a pre-built installer for your platform, and start developing today). We get the site as follows: 

How to Install Angular 10 on MacOSDownload the LTS version of the software with the latest features. 

This gives us three versions for different operating systems: 

  • Windows Installer (.msi) :  
    • 32-bit (node-v14.15.0-x86.msi) 
    • 64-bit (node-v14.15.0-x64.msi) 
  • Windows Binary (.zip) 
    • 32-bit (node-v14.15.0-x86.zip) 
    • 64-bit (node-v14.15.0-x64.zip) 
  • macOS Installer (.pkg) 
    • 64-bit (node-v14.15.0.pkg) 
  • macOS Binary (.tar.gz) 
    • 64-bit (node-v14.15.0-darwin-x64.tar.gz) 
  • Linux Binaries (x64) 
    • 64-bit (node-v14.15.0-linux-x64.tar.xz) 
  • Linux Binaries (ARM) 
    • ARMv7 (node-v14.15.0-linux-armv7l.tar.xz) 
    • ARMv8 (node-v14.15.0-linux-arm64.tar.xz) 
  • Source Code 
    • node-v14.15.0.tar.gz 
  • SmartOS Binaries 
    • 64-bit (node-v14.15.0-sunos-x64.tar.xz) 
  • Docker Image 
    • Official Node.js Docker Image  
  • Linux on Power LE Systems 
    • 64-bit (node-v14.15.0-linux-ppc64le.tar.xz) 
  • Linux on System z 
    • 64-bit (node-v14.15.0-linux-s390x.tar.xz) 
  • AIX on Power Systems 
    • 64-bit (node-v14.15.0-aix-ppc64.tar.gz) 

Download the macOS Installer (.pkg) : 64-bit (node-v14.15.0.pkg). This is the latest version of Node installable package. 

Install the .pkg in your operating system by clicking on the installer.  Once clicked, the .pkg file opens the installer wizard. Click on continue to move to the next page. 

How to Install Angular 10 on MacOSClick on continue to continue to the next page with License Terms and Conditions.   

How to Install Angular 10 on MacOS

You will be asked to accept the license, please do so by clicking on Agree, after reading the terms and conditions. 

How to Install Angular 10 on MacOS

Click on Continue to move to the next page.  

How to Install Angular 10 on MacOS

Once you have clicked on continue, you will get the install now page:  

How to Install Angular 10 on MacOS

Click on Install, and enter the login credentials, the username and password, and then click on Install Software:  

How to Install Angular 10 on MacOS

Once successfully installed, Node.js shows the following summary of the installation:  How to Install Angular 10 on MacOS

Click on Close to close the wizard. 

Set the /usr/local/bin in your $PATH so that you can access the node and npm executable files. To verify the same open the terminal and type: 

Echo $PATH 

Test Installation of Node.js 

Once the package is installedopen the Terminal and type the following command: 

node –v 

You will get the version of Node.js displayed. 

v14.15.0 

and  

npm –v 

You get the version of npm displayed. 

6.4.1 

Install Angular CLI 

Angular CLI has a wide range of commands for Angular Applications. It helps us in managing, testing, and building Angular applications. 

Once Node.js is installed in our system, we can use npm to install software globally on our system. Use –g option in the npm command to install the Angular CLI tool globally. Once done so it will be accessible to all users and applications on the mac OS system.  

To install Angular CLI with the Node.js npm tool, use the following command: 

sudo npm install -g @angular/cli 

This command will install the latest Angular CLI version available at Angular site on your macOS system.  

If you require other than the latest version of Angular, then use the following command in your mac OS: 

For Angular 6: 

$ npm install -g @angular/cli@6#Angular 6 

For Angular 7: 

$ npm install -g @angular/cli@7         #Angular 7 

For Angular 8: 

$ npm install -g @angular/cli@8         #Angular 8 

For Angular 9: 

$ npm install -g @angular/cli@9         #Angular 9 

Testing the installation of Angular CLI 

Once the installation is successful, Angular CLI will provide a command ng to be used for command line operations.  

Type the following command to check the version of Angular CLI: 

$ ng --version   

Or 

$ ng version 

And we should get the following output: 

How to Install Angular 10 on MacOS

This completes your Angular installation. Now let us make a “Hello World” Application in Angular. Following section describes how to make a basic application in Angular. 

Create New Angular Application 

Create a folder for your application in the desired location on your system and open it on your favorite file browser 

A Basic Hello-World Application in Angular  

Open a new terminal and move to your folder created for the application and type in the following command to create your app folder using ng create command as below.  

ng create hello-world 

Or 

$ ng new hello-world 

For the Query “Would you like to add Angular Routing?” type Yes. 

For the Query “Which style sheet format would you like to choose?” move your cursor to point to “CSS” and click enter. 

Then it would take some time for further installation of the application folder, so we need to have patience in this respect. 

At last, when the command is executed successfully, Angular creates a skeleton application under the folder. It also includes a bunch of files and other important necessities for the application. 

Serve Angular Application 

Once our Hello-World project is created change the current directory to project directory by cd command and run application using ng serve command as shown below: 

cd hello-world 
ng serve 

We can leave the ng serve command running in the terminal as it will automatically refresh the browser each time we make and save changes in our Angular application. This makes Angular development quick and iterative. 

Running the Hello-World Application 

Once run, you can access your Angular application on localhost port 4200, which is the default host and port used by any Angular application. To get the output, type in your favorite browser, address bar the following: 

http://localhostž4200 

If another application is running on that address, you can simply run the command. 

ng serve--port 

It will generate a different port for you to navigate to through the web browser 

Check the Output 

Typically, the browser looks something like this: 

How to Install Angular 10 on MacOS

Conclusion

Through Angular 10 we can develop very dynamic applications. 

However, sometimes we may require to undo the installation of Angular CLI. 

We can uninstall angular cli through command terminal by using the npm tool. Run the following command in the terminal to Uninstall Angular: 

npm uninstall -g @angular/cli 

Angular applications are still SPAs or Single Page Applications in their Core. The loading of the Application is still triggered by a main request to the server. The command ng serve helps us to serve this request every time we make changes to our scripts. As our HTML or JavaScript changes, so does the new server request, sending the new changed response to the web browser. 

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

What are React Component Lifecycle Methods

React is the most popular JavaScript library used to create interactive UI for web applications. It is a component-based library where different parts of a webpage can be encapsulated by components which are quite easy to create, manage and update. React allows us to create Single Page Applications which maintain the state of individual components on an app without having to reload it.  What are React Components? Developers who are new to JavaScript libraries and frameworks like React and Angular might ask the question, “What is a component?” Well, in very simple words, a component is a unit of code which includes JavaScript and HTML to build a part of a web page. It acts like a custom HTML element. It is reusable and can be as complex as you want it to be. For example, imagine that you are creating a very basic application with header, footer, and body. The header can be a component; the footer can be another component and the body can be yet another one or even might consist of multiple components.One of the most useful characteristics of React is its ability to integrate reusable components in a project. Reusability is the characteristic of a component which allows it to be used again, thereby reducing the amount of code a developer has to write. In our example here, the header can be a reusable component and can be used on all the pages of the application, which makes it easy to maintain and update. What does a component look like? Here is a simple example of a react component which contains a simple form. This is a class-based component. React also supports function-based components. As you can see in the code below, App is a user-defined class which inherit from React’s Component class and it has a render method which returns HTML code. As the name suggests, the render method returns and renders HTML to our browser. Every component has to return HTML which is rendered to the user’s browser by render method.import React, { Component } from 'react';  class App extends Component {    handleChange(event) {      this.setState({value: event.target.value});    }    render() {      return (                              Username:                                            Password:                                              );    }  }    export default App; In the above example, we have created a login form where there are 2 input boxes for the user to enter their username and password and then submit the form. We have assigned an event handler to form which will handle the login event in component.We have exported our component (using export default App) so that it can be rendered inside other components.This is a very basic example of component, but this can be as complex as you want it to be. But it is always advised to make your component independent and it should represent only a part of your page which can be reusable as well. It can return complex HTML included with JavaScript to handle complex features in your application.Component as a class React allows us to create component in the form of class as well as functions. While creating component as class you need to define a class which extends React.Component class. Component class has many features which the deriving class can use to maintain the state throughout the lifecycle. In case you want to have more custom features, you can create your own base component class which derives from Component class, and then your component classes can derive from your base component class. What do we mean by Component Lifecycle?Lifecycle of a component is the set of different stages (also known as lifecycle hooks) a component goes through while it is active. Stages could be when a component is created or when any changes are made to the component and many others. There are different methods executed by React at different points of time between when a component is created and at the end when it is destroyed and not in use. One such hook or method we have already seen in the code above, which is render(), and it is executed by React to render the component. We can override these methods and perform certain tasks in those methods, but every lifecycle serves a different purpose and it can be a nightmare if we ask them to do something that they aren’t supposed to or are not very good at. As a developer we should be aware of what those different stages are, what happens in those stages, in what order they execute and how we can make the best use of it. Understanding the lifecycle of components also helps us predict behavior of a component at different stages, which makes it easier to work with them. Managing a large set of components in an application can get you in trouble if you do not know how they work behind the scenes.Props and State Before we start with lifecycle hooks, lets understand what props and state are as they are most commonly used properties in component classes. Props It is a keyword which means properties. Props are used by callers of components to pass properties to the called component in a uni-directional flow. For example, if Parent component renders child component, it can define props and pass them to the child component which is then available and accessible by this.props. Another thing to note here is that props is a ready-only attribute which means data which is passed by parent should not be changed by client components. State State is a plan JavaScript object which defines the current state of any component. It is user defined and can be changed by lifecycle hooks. Ideally state should contain only data which is going to be rendered on DOM. State has getter and setter methods this.getState() and this.setState() which as the names suggest are used to access and update State. It is good practice to use setState method to update State and treat State as an immutable JavaScript object.Since there are many lifecycle hooks a component goes through, it would easier to understand if we start with the hooks which are executed when a component is created.Lifecycle hooks while Mounting [These lifecycle hooks are executed in order as listed, when a component is created]constructor(props) This is not a component lifecycle hook, but it is important to mention here and to be aware that Constructor is executed before it is mounted. Constructor receives props(properties of a component) as an argument which then can be passed to base class using super keyword if we define the constructor.  It is not mandatory to define constructor in component class, but if you do to perform any logic, then you need to call base constructor using super keyword.  Mainly constructors are used: To Setup local state of component with this.state To bind event handler methods. This is what a simple constructor would look like.import React, { Component } from 'react';  class App extends Component {    constructor(props) {      super(props);      this.state = { value: 0 };      this.handleClick = this.handleClick.bind(this);    }  } this.state should be called only inside constructor, to update the state in other methods use this.setState() method.  If constructor is required to do any heavy tasks, it will impact the performance of component, and you should be aware of this fact.  getDerivedStateFromProps(props, state) After constructor, this lifecycle hook is called before render method is executed. It is called while mounting as well as whenever props have changed. This is not very commonly used, only in cases where props can change, and you need to update state of the component. This is the only use case where you should implement this lifecycle hook.This method is executed on every render and cannot access component instance.import React, { Component } from 'react';  class App extends Component {    getDerivedStateFromProps(props, state) {      if (props.value !== state.prevValue) {        return {          prevValue: props.value        };      }      return null;    }    }render() This is the method which is required to be implemented in component class. It can access props and state. This is where you can write your html and jsx code. You can also render child components in this method which will then be rendered as well. Before completing the lifecycle of parent, lifecycle of all child components will be finished. All this html and jsx is then converted to pure html and outputs in DOM. JSX is a JavaScript extension which creates React elements. It looks more like template language but it is empowered by JavaScript which allows it to do a lot more. It can embed expressions . JSX has different set of attributes than what we have in html. For example, while creating html using JSX you need to use attribute “className” instead of class. This is what a typical render method looks like:import React, { Component } from 'react';   class App extends Component {   render() {         return (        Click to go Home { this.state.home }       Go to Home         );   } } Alternatively you can also use React.createElement() method to create html using JSX.const element = React.createElement(       'h1',       {className: 'hello'},       'Hello, world!'     );componentDidMount() As the name suggests, componentDidMount() is invoked after the component is mounted, which means html has been added to DOM tree. It is a very commonly used lifecycle hook, as it allows you to do a lot of things including causing side-effects, setting up any subscriptions, or loading data from external endpoints. If you setup any subscription using this method, make sure to unsubscribe them in componentWillUnmount() lifecycle hook. You shouldn’t update state in this method using this.State() as it may cause performance issues. For assigning initial state you should use constructor(). import React, { Component } from 'react';  class App extends Component {    componentDidMount(){    // Component is rendered and now external calls can be made.      this.getDataAfterTimeOut();    }    getDataAfterTimeOut(){      setTimeout(() => {        this.setState({          data: 'Data is fetched'        })      }, 1000)    }  } Lifecycle hooks while Updating [Next set of lifecycle hooks are executed while a component is updating which can be caused by changes to props(properties) or state of component. These are invoked in order as listed below.] getDerivedStateFromProps(props, state) We have already talked about this. This is invoked every time a component is changed or updated. Any changes in properties or state which causes the component to be changed will invoke this method. shouldComponentUpdate(nextProps, nextState) shouldComponentUpdate() is invoked before rendering (not on initial rendering) but only when props or state has been changed. Even though it is not recommended you can use this lifecycle hook to control the re-rendering. This can lead to performance issues as well as bugs, so be careful while doing that.  In this method nextProps can be compared with this.props and nextState can be compared with this.state. This method can return true or false depending on whether you want to continue rendering by skipping the next lifecycle hooks. In either case it can’t prevent re-rendering of child components. Note that this method defaults to true which will not skip rendering and next lifecycle hooks and continue with execution. import React, { Component } from 'react';  class App extends Component {    shouldComponentUpdate(nextProps, nextState) {  // This value will determine if lifecycle execution is to be skipped or continued.      return nextProps.value != this.props.value;    }  } render() After shouldComponentUpdate lifecycle hook render is called, which we have already talked about, it prepares html and jsx code which then outputs to DOM. getSnapshotBeforeUpdate() getSnapshotBeforeUpdate() is invoked right before the recent changes are added to DOM. This lifecycle hook gives us an opportunity to capture any details we need from the DOM before it is updated with new content. For example, if you want to know the scrolling position of the user, which should be restored after the DOM has changed. Use cases for this lifecycle, while rare, can be of great value at times. The snapshot value which is captured and returned by this hook is passed as a parameter to another lifecycle hook componentDidUpdate() which we will talk about next. import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate (prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      if (this.state.value != prevState.value) {        return table.scrollHeight - table.scrollTop      }      return null    }  }componentDIdUpdate(prevProps, prevState, snapshot) componentDidUpdate is invoked when DOM is updated. It is only called on update, not on initial rendering. You can use this method to make data requests after checking if props have changed. You can also call setSatate() in this method, but make sure to wrap that in a condition else it will cause an infinite loop forcing re-rendering and affecting performance issues. Also it should be noted that value for snapshot will only be available if you have implemented getSnapshotBeforeUpdate() in your component; else value for snapshot will be undefined. Here is an example of componentDidUpdate. This is a very basic example where we have captured snapshot by implementing get Snapshot Before Update lifecycle hook. After that componentDidUpdate is invoked and content is overwritten with new dataimport React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } UnMounting [This is where lifecycle of a component ends when component is destroyed and removed from DOM. While Unmounting React gives us an opportunity to do something before component is destroyed, it can include clearing objects which have occupied memory to avoid memory leaks.] componentWillUnMount() componentWIllUnMount() is executed right after component is unmounted which means it is removed from DOM and destroyed. But before it is removed and destroyed, React gives us an opportunity to perform any cleanup we want to. For example, you might have setup subscriptions initially in componentDidMount() which you should unsubscribe when component is destroyed to avoid memory leaks in your application. You can also remove event listeners which were subscribed before. In this lifecycle hooks you should not update state of your component because component is not going to re-render now.import React, { Component } from 'react';  class App extends Component {    componentWillUnmount() {  // Component will be removed from DOM now.        // Unscubscribe subscriptions and events here.  document.removeEventListener("click", this.handleSubmit);    }  }Conclusion In this article we talked about React, its components and its different lifecycles. It is very crucial to understand the different opportunities that React provides through these lifecycle methods. There are many rules we need to follow while working with these hooks. Making them do something they can’t handle can cause performance issues or even infinite loops at times.  These lifecycle hooks work with props and state which are the most used properties of component class. Changes in state and props trigger different lifecycle hooks and even re-render the dom which is something you should be aware of. These lifecycle hooks are provided to intercept the different stages a component goes through and make the best use of it, but without understanding how they work it can break your application by causing performance issues or memory leaks. Hope this has been helpful. 
9271
What are React Component Lifecycle Methods

React is the most popular JavaScript library us... Read More

What are the Pros and Cons of React

If you are a web developer, you are a JavaScript developer--by choice or by force. I mention by force because not many web developers like to work with vanilla JavaScript, especially ones who have worked with frameworks and languages where Object Oriented concepts are made easier for developers to work with. But this does not stop JavaScript from becoming the most widely used language in the world. The popularity of JavaScript has been growing rapidly over the past years.  For any web development, a lot of the work gets done by JavaScript at the user’s browser and at times it becomes difficult to manage vanilla JavaScript in large applications as it lacks the structure which developers enjoy in languages like Java, C# at the back end. Technology leaders identified this problem, and they came up with multiple solutions to make JavaScript not just easier to work with but also to give it performance boost and empowering browsers to do lot more without having to worry about managing complex state of applications as they grow to meet customer demand. React is one such solution along with Angular and Vue. What is React JS? ReactJS is a component-based JavaScript library created by Facebook. React makes it easier to create interactive UI using components and efficiently manage states of those components. Multiple components can be composed together to make complex applications without losing their state in DOM.  Even though we are talking about React as a tool for web application here, it can also be used for mobile application development with React Native, a powerful and open-source native library for mobile application. This is how a simple React component looks like. class HelloWorld extends React.Component {    render() {      return (                  Hello world!              );    }  } What can we build using React JS? Being one of the most popular JavaScript libraries, React can be used to create anything you see on the web. It can be used for multiple requirements; be it a simple but interactive app like Instagram, or a complex streaming app with large userbase and support for multiple languages and regions like Netflix or an application like Facebook, with very large dataset and high complexity with the power to process more than a billion users’ requests parallelly. However, it is not just limited to highly scalable web applications, and you can also create mobile applications using React Native which is an open-source mobile application framework. You can create Android, iOS and Windows apps using this framework. In fact, the above-mentioned web applications “Instagram, Facebook, Netflix” mobile apps are also created using React Native. It gives developers a rich library to utilize the native features of a device to deliver high performance and highly interactive applications to users across the world. Pros 1. Component based architectureIt is not uncommon for vanilla JavaScript based apps to get into a stage, when managing state of data at user’s browser becomes a headache for developers. As the data and complexity of an application grow, it becomes difficult to maintain using vanilla JavaScript. The introduction of React components brings a highly sophisticated unit of a web page which can be independently created, maintained, and even reused. You can divide your web page into multiple components, and they can work independently. You can update one of them without having to worry about changes in others. This makes it very loosely coupled and at the same time available for working together by merging with other components to bring out the best of the web application’s abilities. This is not something unique in React library. In fact, components are the basic building blocks in the Angular framework as well, and a similar concept has been there in many MVC frameworks since a long time. 2. High PerformanceWith component-based architecture, React allows to create highly scaled Single Page Application or SPA, in which content is dynamically loaded during user interaction without loading the entire page. However, this can turn into a trap. Imagine having to update DOM for every change caused by user’s interaction on web page. Every action might force DOM (which is a tree structure) to refresh itself. And if your web page is complex, having multiple UI components this can cause massive performance blockage. To solve this, React uses the concept of Virtual DOM, which you can think of as a copy of your real DOM. Now all the changes caused by user’s interaction or other events are handled by the virtual DOM first, and only if it (the intelligence of React) thinks it is important enough to refresh the real DOM, the real DOM is refreshed. This saves us from massively repeating recreation of the DOM tree for every trivial change resulting in high performance application.3. ReduxBack to our SPA (Single Page Application), where there are multiple components sitting on one page and updated dynamically without reloading the entire page. Now all this sounds very simple and smooth. Which it is, until your components start talking to each other. Let’s say you have a web page where there are few form components which contains large forms with lot of controls, few table components, and a sidebar and header, footer. Content in tables must be updated when user submits form or part of forms. Also, you might want to update header when a new record is created. Now here, our table components have dependency on form components. These dependencies, along with communication between them can grow as your application grows. All this can make our data unstable as there is no way to know which data is latest or which is correct. There is no single source of data. This can cause poor user experience and also performance issues. To make sure that all your components are in sync with latest data, we need to have a--let’s just call it-- a ‘manager’ who manages our data, and provides a single trustworthy source which makes sure the data which the components have is correct and truthful. This manager and its team are known as Redux in React.  Redux forces components to avoid talking to each other directly or being dependent on each other, instead components send their data to redux and it is the responsibility of redux to update the components (which need those data) with new data. This way components are always updated with the latest data available without having to depend on each other.4. Easy to LearnThis is another pro of working with React as any developer with understanding of html and JavaScript can start learning React. Unlike other JS frameworks like Angular which introduce a lot of new terminologies, React uses most of what is already available. This makes it very easy to start with--another reason why it has grown to be the most popular JS library.  It provides more flexibility (which it derives from Vanilla JavaScript) and does not force developers to follow any specific pattern like MVC or any other architectural pattern. Development teams are free to choose their own style or patterns while working with an application. This allows vanilla JavaScript developers to work with component-based architecture without having to lose the freedom they enjoyed with vanilla JavaScript. 5. Mobile App DevelopmentIn a world where every platform, and every stack of an application requires you to learn a whole new tool or language or frameworks; React brings us the flexibility of using the same library over web and mobile applications. React Native allows us to create mobile applications on any mobile platform with the same React concepts and syntaxes. React Native helps you create interactive and high-performance mobile apps for any mobile device without having to learn a new tool or language. So far, we talked about what makes React so popular among development teams, but every technology has pros and cons. Let’s talk about why many teams are not willing to work with React and what makes it less reliable when you need a well-structured and stable JS library to work with. Cons  1. High Pace of DevelopmentThis is arguably the most discussed con of using React. React is not just a rapidly growing library, it is also rapidly changing, which forces its developers to update the way they write code. Now this is obviously annoying for most of the developers who are not comfortable with adopting new ways every Monday they start or the ones who are working on an application where changes are critical to customers. There are many industries which are critical to change where customers look for more stable tools and technologies. But this again depends on how expert team members are and if they can convince their customers to trust them with React.  2. Flexibility and Lack of ConventionsYes, you read it right. I know that we discussed it as an advantage of using React, but at the same time it is also a disadvantage in a broader sense. Libraries, languages, or frameworks have their global standards of how developers work with them, and what styles or patterns they follow. This is useful because when developers change teams, they have an idea of what patterns or styles the new team might be following; whereas among React development teams it is not easy to predict what styles or standards a team might follow, making it harder for new developers to work with new teams and their standards. Developers who have worked with frameworks which follow a fixed structure and set of conventions might not find React very attractive to work with. 3. Not a full-featured frameworkEven though React is a rich JavaScript library with a set of interactive and useful features required for creating large scale applications, developers do not enjoy what they can have in a fully featured framework such as Angular (another popular JS Framework). If you look at the MVC (Model View Controller) architecture, React only handles the view part. For Controller and Model you need additional libraries, and tools. This can result in poor structure of code, and its patterns. Whereas frameworks like Angular provide the complete MVC featured ground, which is more structured, and well managed.  This all sounds like jQuery again. When we talk about empowering JavaScript to structure like we do our code at backend, arguably you might be looking for a full featured, well-structured tool where similar practices and patterns are followed globally, and this is where React might not be very helpful. If not careful, you might end up having the same problem which React claims to resolve. It needs a quite deeper understanding of JavaScript and its core behaviors to make React work the way you want it to. Whereas working with Frameworks like Angular (although it is more difficult to learn than React) force developers to follow a strict structure where you enjoy similar patterns as backend development.4. Poor DocumentationSince React is changing so fast, new tools and patterns are adding up every now and then, and it is becoming difficult for the community to maintain the documentation. This makes it difficult to work with for new developers who want to start with React. Lack of poor documentation can also result in slower development among teams with less experienced developers. 5. JSXReact has introduced JSX to work with html, and JavaScript. This is like JavaScript and html syntax, and allows to mix html and JavaScript together but has some new attributes and syntaxes, which makes it difficult to work with when you start with React. For example, while working with class attribute, in JSX it becomes className. Also, the lack of rich documentation makes it more difficult to work with JSX.  This is what a JSX looks like while creating a simple login form.      Header {this.state.content}      Enter your username:          Enter your password:            6. SEO HandlingIf you are building an application in React which is SEO (Search Engine Optimization) sensitive where the popularity of your application, its appearance and ranking in Google search results are priorities, then this, although not proven, is a concern. The concern is about ability of search engine crawlers to list dynamically loaded content. There are tools available to test your app for SEO results and rankings.Pros from Developer’s Perspective Easy to Learn: The biggest advantage that React has from the developer’s perspective, which is also the reason behind React getting more popular than other JavaScript libraries and frameworks, is that it is very easy to begin with. Anyone with basic understanding of HTML and JavaScript can quickly get started with React. Even though it has JSX to mix JavaScript and HTML together which is bit unconventional, it hasn’t stopped React from becoming the most loved JavaScript library among developers.  Structural Flexibility Unlike other conventional frameworks, React doesn’t draw boundaries on how a developer should treat code. This gives React developers freedom to express their own architectural styles to build apps. Developers who like to work with vanilla JavaScript love this flexibility as they are not used to the idea of a framework controlling the structure of code in an application. Pros from Business Owner’s Perspective One framework for all Platforms Most of the technology stacks force the use of different tools, language or frameworks for web and mobile app development. This requires business owners to hire developers of different skill sets for web and mobile app development, increasing the cost of app development and maintenance in the long run. With React, the easier learning curve allows a React web developer to quickly start with React Native, which is a mobile development framework based on React. This reduces the cost of hiring developers of multiple skill sets and also reduces the cost of maintenance, as the same technology is being used at both the platforms. Rapid Development Time is another significant factor when it comes to software development, as it directly impacts the cost of project development. React is easy to get started with, and has the structural flexibility that allows developers to do rapid application development, reducing both the time and cost of software development. This not only applies to web but mobile development as well. There are many businesses who had to choose between web and mobile apps while in their initial phases because of time and cost constraints. React has been able to give the confidence to start with mobile and web app development simultaneously, allowing them to reach a lot more customers than they would have had if they had to choose between web and mobile. Conclusion Honestly, there is no solid conclusion on whether these pros or cons can be summed up to decide if you should or should not go with React. It entirely depends on customer needs, domain needs and expertise in your team. With the right team of experts React can be implemented at its best, overcoming its cons like “rapid change or lack of documentation and lack of convention”. A team of expert developers can agree to follow a convention, document the practices and patterns they are following for any future developers who might join their team. With all these covered, React has a number of advantages including “Hight performance using Virtual DOM, State Management using Redux”, which you can use to make the best of web and mobile apps available today.
5818
What are the Pros and Cons of React

If you are a web developer, you are a JavaScript... Read More

What is query string in Node.js?

In this article, we will look into query string module in Node.js, and understand a few methods to deal with query string. The available methods can be used to convert query string into a JSON object and convert a JSON object into query string.What is Query StringA query string according to Wikipedia is a part of the uniform resource locator (URL), that assigns values to specified parameters. In plain English it is the string after the ? in a url. Some url examples are shown below.https://example.com/over/there?name=ferret https://example.com/path/to/page?name=ferret&color=purpleThe query string in first case is name=ferret and in second case is name=ferret&color=purpleNode.js Query string moduleNow, the Node.js query string module provides methods for parsing and formatting URL query strings. The query string module can be accessed using the below –const querystring = require(‘querystring’)We will now look into the below six methods in the next section.querystring.decode()querystring.encode()querystring.escape(str)querystring.parse(str[, sep[, eq[, options]]])querystring.stringify(obj[, sep[, eq[, options]]])querystring.unescape(str)Query String methods with descriptionLet us look into a real example to understand the important Query string methods. Let us setup a basic Node application by giving the command npm init -y in terminal, inside a folder. I had created an empty NodeJS folder for the same.$ npm init -y Wrote to D:\NodeJS\package.json: {   "name": "NodeJS",   "version": "1.0.0",   "description": "",   "main": "index.js",   "scripts": {     "test": "echo \"Error: no test specified\" && exit 1"   },   "keywords": [],   "author": "",   "license": "ISC" }The above commands create a basic package.json file, which is the basis of any Node.js project. We are using the -y option, so that we don’t have to enter the details manually.Next, open the folder in a code editor which is VSCode in my case. Here, I have created a file querystring.js and the first line contains the importing of querystring module.querystring.parse() MethodThe querystring.parse() method is used to parse the URL query string into an object that contains the key value pair. The object which we get is not a JavaScript object, so we cannot use Object methods like obj.toString, or obj.hasOwnProperty().The latest UTF-8 encoding format is assumed unless we specify a different encoding format. But we should stick to UTF-8 encoding as it is the standard and contains all international characters like the Chinese characters and the hindi characters. After that also if we need alternative character encoding, then the decodeURIComponent option should be used.The syntax for the method is below.querystring.parse( str[, sep[, eq[, options]]]) )As seen from the above syntax the method accepts four parameters, and they are described below.str: This is the only required string field and it specifies the query string that has to be parsed.sep: It is an optional string field, which if given specifies the substring used to delimit the key and value pairs in the query string. The default value which is generally used is “&”.eq: It is an optional string field that specifies the substring used to delimit keys and values in the query string. The default value which is generally used is “=”.options: It is an optional object field which is used to modify the behaviour of the method. It can have the following parameters:decodeURIComponent: It is a function that would be used to specify the encoding format in the query string. The default value is querystring.unescape(), about which we will learn later.maxKeys: It is the number which specifies the maximum number of keys that should be parsed. A value of “0” would remove all the counting limits, and it can parse any number of keys. The default value is set at “1000”.The below example shows the various options used in querystring.parse() method. Add the below code in querystring.js file, which we created earlier.// Import the querystring module const querystring = require("querystring");   // Specify the URL query string to be parsed   let urlQueryString = "name=nabendu&units=kgs&units=pounds&login=false";   // Use the parse() method on the string   let parsedObj = querystring.parse(urlQueryString);   console.log("Parsed Query 1:", parsedObj);   // Use the parse() method on the string with sep as `&&` and eq as `-` urlQueryString = "name-nabendu&&units-kgs&&units-pounds&&login-true"; parsedObj = querystring.parse(urlQueryString, "&&", "-");   console.log("\nParsed Query 2:", parsedObj); // Specify a new URL query string to be parsed   urlQueryString = "type=admin&articles=java&articles=javascript&articles=kotlin&access=true"; // Use the parse() method on the string with maxKeys set to 1   parsedObj = querystring.parse(urlQueryString, "&", "=", { maxKeys: 1 });   console.log("\nParsed Query 3:", parsedObj);   // Use the parse() method on the string with maxKeys set to 2   parsedObj =  querystring.parse(urlQueryString, "&", "=", { maxKeys: 2 });   console.log("\nParsed Query 4:", parsedObj); // Use the parse() method on the string with maxKeys set to 0 (no limits) parsedObj = querystring.parse(urlQueryString, "&", "=", { maxKeys: 0 }); console.log("\nParsed Query 5:", parsedObj);Now, run the command node querystring.js from the Integrated terminal in VSCode or any terminal. Note that you need to be inside the folder NodeJS, which we had created earlier. The output of the same will be below.Parsed Query 1: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'false' } Parsed Query 2: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'true' } Parsed Query 3: [Object: null prototype] { type: 'admin' } Parsed Query 4: [Object: null prototype] { type: 'admin', articles: 'java' } Parsed Query 5: [Object: null prototype] {   type: 'admin',   articles: [ 'java', 'javascript', 'kotlin' ],   access: 'true' }querystring.stringify() MethodThe querystring.stringify() method is used to produce a query string from a given object, which contains a key value pair. It is exactly the opposite of querystring.parse() Method.It can be used to convert the string, numbers and Boolean values for the key. You can also use an array of string, numbers or Boolean as values. This method of changing an object to query string is called serialized.The latest UTF-8 encoding format is assumed unless we specify a different encoding format. But we should stick to UTF-8 encoding as it is the standard and contains all international characters like the Chinese characters and the Hindi characters. If we still need an alternative character encoding, then the decodeURIComponent option should be used.Syntax for the method is below.querystring. stringify( obj[, sep[, eq[, options]]]) )As from the above syntax the method accepts four parameters, and they are described below.obj: This is the only required object field and it specifies the object that has to be serialized.sep: It is an optional string field, which if given specifies the substring used to delimit the key and value pairs in the query string. The default value which is generally used is “&”.eq: It is an optional string field that specifies the substring used to delimit keys and values in the query string. The default value which is generally used is “=”.options: It is an optional object field which is used to modify the behaviour of the method. It can have the following parameters:decodeURIComponent: It is a function that would be used to specify the encoding format in the query string. The default value is querystring.escape(), about which we will learn later.The below example shows the various options used in querystring.stringify() method. Add the below code in querystring.js file, which we created earlier.// Import the querystring module   const querystring = require("querystring");   // Specify the object that needed to be serialized   let obj = {   name: "nabendu",   access: true,   role: ["developer", "architect", "manager"],   };   // Use the stringify() method on the object   let queryString = querystring.stringify(obj);   console.log("Query String 1:", queryString);   obj = {       name: "Parag",       access: false,       role: ["editor", "HR"],   };   // Use the stringify() method on the object with sep as `, ` and eq as `:` queryString = querystring.stringify(obj, ", ", ":");   console.log("Query String 2:", queryString);   // Use the stringify() method on the object with sep as `&&&` and eq as `==`   queryString = querystring.stringify(obj, "&&&", "==");   console.log("\nQuery String 3:", queryString);Now, run the command node querystring.js from the Integrated terminal in VSCode or any terminal. Note that you need to be inside the folder NodeJS, which we had created earlier. The output of the same will be below.Query String 1: name=nabendu&access=true&role=developer&role=architect&role=managerQuery String 2: name:Parag, access:false, role:editor, role:HR        Query String 3: name==Parag&&&access==false&&&role==editor&&&role==HRquerystring.decode() MethodThe querystring.decode() method is nothing but an alias for querystring.parse() method. In our parse example, we can use it. So, add the below code in querystring.js file, which we created earlier.// Import the querystring module const querystring = require("querystring");   // Specify the URL query string to be parsed   let urlQueryString = "name=nabendu&units=kgs&units=pounds&login=false";   // Use the parse() method on the string   let parsedObj = querystring.decode(urlQueryString); console.log("Parsed Query 1:", parsedObj);As earlier, run the command node querystring.js from a terminal. And the output will be same as that with querystring.parse() method.Parsed Query 1: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'false' }querystring.encode() MethodThe querystring.encode() method is nothing but an alias for querystring.stringify() method. In our stringify example, we can use it. So, add the below code in querystring.js file, which we created earlier.// Import the querystring module   const querystring = require("querystring");   // Specify the object that needed to be serialized let obj = { name: "nabendu", access: true,   role: ["developer", "architect", "manager"],   };   // Use the stringify() method on the object   let queryString = querystring.encode(obj);   console.log("Query String 1:", queryString);As earlier run the command node querystring.js from a terminal. And the output will be same as that with querystring.stringify() method.Query String 1: name=nabendu&access=true&role=developer&role=architect&role=managerquerystring.escape(str) MethodThe querystring.escape() method is used by querystring.stringify() method and is generally not used directly.querystring.unescape(str) MethodThe querystring.unescape() method is used by querystring.parse() method and is generally not used directly. SummaryIn this article we learnt about the useful query string module in Node.js, which is mainly used to parse URL query strings into Object format and also to change an object to URL query strings.
3465
What is query string in Node.js?

In this article, we will look into query string mo... Read More