Search

Web Development blog posts

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 (        <form onSubmit={this.handleSubmit}>          <label>            Username:            <input type="text" value={this.state.username} onChange={this.handleChange} />          </label>          <label>            Password:            <input type="password" value={this.state.password} onChange={this.handleChange} />          </label>          <input type="submit" value="Submit" />        </form>      );    }  }    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 <img src={value}  />. 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 ( <div>       <h1 > Click to go Home { this.state.home }</h1>       <button type="button" onClick = { this.redirectToHome } >Go to Home     </button>     </div>);   } } 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. 
What are React Component Lifecycle Methods
Dheeraj

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 the Use of DNS Module in Node.Js?

Node.js gives the provision of using different modules. In this article, we will look into the use of DNS module in Node.  What is DNS and its importance?DNS stands for Domain Name System. The main function of the DNS is to translate the IP Address, which is a numerical label assigned to your computer. IP addresses can be thought of as names of computers on a network and are used to distinguish different devices and their locations.  For example, 8.8.8.8 is one of the many public IP addresses of Google.com. So, DNS can be considered as phonebook of the Internet. When we type any address like www.example.com in our browser, that request is sent to the Name Server which converts it to an IP Address(like 12.34.56.78). This is then sent to the respective server for further processing. The figure below shows how exactly this happens. Syntax The syntax for including the DNS module in our node application is – const dns = require(‘dns’) DNS methods and its descriptionsWe will look into a real example and some important DNS 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 dns.js and the first line contains the code for importing the dns module.1. lookup()Next, we will call the dns lookup function, which takes two arguments. The first is the domain we want to lookup, which can be anything and is knowledgehut.com in our case. The second is the callback or function that we want to run, once the lookup is complete. The function that runs on completion takes two arguments. The first argument contains an error, if one occurs, and the second is the value or the IP address of the domain. So, inside our function if we have an error we are printing it in the console and returning, which means no further code will run. If we don’t have an error, we are printing the value. Add the below code in a dns.js file.const dns = require('dns');  dns.lookup('knowledgehut.com', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) To run this, I am opening the Integrated terminal, which comes in VSCode by pressing Ctrl+J on Windows or Cmd+J on Mac. Here, give the command node dns to run our file dns.js. The output of the same is below. 54.147.15.161When we run this program, we are not getting any error and getting the IP address of the domain name. 2. resolve()The function resolve() is pretty much identical to the lookup() function. Our code remains the same and we have only changed the lookup to resolve. Add the below code in a dns.js file.const dns = require('dns');  dns.resolve('knowledgehut.com', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) We can get the output by running node dns command from terminal.[ '34.236.195.104',   '50.16.1.247',       '54.147.15.161',     '3.223.64.88' ]But as we can see from the output, we got all the IP addresses associated with this domain.The resolve function actually goes and makes a network request to the DNS system, to see how many IP addresses are registered with that domain name. The lookup function actually just uses the computer’s internal mechanism first to see if there is an IP address that it can return without having to do a network request. So, resolve function is more accurate and should be used in production as it gives all the IP addresses associated with the domain. You can also provide another argument to the resolve function to specify what type of record you want to look up. For example, with the DNS system you can find the Mail exchange record of the domain. This record handles the request, when you send an email to the domain, and specifies which server should handle the request.So, in our code we will add MX as the second argument. Add the below code in a dns.js file.const dns = require('dns'); dns.resolve('knowledgehut.com', 'MX', (err, value) => {     if(err) {         console.log(err);         return;     }     console.log(value); })On running the node dns command from the Integrated Terminal again, we are getting the information of the Mail exchange of that domain in an array.[ { exchange: 'mail.knowledgehut.com', priority: 0 } ]  3. reverse() Now, we will look into the reverse function. It works exactly the same as lookup() and resolve(), but instead of supplying a domain name, we are supplying an IP address. This function goes into the DNS system, to find out if there are any reverse records associated with this IP address. We are using 8.8.8.8, which is the publicly available IP address for Google. Add the below code in a dns.js file. const dns = require('dns');  dns.reverse('8.8.8.8', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) On running the node dns again, we will get the reverse record within an array. [ 'dns.google' ]  4. lookUp Service() This can be used to get the information of host, which includes the hostname and the service. We need to provide a valid IP address and a valid Port as arguments. It uses the Operating Systems getnameinfo to get this data. If the IP address or the Port are not valid, a TypeError will be thrown.   In our example, we are providing a known IP address along with the port 587. This port is used for Mail Exchange(MX).  Then we are console logging the host and service. Add the below code in a dns.js file. const dns = require('dns'); dns.lookupService('34.236.195.104', 587, (err, host, service) => {     if(err) {         console.log(err);         return;     }     console.log(host,'\n', service); })It is shown in console on running node dns in Integrated Terminal.ec2-34-236-195-104.compute-1.amazonaws.com    5875. resolve4()The resolve4 method is almost similar to the resolve() method. It also returns an array of IP addresses, but only the IPv4 addresses and not the newer IPv6 addresses. Still most of the websites use IPv4 address and this function will give a valid output. Add the below code in a dns.js file.const dns = require('dns');  dns.resolve4('knowledgehut.com', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) It is shown in console on running node dns in Integrated Terminal. [ '50.16.1.247',       '54.147.15.161',     '34.236.195.104',    '3.223.64.88' ] 6. resolve6()The IPv4 is a 32 bit address, developed in the 90s. But since there are only 4 billion addresses, the world ran out and they were all used up. So, IPv6 was invented and since then many websites have this new IPv6 address. The resolve6() method internal mechanism is also like the resolve() method, but it only returns array of IPv6 addresses. Add the below code in a dns.js file.const dns = require('dns'); dns.resolve6('nodejs.org', (err, value) => {     if(err) {         console.log(err);         return;     }     console.log(value); }) It is shown in console on running node dns in Integrated Terminal.[ '2606:4700:8d75:a0e6:9d7:10c:f52a:f808' ]7. resolveMx()The resolveMx() method is used to get the Mail exchange records for a hostname. The Mail exchange records are also known as MX records. We need to pass the hostname as argument and we will receive the details in an array, if the request was successful. Add the below code in a dns.js file.const dns = require('dns'); dns.resolveMx('nodejs.org', (err, value) => {     if(err) {         console.log(err);         return;     }     console.log(value); })It is shown in console on running node dns in Integrated Terminal.  [ { exchange: 'aspmx.l.google.com', priority: 10 },         { exchange: 'alt1.aspmx.l.google.com', priority: 20 },    { exchange: 'alt2.aspmx.l.google.com', priority: 20 },    { exchange: 'aspmx2.googlemail.com', priority: 30 },      { exchange: 'aspmx3.googlemail.com', priority: 30 } ] 8. resolveNs() The resolveNs() method is used to get the Name Server(NS records) information of a hostname. The hostname is passed as argument and we receive the information back in an array. Add the below code in a dns.js file. const dns = require('dns');  dns.resolveNs('nodejs.org', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) It is shown in console on running node dns in Integrated Terminal. [ 'pablo.ns.cloudflare.com', 'meera.ns.cloudflare.com' ] 9. resolveSoa() The resolveSoa() method is used to get the Start of Authority record(SOA record) for a given hostname. The SOA records contain a lot of important information about the hostname like Name Server, Host Master, Expiry time. The hostname is passed as argument, and we receive all the information in an object. Add the below code in a dns.js file. const dns = require('dns');  dns.resolveSoa('nodejs.org', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) It is shown in console on running node dns in Integrated Terminal. { nsname: 'meera.ns.cloudflare.com',    hostmaster: 'dns.cloudflare.com',     serial: 2035938779,    refresh: 10000,    retry: 2400,    expire: 604800,    minttl: 3600 } 10. resolveTxt() The resolveTxt() method is used to get the txt queries(TXT records) for a given hostname. The TXT records were actually intended to put human-readable notes in DNS, by the domain administrator. But nowadays, it is also used to prevent email spam.  In the resolveTxt() method the hostname is passed as argument, but we receive the output as a two-dimensional array of text records available for that hostname. Add the below code in a dns.js file.const dns = require('dns');  dns.resolveTxt('nodejs.org', (err, value) => {      if(err) {          console.log(err);          return;      }      console.log(value);  }) The output is shown in console on running node dns in Integrated Terminal. [ [ 'v=spf1 include:aspmx.googlemail.com -all' ] ] 11. resolvePtr() The resolvePtr() method is used to get the pointer records(PTR records) for a given hostname. Now, a PTR record maps an IP address to a domain and is also called “reverse DNS entry”. It is used to convert an IP address to a domain name. This is mainly used as a security and anti-spam measure. 12. resolveNaptr() The resolveNaptr() method is used to get the Naming Authority Pointer records(NAPTR records) for a given hostname. The NAPTR records are newer type of DNS records, in which we can write in regular expressions. The NAPTR records are mostly used in applications, which support Internet Telephony. The resolveNaptr() method is useful to know, whether a domain supports SIP or some other VoIP(Voice Over IP) services. 13. resolveSrv() The resolveSrv() method is used to get the service records(SRV records) for a given hostname. The service records specify the host and port for specific services on a server like voice over IP(VoIP), instant messaging and other services. 14. setServers() The setServers() is a very important method, which is used to set the IP address and port of servers. The argument to this method, is an array of formatted array. Example for the same is below. dns.setServers([    '4.4.4.4',    '[2001:4860:4860::8888]',    '4.4.4.4:1053',    '[2001:4860:4860::8888]:1053'  ]); 15. getServers() The getServers() method of DNS is used to get all the IP addresses associated with a server. It returns the IP addresses, belonging to the server in an array. DNS promises API The dns.promises API returns promise objects, instead of the callbacks which we have seen earlier. So, they are more modern as most of the JavaScript community is moving towards promises, instead of callbacks. We need to access the promises API by using require(‘dns’).promises Almost all the methods that are in dns are also available in DNS promises API. The complete list is below. resolver.getServers() resolver.resolve() resolver.resolve4() resolver.resolve6() resolver.resolveAny() resolver.resolveCaa() resolver.resolveCname() resolver.resolveMx() resolver.resolveNaptr() resolver.resolveNs() resolver.resolvePtr() resolver.resolveSoa() resolver.resolveSrv() resolver.resolveTxt() resolver.reverse() resolver.setServers() We will look into some of the examples, along with syntaxes. 16. resolver.resolve4() This method takes the hostname as argument. On success the Promise is resolved with an array of IPv4 addresses. In the below example, we are using a different import, than our previous section.  Since, the resolver.resolve4() returns a promise we can use the modern syntax of ‘then and catch’ block. The .then is executed if the Promise resolves to success and the .error is executed if the Promise fails. Add the below code in a dns.js file. const { Resolver } = require('dns').promises;  const resolver = new Resolver();  resolver.resolve4('geeksforgeeks.org')      .then(addresses => console.log(addresses))      .catch(err => console.log(err)) The output is shown in console on running node dns in Integrated Terminal. In the case of success, we get an array with IPv4 addresses as in our case. [ '34.218.62.116' ]  17. resolver.resolveMx() This method takes the hostname as argument. On success the Promise is resolved with an array of Mail exchange(MX records) records.  In the below example, we are using the latest async-await format for the Promise. Add the below code in a dns.js file. const { Resolver } = require('dns').promises;  const resolver = new Resolver();  (async function() {      const addresses = await resolver.resolveMx('nodejs.org');      console.log(addresses)  })() The output is shown in console on running node dns in Integrated Terminal. [ { exchange: 'alt1.aspmx.l.google.com', priority: 20 },    { exchange: 'alt2.aspmx.l.google.com', priority: 20 },    { exchange: 'aspmx2.googlemail.com', priority: 30 },      { exchange: 'aspmx3.googlemail.com', priority: 30 },      { exchange: 'aspmx.l.google.com', priority: 10 } ]18. resolver.getServers() The resolver.getServers() method returns an array of IP addresses. We can use it as below, where we are first getting the IPv6 address, by using the resolve6() method. Once, we receive it we are using it inside the .then block and it will return all the IP addresses of the server. Add the below code in a dns.js file. const { Resolver } = require('dns').promises;  const resolver = new Resolver();  resolver.resolve6('nodejs.org')      .then(addresses => {          console.log('IPv6 is ', addresses);          console.log('Server address is ', resolver.getServers());      })      .catch(err => console.log(err)) The output is shown in the console on running node dns in Integrated Terminal. IPv6 is  [ '2606:4700:8d75:a0e6:9ca:10c:f52a:f808' ]  Server address is  [ '2405:201:3001:a3a::c0a8:1d01', '192.168.29.1' ] Error Codes A lot of errors can be thrown when we use any of the dns or dns promise methods. The errors which we can get are as below. dns.NODATA: DNS server returned answer with no data. dns.FORMERR: DNS server claims query was mis-formatted. dns.SERVFAIL: DNS server returned general failure. dns.NOTFOUND: Domain name was not found. dns.NOTIMP: DNS server does not implement requested operation. dns.REFUSED: DNS server refused the query. dns.BADQUERY: Mis formatted DNS query. dns.BADNAME: Mis formatted host name. dns.BADFAMILY: Unsupported address family. dns.BADRESP: Mis formatted DNS reply. dns.CONNREFUSED: Could not contact DNS servers. dns.TIMEOUT: Timeout happened while contacting DNS servers. dns.EOF: End of file. dns.FILE: Error reading file. dns.NOMEM: Out of memory. dns.DESTRUCTION: Channel is being destroyed. dns.BADSTR: Mis formatted string. dns.BADFLAGS: Illegal flags specified. dns.NONAME: Given host name is not numeric. dns.BADHINTS: Illegal hints flags specified. dns.NOTINITIALIZED: c-ares library initialization not yet performed. dns.LOADIPHLPAPI: Error loading iphlpapi.dll. dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function. dns.CANCELLED: DNS query cancelled.We will see an example of DNS error. In the below example of resolver.resolve6() method, we have given a domain name which doesn’t exist. Add the below code in a dns.js file. const { Resolver } = require('dns').promises;  const resolver = new Resolver();  resolver.resolve6('abc.tech')      .then(addresses => console.log(addresses))      .catch(err => console.log(err)) So, we are getting the NOTFOUND error, when we are running node dns from terminal. { Error: queryAaaa ENOTFOUND abc.tech      at QueryReqWrap.onresolve [as oncomplete] (internal/dns/promises.js:163:17)    errno: 'ENOTFOUND',    code: 'ENOTFOUND',    syscall: 'queryAaaa',    hostname: 'abc.tech' } Implementation considerations There is a difference in the was dns.lookup() runs and the other dns methods like dns.resolve(), dns.reverse() runs. The dns.lookup() will always resolve a given name using the same way a ping command works. It doesn’t make a network call and is implemented as a synchronous call to getaddrinfo() function. The functions dns.resolve() and dns.reverse() are implemented quite differently, and they don’t use the getaddrinfo() function. They will always perform a DNS query on the network. So, the result is more accurate and updated. So, these differences can have significant consequences to our NodeJS program and should be considered. SummaryIn this post, we have learnt about the various DNS methods available in our Node.JS. We can use these methods to get a lot of information about any host. Many of these methods need us to have network access to the required, but they can always be used for internal NodeJS codes also. Knowledge of these methods, along with network concepts are important for NodeJS application development. 
9276
What Is the Use of DNS Module in Node.Js?

Node.js gives the provision of using different mo... Read More

What Is the Relationship Between Node.Js and V8?

In this article, we will look into Node.js and V8. Node.js is a very important part of the JavaScript ecosystem, as it is used in the backend to produce a complete application. It is often considered a part of the popular MERN(MongoDB, ExpressJS, ReactJS and Node.js) stack and MEAN (MongoDB, ExpressJS, Angular and Node.js) stack. The V8 engine is what powers Node.js and it is an open-source engine on which even Chrome works. It parses and runs your JavaScript inside a Node environment. Overview on Node.jsNode.js was created by Ryan Dahl in 2009 and since then it has become a very popular backend technology. Till then the backend was dominated by languages like PHP, ASP.NET and Java. It has become popular because it enables a Frontend developer with JavaScript skills to easily create full stack apps.The formal definition on the official Node.js website describes Node.js as “a JavaScript runtime built on Chrome’s V8 JavaScript engine.”Node.js came into existence when its creator Ryan Dahl, understanding the power of V8, powered the Chrome browser and extended it so that it can run on your machine as a standalone application. Another part of the definition on the official Node.js website says,Node.js uses an event driven, non-blocking I/O model that makes it lightweight and efficient.I/O refers to input/output and this is where the additional functionality of Node.js comes into play. We can read and edit local files in Node.js and also do an HTTP request to an API. The earlier backend systems like PHP and ASP used to block the program till a network request was complete. But it was completely changed by Node.JS, which sends the request and then goes to the next line of code. So, it is non-blocking and faster than the earlier backend technologies. But it is a single-threaded technology and that is where it has some limitations, whereas Java shines because of it being multi-threaded. Yet another part of the official definition on the Node.js website says,Node.js package ecosystem, npm is the largest ecosystem of open-source libraries in the world. Over the past decade, an amazing community of open-source enthusiasts have created more than 1 million npm packages, which enhance the capabilities of Node.js.It is completely open-source and anyone can use it, as it has an MIT licence, for developing server-side and networking applications. It can run on all three Operating Systems i.e., Mac OS, Windows, and Linux.Overview on V8 JavaScript engineV8 is Google’s open-source JavaScript engine, which is written in C++. It was developed in 2008 for Google Chrome and Chromium based browsers (like Brave), but was used to build Node.js for server-side coding. In fact, the V8 engine, is also used by JSON based No-SQL databases like Couchbase and the popular MongoDB. Besides this, V8 also powers the popular desktop application framework Electron and the latest server-side runtime environment of Deno. V8 is a JavaScript engine, because it takes our JavaScript and executes it while browsing in Chrome. It actually provides a runtime environment in which JavaScript executes. The great thing about this is that the JavaScript engine is independent of the browser in which it executes. This is the feature that prompted the creator of Node.JS to choose V8 engine to power Node.JS and the rest is history. The popularity of Node.JS exploded and the V8 engine was also used to create desktop frameworks and databases.There are other JavaScript engines like SpiderMonkey used by Firefox, and JavaScript Core used by Safari. Microsoft’s Edge was originally based on Chakra JavaScript engine, but has been recently re-built with Chromium and V8 engine.How V8 Engine works A JavaScript Engine is an interpreter which executes JavaScript code. We can create JavaScript engine in two ways – the first way is to implement as a standard interpreter which is done by SpiderMonkey from Mozilla. The other way is the Just-in-time (JIT) compilation, which converts the native JavaScript code to machine code and that is the way V8 uses it. So, the difference between V8 code and others is that it does not produce any intermediate code. When a developer or program runs a JavaScript on V8(i.e. in browser or Node environment), the Ignition interpreter compiles the JavaScript code and generates non-optimized machine code. On runtime, the machine code is analyzed and re-compiled for best performance, by the Turbofan and Crankshaft components of V8. The V8 engine also uses some other components, along with the ones we had seen above. They are Liftoff and Orinoco– Liftoff is responsible for machine code generation in a highly optimized way. It generates code for each opcode and perform way better then Turbofan.Orinoco is responsible for garbage collection. It looks for disconnected memory allocations and perform operations to free up more space. It also update the pointers to new memory locations.V8 also uses a lot of different threads and they are – The primary thread fetches and compiles the JavaScript code.There is another thread which is used to optimize the running code, while the primary thread continues its execution. Yet another thread is used for profiling, which tells on runtime the methods that are needed to be optimized. Some of the threads also do garbage collection.The Just-in-Time ParadigmWe will learn a bit more about the Just-in-Time (JIT) compilation in V8. For a code to execute in any programming language, it must be converted into machine code, which the computer understands. There is a different paradigm for this transformation. Most of the traditional languages created before JavaScript like C++ and Java, perform something called Ahead-of-Time compilation. Here, the code is transformed into machine code before the execution of our program during compile time. Anyone who has worked with Java or C++ knows that we run commands like below to compile a Java or C++ program.javac MyJavaProgram.java  g++ -o mycppprogram mycppprogram.cpp This converts the code into machine code after which we can run our program with commands like below.  java MyJavaProgram  ./mycppprogram On the other hand, in languages like JavaScript and Python, each line of code is executed at runtime. This is done because it is impossible to know the exact code before execution. In a browser, you never compile a code first and then run it, because it is done automatically behind the scenes.So, the Ahead-of-Time compilation produces more optimized and fast code, because of the compilation done before hand. Which is why interpretation done by languages like JavaScript are slower.To overcome this problem in dynamic languages, the approach of Just-in-Time (JIT) compilation, was created, which combines the best of both interpretation and compilation. So, an interpretation step runs before the compilation step, where the V8 engine detects the more frequently used functions and code and compiles them using information from previous executions.During compile time, this code is re-compiled for optimal performance.What is the relationship between Node and V8?The Node.js is referred to as a runtime environment, which includes everything you need to run a program written in JavaScript.The core powering Node.js is this V8 engine. The diagram shows a comparison with the Java Virtual Machine (JVM), which power the Java Runtime environment. Beside the V8 engine the Node.js runtime environment adds many Node APIs to power the Node.js environment. We can also extend the functionality of our node code by installing additional npm packages.One thing to understand is that V8 is essentially an independent C++ library, that is used by Node or Chromium to run JavaScript code. V8 exposes an API that other code can use, so if you have your own C++ program, you can embed V8 in it and run a JavaScript program. That is how it is done by Node and Chrome.Suppose, we want to add a functionality in our JavaScript code to have statements like print(‘hello world’), in addition to the console.log(‘Hello World’). We can add our own implementation of print function in C++, in V8, which is anyway open sourced. Can Node.js work without V8?The current Node.js engine cannot work without V8. It would have no JavaScript engine and hence no ability to run any JavaScript code. The fact is that the native code bindings, which come with Node.js like the fs module and the Net module, rely on the V8 interface between C++ and JavaScript.  Although in the tech world everything is possible and Microsoft in July 2016, made an effort to use Chakra JavaScript engine (which was used in Edge browser at that time) in Node.js and replace the V8 engine,  that project never took off and Microsoft Edge itself recently moved to Chromium, which uses V8 JavaScript engine.The new kid on the block for server-side programming is DENO. Many consider that it could be a replacement to Node.js in the next 2-3 years, and it also uses V8 JavaScript engine under its hood.Summary We have got an overview of Node.js runtime environment and V8 JavaScript engine in this post. Then, we have gone through the working of the V8 engine. We also investigated details of the Just-in-Time compilation, used by V8 JavaScript engine. Also, we have understood the relationship between Node.js and V8 engine and how V8 engine is independent of Node.js.Lastly, we have learnt that it is not possible for Node.js to run without a JavaScript engine like V8. It can, however, be replaced by another JavaScript engine like Chakra from Microsoft; even though this is highly improbable,  it is still possible. 
5638
What Is the Relationship Between Node.Js and V8?

In this article, we will look into Node.js and ... 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

How to Install Angular on Windows

In this article, you will learn how you can install Angular CLI on your Windows machine and use it to create real-life Angular Applications/Projects.As you know, Angular is popularly used to create SPAs (Single page applications). Angular is an in-demand, open-source, and modern web application development framework by Google, as compared to all other Libraries and Frameworks like ReactJs, VueJs, MithrilJs, etc.The reasons behind this are many. Angular provides you full access to use all its sub-packages like routing, Async calls, Security, etc.Introduction — What  you will learnIn this blog, we will cover the installation of Angular on Windows. By end of the article, you will understand how to -Install Node/npm on your machine.Use and install Angular CLI globally.Run Angular CLI commands.Create an initial workspace for the application.Run the Angular application in Browser.We assume you are already aware of the basics of web development including HTML, CSS, and JavaScript. (if so, please proceed otherwise we strongly recommand to learn those first before jumping into Angular).In order to continue, you must have — Windows MachineGood Internet ConnectivityWindows user account with all/admin installation privileges where you can install any packages freely.PS: While working with Angular, knowledge of TypeScript is good to have, but is not mandatory. A brief note about Node.jsThe very first thing required to install is Node.js. (If already installed, skip this part and jump to the next part of this blog.)Node.js is again an open-source and cross-platform JavaScript run-time environment that allows to execute JavaScript code outside of a browser (on the Server-side). Node.js is responsible to manage and install all npm dependencies for your Angular application. It provides the required libraries to run the Angular project. Node.js acts as a run-time environment for any Angular application which uses servers over localhost. For more information on Node.js refer to official docs.Angular requires the latest/stable version of Node.js in order to continue. Go to the official website in order to install Node.js on your machine locally.You can install any version, the current one or latest stable version, as per your need. Just click on the button and it will start downloading the package on your machine. Once downloaded click on the icons downloaded and follow the steps, till the installation is completed. To check the version installed of Node.js you can use the following command in a terminal/console window. —node -vornode — — versionNeed for NPM for Angular development As Node.js serves as Run time environment for the application, similarly NPM(node package manager) is used as a dependency management tool for any JavaScript application. NPM will allow us to install the libraries required for any Angular application; for example jQuery, angular-router, angular-http, bootstrap, and many more. You can explore a number of packages available in the npm store here.Note: Once you have installed Node.js it will automatically install NPM on your machine, and you can check the version installed using the below command. npm -vAngular CLI — What it is and complete Installation guideEarlier in the initial days of Angular, developers used to create whole architecture, webpack files, build process, etc for any project on their own from scratch which was quite a time-consuming and lengthy process. To make it easier for the developer, Angular team come up with the easy-to-use tool named Angular CLI. As the name suggests CLI (command line interface) provides a user (developer) friendly interface where you can run commands to make your development life easier and faster. Angular CLI comes with a number of commands available to use from creating a new project, to creating components, creating a routing configuration file, services, and many more.Installation Process of Angular CLITo install the Angular CLI on your machine, open the terminal window and run the following command: npm install -g @angular/cli where -g denotes that CLI is being installed globally to your machine, which means you can create or run any command of CLI anywhere on your machine. Once you run the above command CLI will be installed on your machine, and you can verify the version installed using the following command: ng version To know more about Angular CLI commands, you can refer to this blog which contains a number of commands to use. Creating a Project using Angular CLINow, let’s create our first ever Angular project using Angular CLI. Open your terminal window and type the command below on your machine.ng new hello-world Here ng is our CLI prefix, new denotes that we are creating a new project and hello-world is our project name. You can choose any name you want.After running this command you will find the full architecture of the project in the directory where you run this command. The project folder will be something like below in the image -Angular Project architecture The first file to render on running this application will be index.html which present in the src folder. src folder contains Source files for the root-level application project. assets folder contains all the static assets like images, fonts, etc. node_modules This folder is created while you run npm installby package manager (npm) and it contains all the project dependencies or any third party modules required for the project.  e2e folder contains all the source code related to Test Cases.You can customise it as per your requirements. README.md file is being used as documentation for the app. Package.json configures npm dependencies which are available for the project in the workspace along with their versions specified.  For more details about components/Service and source code you can explore this link. Run the application  one with the installation process of Angular application via CLI, it’s time to run the application locally. Angular CLI comes with complete tool-chain/commands for the development of front-end applications on your machine.Run the following command on the terminal (Navigate to the project directory if you are not in that directory).ng serve or ng serve --open The --open (or just -o) option automatically opens your browser to http://localhost:4200/. ng servecommand will serve your application on localhost server which you can check by navigating to your browser with the below URL http://localhost:4200/. You can customise the port as per your requirement. Accessing Angular Web Interfaceng serve command may take a few seconds to run your application, and once completed, you should see a web page similar to the following. And we are done!Now you can make changes in the default component’s template which is app.component.html .Also, moving forward, you can generate a number of components/service/routing files using CLI commands as per your requirements and keep learning.ConclusionIn this blog you have learnt - What is Node/NPM and how you can install and use it,  What is Angular CLI and how you can use it after installing it on your Windows machine, How to create a new Angular project from scratch using CLI commands and run it. Now that you have basic hands-on knowledge of getting started with an Angular application, you can start exploring Angular further. If you have any questions/doubts related to this blog, please let us know in the comment box below...we would be more than happy to help you out! Uninstall angular cliThere are cases when you need to uninstall Angular-CLI from your operating system, you can simply do so by running this below command on terminal -  npm uninstall -g @angular/cli It's always recommended to run the command  npm cache clean After un installation of Angular CLI from your system in order to avoid unwanted errors while installing it again. 
9584
How to Install Angular on Windows

In this article, you will learn how you can instal... Read More