Search

How to Use the Node.js REPL

Node.js is an Open-Source and Cross-platform JavaScript runtime environment built on V8 JavaScript engine – the core of google chrome. It is used to build high-performing and scalable applications and is an event-driven non-blocking I/O model.Introduction to REPLNode.js, when installed, comes with REPL environment which stands for READ, EVAL, PRINT, and LOOP which is similar to a computer environment like a command prompt or Shell. This environment interacts with the user writing or debugging through the outputs of his commands/expressions.To switch to this environment, open the terminal and enter ‘node’ text and press ‘Enter’ key. Let’s follow along with each keyword.READ – User interacting with the environment writes the commands or expressions which are parsed into Java script data structure and store in memory.EVAL – Output of READ i.e., parsed JavaScript data structure is evaluated to obtain the result.PRINT – The result obtained from the EVAL is printed back to the environment for the user to read.LOOP – The above three functions are executed in loop till the user exits/terminates from the environment by pressing Ctrl+C.To exit in Terminal (mac), press Ctrl+C twice (or) Ctrl+D (or) .exit + Enter key.In terminal:machine-name ~ % node Welcome to Node.js v14.16.1. Type ".help" for more information. >As you can see from the above pic, REPL is demarcated by symbol ‘>’ once it is started. As a user, we can input any command or expression to get REPL.Note: Going forward we would be switching between node.js terminal and chrome console based on convenience, but both would mean the same.Decoding the REPLUnderstanding of REPL with simple variableNow let's start giving a few basic commands and understand how REPL worksInvoke the REPL by entering the node and pressing the ‘enter’ key. You should be seeing the symbol ‘>’ ready to take input for evaluation.In browser console:> var greet = "Welcome to Node.Js REPL" <. undefined > greet <. 'Welcome to Node.Js REPL' > greet = "Good to see you here!" <. 'Good to see you here!' > greet <. 'Good to see you here!' >In the first line, we created a variable named greet with a value of ‘Welcome to Node.Js REPL’. REPL responded with undefined as the expression doesn’t return anything.Next, we entered the variable name ‘greet’ and REPL responded with the value stored in previous execution i.e., Welcome to Node.Js REPL.Post this, we tried reset the value of ‘greet’ variable with different text and on click on enter it responded with the new value in the ‘greet’. To recheck the value is set correctly, we re-entered the greet and REPL responded with the new value set i.e. ‘Good to see you here!’.Note: Output of the command is demarcated by symbol ‘<’ with dot in chrome and without symbol in terminal.Performing Arithmetic operations in REPLLet’s take another example where we want to perform some arithmetical operations in REPL.In browser console:> 1 + 1 // addition <. 2 > 2 - 1 //subtraction <. 1 > 2 * 2 // multiplication <. 4 > 6 / 3 // division <. 2 > 10 % 3 // remainder <. 1 > 3 * 4 - 2 / 2 + 1 // follows BODMAS principle <. 12 >In the above example we are able to perform different arithmetic operations individually and together. And from the last example, it is evident that REPL internally follows BODMAS principle for performing operations.In-built Math Module in REPLNode.js also comes with a library called Math which is used to perform some more complex operations. Let’s see few of them which are used more often in action.Examples of Math methods in the browser console:> Math.floor(4/3) // round to lower integer <. 1 > Math.ceil(4/3) // round to closest higher integer <. 2 > Math.round(4.6) // rounds to higher if decimal is greater than or equal to .5 otherwise to lower integer <. 5 > Math.sqrt(4) // Square root <. 2 > Math.pow(2, 3) // 2 raised to the power of 3. <. 8 >Writing functions in REPLTill now we were using simple one-line expressions. Let’s try writing functions and get them executed as well. Let’s write a function which gives random number for a given maximum say 10, 100, 1000.> function getRandomNumber(max) {     let result = Math.random() * max;     return Math.floor(result);   } <. undefined >  getRandomNumber(10) <. 1 >  getRandomNumber(10) <. 7 >  getRandomNumber(100) <. 59 >  getRandomNumber(1000) <. 431 >An important observation here is that after the first line curly bracket REPL didn’t evaluate the statement/expression. Instead, it went on the input mode to take more user text. After closing the curly bracket, it stored the function for future evaluation.Note: Math.random() returns a random decimal value within the range of 0 to 1.Loops in REPLWe can also execute loops in REPL. As we observed for functions, REPL will wait for the closing curly brace and then evaluates. Let’s take a for loop to demonstrate it.> for (var i = 0; i < 100; i++) {     var sqrt = Math.sqrt(i);     if (Math.floor(sqrt) === Math.ceil(sqrt)) {         console.log(i);     }   }   0   1   4   9   16   25   36   49   64   81 <. undefined >Note that the output is undefined but during execution/evaluation of for-loop we added the console.log to display the numbers which have prefect square roots with integer values.Also, REPL didn’t execute the expression after the first closing curly brace as REPL understands it is for the IF statement and not for the FOR loop. So, it tracks the number of open and closed curly brackets.REPL in NodeJSIn node.js terminal, we have a few other options which are listed down and can be obtained by writing ‘.help’ and pressing the ‘ENTER’ key.COMMANDDESCRIPTION.breakSometimes you get stuck, this gets you out.clearAlias for .break.editorEnter editor mode.exitExit the REPL.helpPrint this help message.loadLoad JS from a file into the REPL session.saveSave all evaluated commands in this REPL session to a fileFrom the above list, we have already used a few of them like .exit and .help. Let’s look at the other options.Overview of REPL commands.break - When in the process of inputting a multi-line expression like writing a for loop, enter the .break command (or press Ctrl+C) to abort further input or processing of that expression..editor - Helps in going to editor mode to process multiple lines, functions, etc. On pressing Ctrl+D, it will execute the code written in editor, and to cancel press Ctrl+C..Save - Helps to save all the operations done to the file for future reference..load - helps to load the file into the current REPL session.The REPL ModuleOverview on Standalone REPL ModuleNode.js also comes up with a REPL module that is available as standalone or includible in other applications. All the functionalities we discussed above are available in this module as well. The respective input and output are defaulted to Process.stdin and Process.stdout can be configured to any other Node.js stream.Since it is exposed as a module it has access to the internal core modules and load them in REPL environment.Exception HandlingREPL uses the domain module for all uncaught exceptions in their respective session. And the effect of this is that the uncaught exception only emits the ‘uncaughtException’ event and a listener to this event in other node.js results in ERR_INVALID_REPL_INPUT.Similarly, if we use process.setUncaughtExceptionCaptureCallback() then it will show an ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE error.REPL supports asynchronous functionalityAwait keyword is supported and enabled. Let’s look at an example.> async function Sample() { ... console.log(await Promise.resolve('test')); ... } undefined > Sample() Promise { <pending> } > testAn REPL can be exposed from node.js application with the help of repl module.Create a node js application using npm init.Fill the package details with valid info.Create an index.js file with the below code.Install the repl module using npm I.e., npm install repl.Run node index.js and perform same kind of action as we do on REPL.import repl from 'repl'; repl.start({   prompt: 'Node.js via stdin:',   input: process.stdin,   output: process.stdout   });Output:CustomizationWith the help of environment variables, REPL behavior can be customized.NODE_REPL_HISTORY – path where the REPL history will be stored. To disable REPL history set it to empty string '’.NODE_REPL_HISTORY_SIZE – As the name suggests the number of lines of history to be persisted with the default being 1000 and accepts only positive number.NODE_REPL_MODE – allows the code to run in strict or sloppy mode with default being sloppy.Sharing REPL instancesSingle/Multiple REPL instances can be created and run in an instance of Node.js which can be shared via global object.Usage of REPL moduleThe following example provides a REPL instance on stdin of a TCP socket and the same could be created in different Unix socket or same socket with a different port.Steps:Open the terminalCreate a folder namely REPL using mkdir and navigate inside the folder.Execute npm initFill the required details on prompt for package.json file, take the default wherever possible with package name customrepl.Create two files Server.js and Client.js file with the below content.Install net and repl module using npm I.e.,npm install net andnpm install replExecute node Server.js file to start the server in same terminal.Invoke another terminal and navigate to REPL folder.Execute node Client.js file to start the client.Now the client has the ability to perform REPL actions on client.server.js file:import net from 'net'; import repl from 'repl'; net.createServer(function (socket) { var r = repl.start({ prompt: 'Node.js via TCP socket> ' , input: socket , output: socket , terminal: true , useGlobal: false }) r.on('exit', function () { socket.end() }) }).listen(5001);client.js file:import net from 'net'; var sock = net.connect(5001) process.stdin.pipe(sock) sock.pipe(process.stdout) sock.on('connect', function () { process.stdin.resume(); process.stdin.setRawMode(true) })Output:Significance of REPL REPL is an interactive environment that comes with installing node.js, helps to execute JS code without saving or writing to a file. Understanding this is important to anyone who wants to work with Node. Try what you have read here starting from the basic arithmetic operation, expressions to having node.js REPL over net.server.

How to Use the Node.js REPL

5K
How to Use the Node.js REPL

Node.js is an Open-Source and Cross-platform JavaScript runtime environment built on V8 JavaScript engine – the core of google chrome. It is used to build high-performing and scalable applications and is an event-driven non-blocking I/O model.

Introduction to REPL

Node.js, when installed, comes with REPL environment which stands for READ, EVAL, PRINT, and LOOP which is similar to a computer environment like a command prompt or Shell. This environment interacts with the user writing or debugging through the outputs of his commands/expressions.

To switch to this environment, open the terminal and enter ‘node’ text and press ‘Enter’ key. Let’s follow along with each keyword.

  • READ – User interacting with the environment writes the commands or expressions which are parsed into Java script data structure and store in memory.
  • EVAL – Output of READ i.e., parsed JavaScript data structure is evaluated to obtain the result.
  • PRINT – The result obtained from the EVAL is printed back to the environment for the user to read.
  • LOOP – The above three functions are executed in loop till the user exits/terminates from the environment by pressing Ctrl+C.
    • To exit in Terminal (mac), press Ctrl+C twice (or) Ctrl+D (or) .exit + Enter key.

In terminal:

machine-name ~ % node
Welcome to Node.js v14.16.1.
Type ".help" for more information.
>

As you can see from the above pic, REPL is demarcated by symbol ‘>’ once it is started. As a user, we can input any command or expression to get REPL.

Note: Going forward we would be switching between node.js terminal and chrome console based on convenience, but both would mean the same.

Decoding the REPL

Understanding of REPL with simple variable

Now let's start giving a few basic commands and understand how REPL works

Invoke the REPL by entering the node and pressing the ‘enter’ key. You should be seeing the symbol ‘>’ ready to take input for evaluation.

In browser console:

> var greet = "Welcome to Node.Js REPL" 
<. undefined 
> greet 
<. 'Welcome to Node.Js REPL' 
> greet = "Good to see you here!" 
<. 'Good to see you here!' 
> greet 
<. 'Good to see you here!' 
>

In the first line, we created a variable named greet with a value of ‘Welcome to Node.Js REPL’. REPL responded with undefined as the expression doesn’t return anything.

Next, we entered the variable name ‘greet’ and REPL responded with the value stored in previous execution i.e., Welcome to Node.Js REPL.

Post this, we tried reset the value of ‘greet’ variable with different text and on click on enter it responded with the new value in the ‘greet’. To recheck the value is set correctly, we re-entered the greet and REPL responded with the new value set i.e. ‘Good to see you here!’.

Note: Output of the command is demarcated by symbol ‘<’ with dot in chrome and without symbol in terminal.

Performing Arithmetic operations in REPL

Let’s take another example where we want to perform some arithmetical operations in REPL.

In browser console:

> 1 + 1 // addition 
<. 2 
> 2 - 1 //subtraction 
<. 1 
> 2 * 2 // multiplication 
<. 4 
> 6 / 3 // division 
<. 2 
> 10 % 3 // remainder 
<. 1 
> 3 * 4 - 2 / 2 + 1 // follows BODMAS principle 
<. 12 
>

In the above example we are able to perform different arithmetic operations individually and together. And from the last example, it is evident that REPL internally follows BODMAS principle for performing operations.

In-built Math Module in REPL

Node.js also comes with a library called Math which is used to perform some more complex operations. Let’s see few of them which are used more often in action.

Examples of Math methods in the browser console:

> Math.floor(4/3) // round to lower integer 
<. 1 
> Math.ceil(4/3) // round to closest higher integer 
<. 2 
> Math.round(4.6) // rounds to higher if decimal is greater than or equal to .5 otherwise to lower integer 
<. 5 
> Math.sqrt(4) // Square root 
<. 2 
> Math.pow(2, 3) // 2 raised to the power of 3. 
<. 8 
>

Writing functions in REPL

Till now we were using simple one-line expressions. Let’s try writing functions and get them executed as well. Let’s write a function which gives random number for a given maximum say 10, 100, 1000.

> function getRandomNumber(max) { 
    let result = Math.random() * max; 
    return Math.floor(result); 
  } 
<. undefined 
>  getRandomNumber(10) 
<. 1 
>  getRandomNumber(10) 
<. 7 
>  getRandomNumber(100) 
<. 59 
>  getRandomNumber(1000) 
<. 431 
>

An important observation here is that after the first line curly bracket REPL didn’t evaluate the statement/expression. Instead, it went on the input mode to take more user text. After closing the curly bracket, it stored the function for future evaluation.

Note: Math.random() returns a random decimal value within the range of 0 to 1.

Loops in REPL

We can also execute loops in REPL. As we observed for functions, REPL will wait for the closing curly brace and then evaluates. Let’s take a for loop to demonstrate it.

> for (var i = 0; i < 100; i++) { 
    var sqrt = Math.sqrt(i); 
    if (Math.floor(sqrt) === Math.ceil(sqrt)) { 
        console.log(i); 
    } 
  } 
  0 
  1 
  4 
  9 
  16 
  25 
  36 
  49 
  64 
  81 
<. undefined 
>

Note that the output is undefined but during execution/evaluation of for-loop we added the console.log to display the numbers which have prefect square roots with integer values.

Also, REPL didn’t execute the expression after the first closing curly brace as REPL understands it is for the IF statement and not for the FOR loop. So, it tracks the number of open and closed curly brackets.

REPL in NodeJS

In node.js terminal, we have a few other options which are listed down and can be obtained by writing ‘.help’ and pressing the ‘ENTER’ key.

COMMAND
DESCRIPTION
.breakSometimes you get stuck, this gets you out
.clearAlias for .break
.editorEnter editor mode
.exitExit the REPL
.helpPrint this help message
.loadLoad JS from a file into the REPL session
.saveSave all evaluated commands in this REPL session to a file

From the above list, we have already used a few of them like .exit and .help. Let’s look at the other options.

Overview of REPL commands

.break - When in the process of inputting a multi-line expression like writing a for loop, enter the .break command (or press Ctrl+C) to abort further input or processing of that expression.How to use the Node.js REPL.editor - Helps in going to editor mode to process multiple lines, functions, etc. On pressing Ctrl+D, it will execute the code written in editor, and to cancel press Ctrl+C.

How to use the Node.js REPL

.Save - Helps to save all the operations done to the file for future reference.

How to use the Node.js REPL

.load - helps to load the file into the current REPL session.

How to use the Node.js REPL

The REPL Module

Overview on Standalone REPL Module

Node.js also comes up with a REPL module that is available as standalone or includible in other applications. All the functionalities we discussed above are available in this module as well. The respective input and output are defaulted to Process.stdin and Process.stdout can be configured to any other Node.js stream.

Since it is exposed as a module it has access to the internal core modules and load them in REPL environment.

Exception Handling

REPL uses the domain module for all uncaught exceptions in their respective session. And the effect of this is that the uncaught exception only emits the ‘uncaughtException’ event and a listener to this event in other node.js results in ERR_INVALID_REPL_INPUT.

Similarly, if we use process.setUncaughtExceptionCaptureCallback() then it will show an ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE error.

REPL supports asynchronous functionality

Await keyword is supported and enabled. Let’s look at an example.

> async function Sample() { 
... console.log(await Promise.resolve('test')); 
... } 
undefined 
> Sample() 
Promise { <pending> } 
> test

An REPL can be exposed from node.js application with the help of repl module.

  • Create a node js application using npm init.
  • Fill the package details with valid info.
  • Create an index.js file with the below code.
  • Install the repl module using npm I.e., npm install repl.
  • Run node index.js and perform same kind of action as we do on REPL.
import repl from 'repl'; 
repl.start({   
prompt: 'Node.js via stdin:',   
input: process.stdin,   
output: process.stdout   
});

Output:

How to use the Node.js REPL

Customization

With the help of environment variables, REPL behavior can be customized.

  • NODE_REPL_HISTORY – path where the REPL history will be stored. To disable REPL history set it to empty string '’.
  • NODE_REPL_HISTORY_SIZE – As the name suggests the number of lines of history to be persisted with the default being 1000 and accepts only positive number.
  • NODE_REPL_MODE – allows the code to run in strict or sloppy mode with default being sloppy.

Sharing REPL instances

Single/Multiple REPL instances can be created and run in an instance of Node.js which can be shared via global object.

Usage of REPL module

The following example provides a REPL instance on stdin of a TCP socket and the same could be created in different Unix socket or same socket with a different port.

Steps:

  • Open the terminal
  • Create a folder namely REPL using mkdir and navigate inside the folder.
  • Execute npm init
  • Fill the required details on prompt for package.json file, take the default wherever possible with package name customrepl.
  • Create two files Server.js and Client.js file with the below content.
  • Install net and repl module using npm I.e.,
    • npm install net and
    • npm install repl
  • Execute node Server.js file to start the server in same terminal.
  • Invoke another terminal and navigate to REPL folder.
  • Execute node Client.js file to start the client.
  • Now the client has the ability to perform REPL actions on client.

server.js file:

import net from 'net'; 
import repl from 'repl'; 
net.createServer(function (socket) { 
var r = repl.start({ 
prompt: 'Node.js via TCP socket> ' 
, input: socket 
, output: socket 
, terminal: true 
, useGlobal: false 
}) 
r.on('exit', function () { 
socket.end() 
}) 
}).listen(5001);

client.js file:

import net from 'net'; 
var sock = net.connect(5001) 
process.stdin.pipe(sock) 
sock.pipe(process.stdout) 
sock.on('connect', function () { 
process.stdin.resume(); 
process.stdin.setRawMode(true) 
})

Output:How to use the Node.js REPL

Significance of REPL 

REPL is an interactive environment that comes with installing node.js, helps to execute JS code without saving or writing to a file. Understanding this is important to anyone who wants to work with Node. Try what you have read here starting from the basic arithmetic operation, expressions to having node.js REPL over net.server.

Sumanth

Sumanth Reddy

Author

Full stack,UI Architect having 14+ Years of experience in web, desktop and mobile application development with strong Javascript/.Net programming skills .Strong experience in microsoft tech stack and Certified in OCI associate. Go-to-guy on integration of applications, building a mobile app by zeroing on tech stack. Majorily experienced on engineering based IIOT products and Marekting Automation products deployed on premise and on-cloud. 

Join the Discussion

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

Suggested Blogs

How to Become a Successful Full Stack Web Developer?

The ResponsibilitiesFull-stack developer roles are among the hottest careers in the tech space now. These talented folks can develop a whole product from scratch. A full-stack developer is a combination of a Front-end developer and a Back-end developer. These two in themselves are full-time jobs and most people make careers out of one of them. So, we will start with the Front-end roadmap and then go to the Back-end roadmap. A person interested in becoming a Full-stack developer needs to have proficiency in both the front-end and back-end tools, just like I started as a Front-end developer and later on become a Full stack developer by mastering JavaScript backend technologies and databases.Industries were relevantThe demand for Full stack developers is the highest in early-stage startups, where they want to create a Minimum Viable Product at the earliest to showcase to the investors. It is also a nice skill to have in addition to frontend technologies or backend technologies alone since an employer prefers people with both skills.What to learn & where to learnThere are a lot of technologies to learn to be a Full-Stack developer. We will discuss about them in the coming sections.   List of technologies to master to become a Full-Stack developer A full-stack developer is actually a combination of Front-end developer and Back-end developer. We need to master both, and both have different Roadmaps. Let’s start with the basics. The frontend is the website that we see and it is primarily made with HTML and CSS.  JavaScript was also used earlier but nowadays, it is created with JavaScript frameworks like ReactJS, Angular, or Vue. All these frameworks require one to learn the basics of HTML, CSS, & JavaScript. So, we need to learn the basics followed by at least one framework.In the backend, we have a lot of technologies and databases also. So, we need to choose one backend framework from Java (Spring Framework), JavaScript (NodeJS), etc, and then also learn databases. Databases are divided into two categories, which are NoSQL(MongoDB) and SQL(PostgreSQL, MySQL, Oracle) databases. So, you need to choose one of the databases.We are also required to know about DevOps, which is a practice of harmonizing development and operations whereby the entire pipeline from development, testing, deployment, continuous integration, and feedback is automated. The knowledge of either AWS or Azure-based cloud ecosystem is required, and also CI/CD like Jenkins and containerizing & orchestrating applications using Docker and Kubernetes.Frontend RoadmapLearn the BasicsPlease refer to the attached figure for the Front-end roadmap, as we will be referring to this throughout this article. We have to start our journey by learning HTML, CSS, and JavaScript which is the base for a web app or website. HTML has changed a bit over the years, with the introduction of HTML 5 and semantics tags, so make sure to update yourself. JavaScript which was released in 1995, didn’t change much during the next 20 years. But once more and more developers started using it, the ECMA committee decided to add some very nice features and enhance the language and renamed it ES6 in 2015. After that, they regularly added new features to the language and have just released ES2020 in June 2020, which has many additional features. So, learn the basic JavaScript first and then upgrade to ES6 and newer versions. CSS is what makes a website or web-app beautiful, and is often considered the hardest part by a developer. Earlier, CSS was very confusing and had a steep learning curve, because of the use of floats to create a layout. Developers usually used to work with CSS frameworks like bootstrap to design a site. But things have changed a lot with the invention of CSS Grid and Flexbox. Some of the best resources to learn the basics are -html.specdeveloper.mozilla.HTMLStyle CSSdeveloper.mozilla.CSSdeveloper.mozilla.JavaScriptGetting Deeper Now, just learning JavaScript and some basic CSS will not make you a good Front-end developer as you have to take a deep dive into JavaScript. We will discuss CSS later, after learning the essentials of JavaScript.JavaScript EssentialsThere are many things associated with JavaScript which we need to learn before moving forward.The TerminalThe first thing to learn is to work in a terminal and master some of the basic commands. If you are on a Mac, it’s already based on Linux and runs most Linux commands. If you are working on Windows then you must install git bash, which will give you a Linux environment to work with. In JavaScript frameworks, we need to run a lot of commands from the terminal, like if we want to install a third-party dependency by npm.  The basics of Linux can be learned from their official site: Linux FoundationVersion ControlNext, learning version control is very important because we should always keep our code in some remote repository like Github. The industry works on Git, which is version control software. It is completely command-based and is used heavily everywhere. Learn the basic commands which will be useful even for an individual developer. Later on, when working with teams, more advanced knowledge of the git command is required.Through the git commands, we store our code in repositories. The most popular ones are Github and Bit Bucket, so we need to learn how to store and link them.The basics of git can be learned from this awesome tutorial: Git TutorialTask Runners Task runners are applications that are used to automate tasks required in projects. These tasks include minification of JavaScript and CSS files, CSS preprocessing from SASS to CSS, image optimization, and Unit testing. The three popular task runners are npm scripts, gulp, and grunt.The npm script is nothing but the package.json file which comes with React projects or is created in a Node.js project using npm init. Gulp and Grunt are much bigger applications and also have a plugin ecosystem that is suited for large JavaScript projects. The basics for these two technologies can be learned from here:GulpGruntModule Loader and Bundler  Both module loaders and bundlers are required for large JavaScript applications. Knowledge of both is required if the project you are working is a big Vanilla JavaScript project. When a large JavaScript application consists of hundreds of files, the module loader takes care of the dependency and makes sure all the modules are loaded when the application is executed. Examples are RequireJS and SystemJS.Module bundlers also do the same thing, building it at the time of application build rather than at the runtime. Popular examples are Webpack and Rollup.The basic tutorials which can be referred are:RequireJSGithubWebpackRollupJSTesting  Testing nowadays is very important in any type of project. There are two types of testing; one is known as Unit testing and other as end-to-end testing. For unit testing we write test cases and the most popular tool nowadays is Jest. End-to-end testing is automated testing, which emulates the whole app. Suppose, an app has a login screen and then it shows posts. The testing tool will run the web app to check whether all the functionalities are done correctly. The two most popular options today are Puppeteer and Cypress. The tutorials to refer for these topics are:JestPuppeteerCypressLibraries and FrameworkThey are the most important part of the JavaScript ecosystem nowadays. It all started with the release of AngularJS in 2010. Before that period most enterprise apps were made in Java and were desktop apps. But AngularJS changed everything because it made it easy to manage big projects with JavaScript and helped to create complex web apps.React It is the most popular JavaScript library today and is used by both enterprises and startups that have a huge ecosystem. It is not a complete framework like Angular and we have to install third-party dependencies for most things. But if you want to learn a framework that will get you a job, then that framework would be ReactJS, and its demand is not going away for the next 5 years. The component approach and its easy learning curve have made React more popular than other frameworks. A good starting tutorial for React is: ReactJSState Management In React state management can sometimes become complex, when we need to share data between components. We generally take the help of external packages in it with the most popular being Redux. But we also have other state management libraries like XState and Recoil.Server-side rendering With performance becoming important nowadays, Server-Side Rendering speeds up the React projects even faster. In SSR projects, the React code is rendered on the server and the client browser directly receives the HTML, CSS, JS bundle. The only framework to do it is NextJS.Static Site Generators   A lot of sites don’t need to be updated frequently and it is the place where the only Static Site Generator for ReactJS, which is GatsbyJS shines. With the help of GatsbyJS we can create extremely fast static sites and it gets into Wordpress domain a lot with it. GatsbyJS also has a huge ecosystem of plugins, which enhances its functionalities. React Testing   Unit testing is a very important part of ReactJS projects, especially the ones which are very large. Unit testing ensures that we have lower bugs in the Production build. The two popular libraries are – Enzyme and Jest. Angular It is a complete framework and unlike React requires very few external dependencies. Everything is built within Angular and we don’t have to go outside for more features. Since it was among the earliest frameworks, older projects are in Angular and it is still widely used in enterprises. A good tutorial to learn Angular is below-AngularVue Vue is another very popular JavaScript library, which has the best features of both ReactJS and Angular and has become very popular in recent years. It is widely used in both enterprises and startups. A good tutorial to start with Vue is below-Vue  NuxtJS-   It is used for Server-Side Rendering in Vue projects and is similar to the NextJS framework used in ReactJS for SSR.  Svelte It is the newest of all frameworks/libraries and has become quite popular, but still not used much in enterprises and startups. It is different from React, Vue, and Angular and converts the app at build time rather than at run time as in the other three. Good tutorials to start with Svelte are below-SvelteSvelte handbookCSS Deep DiveA lot has changed in CSS after it included CSS Grid and Flexbox; it has become much easier for developers to work with. CSS Essentials   It is now mandatory for frontend developers to learn CSS Grid and Flexbox, because through it we can develop beautiful layouts with ease. More companies are moving away from CSS Frameworks and have started working with CSS Grid and Flexbox, which are now supported by all browsers. Good tutorials to learn Flexbox and CSS Grid are below-CSS FlexboxCSS layout FlexboxCSS GridCSS layout GridGrid GuidePreprocessors CSS preprocessors are used to add special functionalities in CSS, which it lacks. An example is Sass, which adds special features like variables and nested rules in CSS and is widely used in the industry for larger projects. The other popular one is PostCSS, in which we can use custom plugin and tools in CSS. CSS Frameworks Frameworks were very popular from the early days of CSS, when it was very complicated because of floats. Bootstrap  This is the most popular and oldest CSS framework; easy to learn and also has a wide variety of elements, templates and interfaces. Bulma   It is another CSS framework, which is very popular and much easier to use than bootstrap. Tailwind CSS   This is a fairly new CSS framework and is quite popular nowadays. It follows a different approach than the other frameworks and contains easier classes. Styled Components (React)   This is a CSS in JS library and is for React only. It is used to create components out of every style and is very popular in the React world.  CI/CDContinuous Integration/ Continuous deployment is mainly used by DevOps. But a frontend engineer should know its basics. It is used to build, test and deploy applications automatically.Github Actions    It is a freely available CI/CD pipeline, which directly integrates to your github based project and can be used in a variety of languages. Deployment It is again a task that mainly falls into the domain of Backend engineers and DevOps, but a frontend engineer should know some basic and simple tools. Static Deployment   These products are mainly used to deploy static sites, which consists of HTML, CSS, and JavaScript only. Two very popular services are Amazon S3 and Surge.sh.Node Application Deployment   The projects containing node code cannot be deployed using static deployment. Even if the project is a simple ReactJS project, it also uses node for processing. These applications require services which run the Node code and deploy it. The three most popular services are Vercel, Firebase and Netlify. Backend Roadmap (Including Storage, Services & Deployment)Understanding the BackendBackend is the part of the website that provides the functionality, allowing people to browse their favorite site, purchase a product and log into their account, for instance. All data related to a user or a product or anything else are generally stored in databases or CMS (Content Management System) and when a user visits any website, they are retrieved from there and shown. One of the responsibilities of a backend engineer involves writing APIs, which actually interact with the database and get the data. They are also involved in writing schemas of databases and creating the structure of databases. Backend EssentialsFor a backend engineer, working in a Linux environment is an essential skill. A lot of the configurations are done on the terminal. So, he or she should be very good with Linux commands.Also, they should know both commands and the use of any git powered platforms like Github or bitbucket.Languages and FrameworksAll of the popular languages have some framework, which has been used for backend development. These frameworks are generally used to create API endpoints, which are used to fetch or store data in the database. For example, when we scroll articles on Facebook, these articles are fetched from a database and we use the GET method to fetch them. Similarly, when we write an article and hit submit, it uses POST method.Now, different frameworks implement this GET, POST, and other APIs also referred to as RESTful APIs in their own way.JavaJava is by far the oldest and the most used language for backend development. It is also used for a variety of other tasks like Android development, but it shines in the backend because of its multithreading abilities. So, enterprise-grade web apps and web apps with a lot of traffic prefer Java, because it handles loads better.The most popular frameworks for backend development in Java are Spring Framework and Hibernate.JavaScriptIt is a very popular choice for backend development because on the frontend side JavaScript is the only choice. So, a lot of front-end engineers can take this choice to become Full-stack developers.Node.jsIt allows developers to use JavaScript to write server-side code, through which they can write APIs. Actually, the API part can be done by numerous frameworks of Node.js out of which Express is widely used. The other popular framework is Fastify.PythonPython is one of the most popular languages among developers and has been used in a variety of fields. The two most popular frameworks for Python are Flask and Django.C#It is a very popular programming language that was developed by Microsoft and it has the power of C++. Its popularity increased once the .NET framework was released for backend development.As Microsoft is very popular in enterprises, the .NET framework is generally preferred in enterprises.GoGo language which is also referred to as Golang, has gained popularity in recent years. It is used a lot in Backend programming and the two popular frameworks are Gin and Beego.DatabaseFor a Backend engineer, after making APIs with a framework based on language, it's time to learn about Databases. Databases are used to store most of the things which we see in a web app, from user login credentials to user posts and everything else. In the earlier days, we only used to have one type of Database and that was Relational databases, which use tables to store data. Now we have two other categories also, one being NoSQL databases and the other In-memory databases.Relational databasesRelational databases allow you to create, update and delete data stored in a table format. This type of database mostly uses SQL language to access the data, hence is also known as an SQL database.MySQLIt is one of the oldest databases and was released in 1995. It is an open-source database and was very popular in the 2000s with the rise of LAMP (Linux, Apache, MySQL, PHP) stack. It is still widely in use, but there are other popular Relational databases.A good tutorial to learn MySQL is- MySQL Tutorial.PostgreSQLPostgreSQL, which is also known as Postgres is also an old open-source Relational database, which was released in 1996. But it gained popularity recently, as it goes very well with modern stacks containing NodeJS and other backend technologies. A good tutorial to learn PostgreSQL is- PostgreSQL Tutorial.OracleOracle is the most popular and oldest relational database. It was released in 1979 and still remains the number one preference for enterprise customers. All the big banks and other organizations run on Oracle databases. So, the knowledge of Oracle is a must in many companies for an Engineer. A good tutorial to learn Oracle is- Oracle Tutorial.MS-SQLMS-SQL is also known as Microsoft SQL and is yet another commercial Relational database. It has got different editions, used by different audiences. It is also heavily used by enterprise users and powers a whole lot of big systems around the world.NoSQL databasesNoSQL databases are also called non-SQL databases. The NoSQL databases mainly store data as key-value pairs, but some of them also use a SQL-like structure.These databases have become hugely popular in the 21st century, with the rise of large web apps which have a lot of concurrent users. These databases can take huge loads, even millions of data connections, required by web apps like Facebook, Amazon, and others. Besides this, it is very easy to horizontally scale a NoSQL database by adding more clusters, which is a problem in Relational Databases.MongoDBIt is the most popular NoSQL database, used by almost every modern app. It is a free-to-use database, but the hosting is charged if we host on popular cloud services like MongoDB atlas. Its knowledge is a must for backend engineers, who work on the modern stack. MongoDB uses json like documents to store data. A good tutorial to learn MongoDB is- MongoDB Tutorial.DynamoDBDynamoDB is a proprietary database service provided by Amazon. It is quite similar to MongoDB and uses key-value pairs to store data. It is also a part of the popular AWS services. A good tutorial to learn DynamoDB is- DynamoDB Tutorial.CassandraCassandra is an open-source and free-to-use NoSQL database. It takes a different approach when compared to other NoSQL databases, because we use commands like SQL, which are known as CQL (Cassandra Query Language). A good tutorial to learn Cassandra is- Cassandra Tutorial.In-memory databasesThe in-memory database is a database that keeps all the data in the RAM. This means it is the fastest among all databases.  The most popular and widely used in-memory database is Redis.RedisRedis (Remote Dictionary Server) is an in-memory database, which stores data in RAM in a json like key-value format. It keeps the data persistent by updating everything in the transaction log, because when systems are shut down their RAM is wiped clean. A good tutorial to learn Redis is- Redis Tutorial.StorageStoring the data is an important part of any application. Although this is mainly DevOps territory, every backend developer should know the basics for the same. We need to store the database data and also the backend code. Beside this the frontend code must also be stored somewhere. Nowadays everything is stored in the cloud, which is preferred by individuals, startups and enterprises. The two most popular cloud-based storages are –Amazon S3Azure Blob StorageServices and APIsThese are theoretical concepts and are implemented by various services, but a backend engineer should know them and how to use them.Restful APIsThis is by far the most popular way to get data from a database. It was made more popular, with the rise of web apps. We do GET, PUT, POST, and DELETE operations to read, update, create or delete data from databases. We have discussed different languages and frameworks earlier, which have their own implementations for these operations.Microservices ArchitectureIn microservice architecture, we divide a large and complex project into small, independent services. Each of these is responsible for a specific task and communicates with other services through simple APIs. Each service is built by a small team from the beginning and separated by boundaries which make it easier to scale up the development effort if needed.GraphQLIt is the hottest new kid in the block, which is an alternative to the Restful APIs. The problem with Restful APIs is that if you want some data stored in database, you need to get the whole data sent by the endpoint. On the other hand, with GraphQL, you get a query type language that can return only the part of the data which you require.DevOps & DeploymentA backend engineer requires a fair bit of DevOps knowledge. So, we will next dive deep into the methodologies in DevOps.Containerization & OrchestrationContainers are a method of building, packaging, and deploying software. They are like but not the same thing as virtual machines (VMs). One of the primary differences is that containers are isolated or abstracted away from the underlying operating system and infrastructure that they run on. In the simplest terms, a container includes both an application’s code and everything that code needs to run properly.Container orchestration is the automatic process of managing the work of individual containers for applications based on microservice architecture. The popular Containerization and Orchestration tools are-KubernetesDockerDevOpsDevOps is a set of practices that combine software development (Dev) and IT operations (Ops). It aims to shorten the systems development life cycle and provide continuous delivery with high software quality. The two most popular DevOps services are AWS and Azure. Both of them are cloud based and are market leaders. Both of these platforms contain a wide variety of similar services.AWSIt consists of over 200 products and services for storage, database, analytics, deployment, serverless function and many more. AWS is the market leader as of now with 33% of market share. The AWS certifications are also one of the most in-demand certifications and a must for frontend engineers as well as Backend engineers.AzureMicrosoft Azure is second in terms of market share of cloud-based platforms, with 18% of the market. It also consists of SaaS (Software as a Service), PaaS (Platform as a Service), and IaaS (Infrastructure as a Service) like AWS.PaaS (Platform as a Service)There are several smaller players, which provide Platform as a Service and are much easier to use than services like AWS and Azure. With these services you can directly deploy your React or other web apps, by just hosting them on GitHub and pushing the code. These services are preferred a lot by freelancers, hobbyists, and small companies as they don’t require investment in learning complicated services like AWS and Azure. The three most popular PaaS services are –Digital OceanHerokuNetlifyServerlessServerless computing is an execution model where the cloud provider (AWS, Azure, or Google Cloud) is responsible for executing a piece of code by dynamically allocating resources and only charging for the number of resources used to run the code. The code is typically run inside stateless containers that can be triggered by a variety of events including HTTP requests, database events, queuing services, monitoring alerts, file uploads, scheduled events (cron jobs), etc. The code that is sent to the cloud provider for execution is usually in the form of a function.AWS LambdaIt is an event-driven, serverless platform which is part of AWS. The various languages supported by AWS Lambda are Node.js, Python, Java, Go, Ruby and .NET. AWS Lambda was designed for use cases such as updates to DynamoDB tables, responding to a website click etc. After that it will “spin down” the database service, to save resources.Azure FunctionsThey are quite similar to AWS Lambda, but are for Microsoft Azure. Azure functions have a browser-based interface to write code to respond to events generated by http requests etc. The service accepts programming languages like C#, F#, Node.js, Python, PHP and Java.Serverless FrameworkIt is an open-source web-framework written using Node.js. Popular services like AWS Lambda, Azure functions and Google cloud functions are based on it.CI/CDA backend developer should know the popular CI/CD (Continuous Integration/Continuous deployment) tools. These tools help to automate the whole process of building, testing and deployment of applications.Github ActionsIt is a freely available CI/CD pipeline, which directly integrates to your GitHub-based project and can be used in a variety of languages.JenkinsJenkins is the most popular CI/CD automation tool, which helps in the building, testing, and deployment of applications. Jenkins was written in Java and over the years has been built to support over 1400 plugins, which extend its functionalities.Circle CICircle CI is also a CI/CD automation tool, which is cloud-based and so it is different from Jenkins. It is much easier to use than Jenkins, but has a smaller community and lower user base.SecuritySecurity is an important aspect of any application. Most applications containing user personal data, like email, etc, are often targeted by hackers.OWASPThe Open Web Application Security Project (or OWASP), is a non-profit organization dedicated to web application security. They have free material available on their website, making it possible for anyone to improve their web application security.Protecting Services & databases against threatsHackers target databases of popular web apps on a regular basis to get sensitive information about their customers. This data is then sold to the highest bidder on the dark-net. When such public breaches are reported, then it's a reputation loss for the enterprise also. So, a lot of emphases should be given to Authentication, Access, Backups, and Encryption while setting up a database. The databases should also be monitored for any suspicious activities.Besides this, the API routes also need to be protected, so that the hacker cannot manipulate them.Career rolesMost of the companies hire Frontend developers, Backend developers and DevOps engineers separately. This is because most of the enterprise projects are huge, in which roles and responsibilities are distributed.But there is a huge demand for Full Stack developers in the startup sector in US and India. These companies need specialists who can get the product out as soon as possible with agile and small teams.Top companies hiringAlmost every company on the planet is hiring web-developers or outsourcing the development work. Since the past decade, the demand for developers has risen exponentially. The top technology companies which hire full stack developers are Facebook, Amazon, Apple, Netflix, Google, Uber, Flipkart, Microsoft and more.The sites of each of these companies are web apps (excluding Apple and Microsoft), with complex frontend and backend systems. The frontend generally consists of React or Angular and the backend is a combination of various technologies. The DevOps part is also quite important in these web-apps as they handle millions of concurrent connections at once.SalariesThe salary of a beginner Frontend developer in India starts from Rs. 300,000($ 3980) per year in service-based companies to Rs. 12,00,000($ 15,971) per year in the top tech companies mentioned above. The salary of a Beginner Full-Stack developer in India starts at Rs. 4,50,000 ($ 5989) per year in service companies to Rs. 12,00,000($ 15,971) per year in top tech companies.The salary for an entry level Frontend developer in USA is $ 59,213 per year and for an entry level Full stack developer is $ 61,042 per year.Below are some sources for salaries:Front End vs Back End Developer SalaryFull Stack Developer SalariesWeb-developer SalariesTop regions where there is demandThere are plenty of remote and freelancing opportunities in web-development across the world. The two countries with most developers and top tech companies are USA and India. Silicon Valley, which is the San Francisco Bay Area, in Northern California, USA is the hub of technology companies.  The top city in India to start a developer job is the Silicon Valley of India – Bengaluru. The number of jobs is more than all the other cities combined and it also has a very good startup ecosystem. Almost all the big technology companies mentioned earlier and top Indian service companies are located in the city. After Bengaluru, the city where the greatest number of technology jobs are based in Hyderabad, followed by Chennai and then Pune.Entry PointsThe demand for web-developers is high and anyone with a passion for creating apps can become a web-developer. An Engineering degree is not mandatory to land a job as a web developer.  The most in-demand skill today and for the next 5 years is React and its ecosystem. So, if you know HTML, CSS, JavaScript and React, it is impossible to not get a job.Career PathwayMost people start as an intern Front-end developer or Intern Full-Stack developer and in many cases Intern Backend developer. Many companies directly hire junior Frontend/Backend/Full-stack developers.After that, the next step is the role of Senior Frontend/Backend/Full-stack developers. Many Frontend and Backend developers become full stack developers at this level, by learning additional technologies. Senior resources in Frontend/Backend/Full-stack can then go on to assume Team Lead roles. These people manage small teams in addition to being individual contributors.After this a professional can become a Project manager, whose main responsibility is managing the team. Another role is that of Technical Project Manager, who manages the team and also has hands-on knowledge in Technology. The last role at this level is that of a Software Architect, who handles and designs big projects and has to look at every aspect of the technology to create the enterprise app. Generally Full-stack developers are preferred in this role, as they need to know all technologies.The highest career milestone is CTO or Chief Technology Officer, who handles all the technology teams and makes all technology decisions in a Technology company.Job SpecializationThere are some Full stack development specializations which I see nowadays in the industry. Full-stack developers who work with React in the Frontend and Java in the Backend are in great demand. Similarly, developers who work with Angular in the Frontend and .NET in the backend are in great demand.How KnowledgeHut can helpAll these free resources are a great place to start your Front-end or Full-Stack journey. Besides these there are many other free resources on the internet, but they may not be organized and may not have a structured approach.This is where KnowledgeHut can make a difference and serve as a one-stop-shop alternative with its comprehensive Instructor-led live classes. The courses are taught by industry experts and are perfect for aspirants who wish to become Frontend or FullStack developers.Links for some of the popular courses & bootcamps by KnowledgeHut are appended below-Project-Based Full-Stack Development BootcampFront-End Development BootcampBack-End Development BootcampHTML5 & CSS3 TrainingHTML5 CSS3 & JavaScript TrainingReact TrainingNode.js Certification CourseDevOps TrainingConclusionThis completes our article on the Full stack developer journey by combining both the Frontend and backend roadmap. There are many people who become backend developers first by working on languages like Java and then go on to learn React to become full-stack developers.Again, many developers learn front-end development first with frameworks like React and then become full-stack developers by learning Node.JS. This path is easier for developers because both React and Node.JS use the same language which is JavaScript.We hope you have found this blog useful, and can now take the right path to become a full-stack developer. Good luck on your learning journey!
6572
How to Become a Successful Full Stack Web Develope...

The ResponsibilitiesFull-stack developer roles are... Read More

Angular: Add Service to Module Code Example

What are services in an Angular app?Services is a general term broadly categorized as values, functions, or features that our application may need. Services are made to reuse codes designed for a purpose.Angular services differentiate an element from its service so that the services can be re-used. This increases the modularity of the Angular application. Service in an Angular App can be almost anything, it can be an element, a component, or it can be a module used for some specific purpose.All services in Angular App are classes with a definite purpose. It serves a purpose and serves it well.Some of the very well-known services include:Logging Service: Used for logging in, logging out.Data Fetching: Fetching Data and representing it in a formatted way.Data Service: Fetching and receiving Data.Message Bus: Used for communicating through a set of shared interfaces.Tax Calculator: Calculating Tax by synchronizing with the current Law system.EMI calculator: Easy Monthly Instalment Calculator, mainly used in calculations related to Loan. Application Configuration: Common configuration throughout the application support.ReusabilityReusability is very important when building large-scale applications. Classes built for a common purpose should not be required to be built again and again. This even causes misinterpretation of certain important classes. We need to implement separation of concerns to segregate different classes used for different purposes. This can be achieved by Angular services.In Angular 13 Framework, the services are those objects that get instantiated a maximum of one time during the entire lifetime of any Angular application or Angular module.All the Angular Services contain many methods that maintain data throughout the lifetime of an application. Thus, it has become a medium to share various responsibilities within one or multiple components.Services and Dependency InjectionServices provide us with injectable features. The Angular App provides us the decorator @Injectable for creating a service. Classes thereby created can be injected into any other module or component by calling it through service provider modules.The two-step process for creating a service in Angular application is:Use @Injectable decorator to create a class.Use Dependency Injection to inject the class or register the class with the service provider.In Angular 13 Framework, one of the ways of performing DI – Dependency Injection is by using Service injection. Dependencies are services or objects of a class that helps in performing its function. Dependency injection or DI are design patterns in which a class demands dependencies from external sources rather than constructing them.Building and providing servicesLet us build a service for keeping Records of Employees:Step 1: Install Node.js:Angular requires Node.js version 14.X.X or later. You can download it from Nodejs.org.The latest Version is : node-v16.13.1-x64Install node.js once downloaded:Once you have installed Node.js on your system, open node.js command prompt.To check your version, run node -v in a terminal/console window.Step 2: Use npm to Install Angular CLIUse the following command to install Angular CLInpm install -g @angular/cli Ornpm install -g @angular/cli@latestOrJust go to Angular CLI official website https://cli.angular.io/You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are same for Windows and Mac.To check Node and Angular CLI version, use ng --version command.Step 3: Create an app called ngApp4ServiceSyntax:ng new app_nameC:\>ng new ngApp4Service It asks forWould you like to add Angular routing? YesWhich stylesheet format would you like to use?> CSS….Step 4: Generate Service via CLI:Syntax for creating a service:ng generate service [options]ng g service [options]Let us generate the required service: here we are going to create “Employee” Service.Go to the app folder and install the required service: “Employee”:Step 5: Edit the service ts file:Service to store Employee Data: employee.service.tsFile name: employee.service.tsimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class EmployeeService { public _empList: Array = [];       constructor() {           this._empList = [{name:'Jay Choudhury', city:'Ghaziabad'}];       }        returnEmpData(): Array {           return this._empList;       }        addEmpData(item: any): void {           this._empList.push(item);       }   }Step 6: Import the employee service:Import the service in the app.module.ts:import { BrowserModule } from '@angular/platform-browser';   import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';   import { FormsModule, ReactiveFormsModule } from '@angular/forms';   import { AppComponent } from './app.component';   import { EmployeeService } from './employee.service';   @NgModule({     declarations: [       AppComponent     ],     imports: [       BrowserModule, FormsModule, ReactiveFormsModule     ],     providers: [EmployeeService],     bootstrap: [AppComponent],     schemas: [NO_ERRORS_SCHEMA]   })   export class AppModule { }Step 7: Use the service: Employee:Edit: app.component.tsimport { Component, OnInit } from '@angular/core';   import { EmployeeService } from './employee.service';   @Component({       selector: 'app-root',         templateUrl: './app.component.html',         styleUrls : ['./app.component.css']         })   export class AppComponent implements OnInit {         public model: any = {};         public source: Array;         constructor(public service: EmployeeService) {               this.source = this.service.returnEmpData();               }          ngOnInit(): void { }          public submit(): void {               if (this.validate()) {                   this.service.addEmpData(this.model);                   this.reset();               }           }         public reset(): void {          this.model = {};      }          public validate(): boolean {                  let status: boolean = true;                  if (typeof (this.model.name) === "undefined") {                         alert('Name is Blank');                         status = false;                         return status;                        }                  else if (typeof (this.model.city) === "undefined") {                         alert('City is Blank');                         status = false;                         return status;                        }                  return status;           }    }Edit app.component.html:         Employee Form             Employee Name                       City                                           Employee Details                                         Employee's Name                     City                                   {{item.name}}                         {{item.city}}                                     Step 8: Run to check the service:Go to the app folder:C:\>ng serveRun at localhost:4200/We get the Employee Form.We can add more details for the employee, and see the result.Importance of ServicesAngular App provides Angular Services as re-usable components of the application. It uses @Injectable Decorator for building a Service. A service can be called through multiple components as a common element and shared for various purposes. This helps in avoiding repetitive work and improves the speed of app development.
4986
Angular: Add Service to Module Code Example

What are services in an Angular app?Services is ... Read More

How to Create Libraries for Angular Apps?

In this Article we are going to talk about Libraries in Angular 13.  We will be covering the following topics in the blog:Reusability with Angular Libraries:Here we introduce the idea of reusability and the concept of building libraries in Angular apps.Creating a New Library:Here we will walk through steps to generate a new library using the ng generate.Rebuilding an app using libraries:Here we walk through an example where we convert a portion of an existing Angular 13 app to a library and then use it.Publishing your library:Here we walk through publishing a library, keeping Ivy related features, version compatibility etc. in mind.SummaryAbout Angular 13:Angular 13 is the latest version of the Angular family. Angular applications are basically designed for Single Page Applications, where all controls are required in single-page architecture. Angular is an application-based design framework, which provides the Cross-Platform development environment for creating the most sophisticated Single Page Applications (SPAs). These SPAs are efficient enough for giving us a component to view the model environment, making it an MVC or MVVM application.Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App-like experience with high-performance. Angular has zero-step installation, making its up-gradation using modern web capabilities possible, even if offline. Angular has the capability of making a cross-platform Desktop App that can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP, and many other servers by giving the output in HTML-CSS format. This even optimizes the App for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command-Line tools, we can build and deploy Apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests making the applications made in Angular more stable.According to angular.io, some of the features worth mentioning are:1. DEVELOP ACROSS ALL PLATFORMSLearn one way to build applications with Angular and reuse your code and abilities to build apps for any deployment target. For web, mobile web, native mobile, and native desktop.  2. SPEED & PERFORMANCEAchieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering.Angular puts you in control over scalability. Meet huge data requirements by building data models on RxJS, Immutable.js, or another push model.3. INCREDIBLE TOOLINGBuild features quickly with simple, declarative templates. Extend the template language with your own components and use a wide array of existing components.  Get immediate Angular-specific help and feedback with nearly every IDE and editor. All this comes together so you can focus on building amazing apps rather than trying to make the code work.4. LOVED BY MILLIONSFrom prototype through global deployment, Angular delivers the productivity and scalable infrastructure that supports Google's largest applications.Reusability with Angular LibrariesA Library in Angular App is a reusable code that determines Angular components, services, or projects meant to be called by other projects. These projects are like a normal application. The only difference these have over Angular applications is that these projects cannot execute on their own. We need to import these projects to use them.We make libraries to solve some generic issues like the unified user interface or data presentation or data entry issues. Angular developers create these libraries for such general-purpose solutions. Later these libraries can be adapted in different applications for re-usage of the solution.An Angular Library can be built as an Angular application, later published as an npm package. These npm packages can be shared with different applications deploying the libraries.Libraries can be published as third-party libraries or Angular Team libraries.Some of the examples are:ReactiveFormsModule from the @angular/forms library is used to add reactive forms to an Angular app. We add this library package by using ng add @angular/forms and then importing the ReactiveFormsModule from the @angular/forms.To turn an Angular App into a progressive application we add the service worker library. This turns our code into a Progressive Web App (PWA).A very large and general-purpose library is the Angular Material. It is a library or a component that helps in constructing attractive, sophisticated, functional web app and reusable, and adaptable UI components.Creating a New LibraryLet us build a Library in Angular App step-by-step:Step 1: Install Node.js:Angular requires Node.js version 14.X.X or later. You can download it from Nodejs.org.Latest Version is: node-v16.13.1-x64Install node.js once downloaded:Once you have installed Node.js on your system, open node.js command prompt.To check your version, run node -v in a terminal/console window.Step 2: Use npm to Install Angular CLIUse the following command to install Angular CLInpm install -g @angular/cli Ornpm install -g @angular/cli@latestOrJust go to Angular CLI official website Angular.io.You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are the same for Windows and Mac.To check Node and Angular CLI version, use ng --version command.Step 3: Create an app called ngApp4LibrarySyntax:ng new app_name C:\>ng new ngApp4Library It asks forWould you like to add Angular routing? YesWhich stylesheet format would you like to use?> CSS ….Step 4: Generate Library via CLI:Syntax: for creating a Libraryng generate library [options] ng g library [options]Let us generate the required library: here we are going to create “my-lib” Library.Go to the app folder and install the required Library: “my-lib”:ng generate library my-lbThis will create a library project my-lib into our ngApp4library project.my-lib Library will contain library module, services, components, etc.Step 5: Edit the library ts file: Give a functionality to your libraryAs you can see our library has its own module, service, and component. We can add more components, services, directives, pipes, and modules as per our needs.The Library file that we need to edit is my-lib. It appears in the folder C:\Users\ISHU\Desktop -> ngApp4Library -> projects -> my-lib -> src -> lib. The file to be edited is:  my-lib.component.tsAdd the following code:import { Component, OnInit } from '@angular/core'; @Component({   selector: 'lib-my-lib',   template: `       Username:           Password:             Login   `,   styles: [   ] }) export class MyLibComponent implements OnInit {   constructor() { }   ngOnInit(): void {   } }Rebuilding an app using librariesBefore consuming the library, we need to build an Angular library.Here we will build the library for local (same application) usage.Then we will re-build the library for global (any application) usage.Creating a New Library1. Build the library and consume it in the same application:To build the library, we run the following command:ng build Here our library name is my-lib, thus the command we need is: ng build my-libThe command will generate the library dist folderNext step is to implement the library into our current project: ngApp4Library:For this step, we need to import this library in our main app (ngApp4Library).In app.module.ts import my-lib library module as shown: app.module.ts:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { MyLibModule } from 'my-lib'; @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     MyLibModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }Now, we simply add the my-lib library in the HTML file.Please note that the selector for the library used here is: lib-my-libTo know about the selector (lib-my-lib), we can check the file: ngApp4Library -> projects -> my-lib -> src -> lib->  my-lib.component.tsNow open and edit: app.component.html from the main App folder: ngApp4Library\src\app\ app.component.html: Now we can start our application from the Node.js command line as: ng serveOpen the favourite browser and type the default Angular app URL to check the output: localhost:4200/.2. Rebuild the library and consume it from some other application:We go through the following steps to implement the Library into another project:Step 1:To Re-build the library, we run the following command:ng build Here our library name is my-lib, thus the command we need is: ng build my-libThe command will generate the library dist folderNow, create a new Angular application: ngAppClient in a new command window. We need to let the library application run.ng new ngAppClientNow from the build, check the paths destined as “to”Here, the “to” part gives us the value: C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-libSo, now copy this path: “C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-lib”Next, we open the terminal of ngAppClient project and install this library with the following command into the ngAppClient project: npm i C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-libC:\Users\ISHU\Desktop>cd ngAppClientC:\Users\ISHU\Desktop\ngAppClient>npm iC:\Users\ISHU\Desktop\ngApp4Library\dist\my-libAfter installation of the library in the client application, we can import the library into the app.module.ts of the client app. After importing the library module, we can easily use those services, components, etc.To use the library:Open Client Project -> app.module.ts file and edit it to add the library:App.module.ts:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { MyLibModule } from 'my-lib'; @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     MyLibModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { } Now, we simply add the my-lib library in the client project app.component.html file.Please note that the selector for the library used here is: lib-my-libTo know about the selector (lib-my-lib), we can check the file: ngApp4Library -> projects -> my-lib -> src -> lib->  my-lib.component.tsAnd then open and edit: app.component.html from the client App folder: ngAppClient\ src\ app\ app.component.html: We can now start our client application for the Node.js command line as:ng serve.In case the Library project is running in the default port, 4200, we can change the port of the client app to 5200 by the following command:ng serve --port 5200Open the favorite browser and type the default Angular app URL to check the output: localhost:5200/.Publishing your libraryWe publish the library to make the library available on npm. For publishing the library, all we need to do is create a production build, and then run npm publish command from the library project’s dist directory.The Syntax is as follows:ng build --prod cd dist/ npm publishHere the Library project is ngApp4library, and the library is my-lib, so we run the following commands:ng build my-lib --prod cd dist/my-lib npm publishIf you have not published anything before, you will need to create an npm account first and log in into your npm account and then publish your library.The Purpose of Angular LibrariesAngular Libraries are very useful in case we want to re-use components, services, modules, etc. in our application. We just need to add the published library in our project, and that’s it, the components, modules, services, are all ready to be used in the application.To create a library, we generate it by “ng generate” command, built it by “ng build” command, publish by “npm publish” command. To use a library we install it by “ng i “ command.
5703
How to Create Libraries for Angular Apps?

In this Article we are going to talk about Librari... Read More