Search

What Is Deno, and Difference Between Deno & Node.js?

Deno is a JavaScript and TypeScript runtime based on the V8 JavaScript engine and the Rust programming language. It was created by Ryan Dahl, the original Node.js creator, and is geared toward productivity. Dahl made the announcement in 2018 during his talk "10 Things I Regret About Node.js."Deno could be viewed as the successor to Node.js among all the old and new server-side runtimes/frameworks.Architecture and inner workings:Deno considered a variety of topics, including security, when designing the architecture. Deno put a lot of thought into creating a clean and performant way of communicating with the underlying OS without leaking details to the JavaScript side. Deno communicates with the Deno backend from the V8 using message-passing. The backend is the Rust component that interacts with the event loop and thus with the OS. Deno is made possible by four technological advances: V8 TypeScript Tokio (event loop) Rust Core FeaturesList of Deno Features are: Out-of-the-box TypeScript support:TypeScript extends JavaScript with optional types that make large-scale application development easier. It is a superset of JavaScript and is maintained by Microsoft. Deno's runtime is built with TypeScript in mind, and Deno's standard modules are written in TypeScript as well. It provides more control over the types of your project. In contrast to Node.js, it provides first-class TypeScript support.Easy Installation:Deno is simple to install because it only requires one executable file. There is no need to install any additional libraries, dependencies, or set up a development environment. It only takes a few clicks to install it and begin developing.A More Modern and Complete Library:Deno seeks to provide a more complete and ready-to-use environment that facilitates and accelerates development. It provides a standard set of high-quality modules that have been reviewed by the core team. It makes use of modern JavaScript and Node.js lessons to provide a seamless runtime scripting environment.Decentralized Package Management: Deno does not have a package.json file or a large collection of node modules. It includes a package manager in the same executable that will fetch all resources for you. URLs are used to load modules into the application. This helps to eliminate the need for a centralised registry, such as npm for Node.js.Security:With Deno, a developer can grant scripts permission by using flags such as —allow-net and —allow-write. Deno provides a sandbox security layer via permissions. A program can only access the executable's permissions as specified by the user. You're probably wondering, "How will I know which flags I need to add to execute the server?" Don't worry; a message will appear in the console log asking you to add a specific flag. The module systemGood news for developers! There isn't even a package.json file! Unlike Node's NPM, Deno has its own package manager. As we all know, when you install a package using npm, all required dependencies must also be installed, which adds to the complexity.  Deno's decentralised module system performs admirably here. It includes some built-in tooling for gaining access to third-party modules. Third-party code or packages can be imported using HTTP URLs and a syntax familiar to modern JS and Angular. Packages are cached locally so that they do not need to be loaded on each run. However, there is a cache, so you only need to download packages and modules once. Here's an example: Create a file assertequals.ts and paste the following code in it. import { assertEquals } from "https://deno.land/std@0.100.0/testing/asserts.ts";  assertEquals(2 + 2, 4);  console.log('success!')  Run the above code using:  deno run -A assertequals.ts You will see Output as: Deno directly imports the assertEquals symbol (which happens to be a function in the Deno standard library) from a URL in this case. It's worth noting that the URL includes version information (std@0.100.0), making it simple to support multiple versions of the same package. Deno has a curated list of packages available at https://deno.land but you can import packages from any URL. Node.js vs. DenoHere are the key differences between Node.js and Deno. ES modules vs. CommonJS modules:Deno fully supports ES modules, so we can use imports in the same way that you would in React. For example, the ES module has two significant advantages over require: the node way of importing dependencies loads resources synchronously, whereas import is synchronous, which is more performant. You can also save memory by importing only the packages you require. Node uses the CommonJS standard: const module = require(‘module-name’)  Deno uses the standard EcmaScript modules:  import module from ‘https://some-repo/module-name.ts' Note that Deno requires fully qualified module names including the extension. Built-in Typescript compiler vs. external support:The typescript compiler is built into Deno by default; all you have to do is name your files with a .TS extension to use typescript in your code. Following that, you will require confirmation or installation. In Node, on the other hand, you must install a typescript update package. json, include a TS configuration file, and ensure that your modules have type support.Decentralized Packages:Deno eliminates the need for NPM packages and large Node modules folders. Packages are instead imported from the URL and cache to the hard drive. It means that the imported dependency is cached, and you won't have to download it again if you need to use it elsewhere.Security:Deno takes security seriously and prioritises it. Unlike Node, it executes the code in a sandbox, so our program does not have access to the file system, network, environment, variables, or the execution of other scripts by default. If we want to use these resources, we must request permissions or use the appropriate security flags when running our scripts.Browser API:Unlike Node, Deno has access to the browser API, which means you can use anything from the browser API without having to install any additional packages. You can, for example, use fetch right away. You must install the Node fetch package while in NodeJS. You have native access to window objectives, which lead to cleaner and fewer packaging ports.  Installing DenoDeno is compatible with macOS, Linux, and Windows. Deno consists of a single binary executable.  Using Shell (macOS and Linux):  curl -fsSL https://deno.land/x/install/install.sh | sh  Using PowerShell (Windows):  iwr https://deno.land/x/install/install.ps1 -useb | iex  Using Scoop (Windows):  scoop install deno  Using Chocolatey (Windows):  choco install deno  Using Homebrew (macOS):  brew install deno  Using Nix (macOS and Linux):  nix-shell -p deno  Build and install from source using Cargo:  cargo install deno --lockedI use Windows so, I installed Deno on my system with PowerShell using following command: iwr https://deno.land/x/install/install.ps1 -useb | iex Use the deno command to check the version installed and use the access the REPL (Read Evaluate Print Loop) Your first Deno appCreate a folder with name deno-dmo and c reate a file called index.ts in the application's root folder to serve as the Deno application's starting point. To make building and routing easier, you'll use Opine, which is an Express clone for Deno.  Deno differs from others in that there are no package managers for importing third-party libraries. You do this by entering the full URL of the library. Put that at the top of the index.ts file, and then create a simple web application. import { opine } from "https://deno.land/x/opine@2.0.0/mod.ts";  const app = opine();  app.get('/', (req, res) => {   res.send('Deno Sample');  });  app.listen(3000);  console.log('running on port 3000'); To run the application, open the terminal and type: deno run -A index.ts You can see the output in the terminal as running on port 3000. then go to http://localhost:3000 you should see Deno Sample on a blank page. The -A  is a development shortcut. Deno is completely locked down by default, so you'll need to pass arguments to the run command to allow access, such as —allow-net for networking and —allow-read for file system reading. The -A flag, in this case, allows everything, effectively disabling all security. Deno Runtime APIsWeb Platform APIs:Deno intends to use web platform APIs (such as fetch) rather than inventing new proprietary APIs where possible. These APIs generally adhere to the specifications and should be compatible with Chrome and Firefox implementations. Because of Deno's different security model, it makes sense to deviate from the specification slightly in some cases.Permission APIs:When you run the ‘deno’ command, the CLI grants you permissions. User code frequently assumes its own set of required permissions, but there is no guarantee that the set of granted permissions will match this during execution.In some cases, ensuring a fault-tolerant program necessitates a way for the program to interact with the permission system at runtime. Example: const desc1 = { name: "read", path: "/foo" } as const;  console.log(await Deno.permissions.query(desc1)); When you run the above code on PowerShell, you will see output as:  HTTP Server APIs:Native HTTP server APIs were introduced in Deno 1.9 and later, allowing users to build robust and performant web servers in Deno. The API attempts to leverage as many web standards as possible while remaining simple and straightforward. To accept requests, you must first listen for a connection on a network port. Deno.listen() is used to accomplish this: const server = Deno.listen({ port: 3000}); If there is a problem opening the network port, Deno.listen() will throw, so in a server sense, you should wrap it in a try... catch block to handle exceptions, such as the port already being in use. Web Storage API:Deno 1.10 added the Web Storage API, which allows you to store string keys and values. Persistent data functions similarly to a browser and has a storage limit of 10MB. LocalStorage persists data from execution to execution, whereas the global sessionStorage object only persists data for the current execution context.  Workers:Deno is compatible with the Web Worker API. Workers can be used to run code on multiple threads at the same time. Each Worker instance runs on a separate thread that is dedicated solely to that worker. Deno currently only supports module type workers; thus, when creating a new worker, the type: "module" option must be specified. The use of relative module specifiers in the main worker is only supported with the CLI option —location <href>. This is not a good option for portability. Instead, you can use the URL constructor and import.meta.url to quickly generate a specifier for a nearby script. Dedicated workers, on the other hand, have a location and this capability as a matter of course. Deploying Deno apps with Deno DeployDeno Deploy is an application deployer and a stripped-down runtime built on top of Deno. Deno Deploy only supports a subset of web APIs.  Let’s create a simple application and deploy our deno application using Deno Deploy: Step 1: Create a folder by the name deno-deploy-demo and create a file index.js in it. Step 2: Add the below code in the index.js file: addEventListener("fetch", (event) => {     const response = new Response ("Hello World!", {         headers: {"content-type": "text/plan"},     });     event.respondWith(response);  }); Step 3: Go to https://deno.com/deploy and create your account.  Step 4: Create a new project and name your project: Step 5: We have our project created, now add the project on your GitHub as a repository. For this article, I am considering that you have a GitHub account. Step 6: Now, go to the settings option and select Git. Step 7: Under the Git Integration part, select the repository you have created for the project on your GitHub account.  Step 8: Now, go down in the File part and click on the small arrow to deploy your project. You will see a page like this:  Step 9: Click on any of the link in the Domain Part to access your Deployed Application.  Should you be using Deno instead of Node.js? Deno's goal is to be an alternative to Node, not a replacement for it. I'd say that the vast majority of developers are satisfied with the way Node.js is evolving and aren't looking to change things up. Deno's emphasis on security, as well as the ability to bundle the entire codebase into a single file., It presents an excellent opportunity for Deno to become the go-to tool for JavaScript developers when it comes to creating utility scripts that would otherwise be written in languages such as Bash or Python. Those who are already using TypeScript or coming from other languages may find the transition easier, but Node.js developers will have no trouble switching from Deno to Node.js and back again. Deno, on the other hand, has an exciting advantage: Its module system is identical to client-side JavaScript. It implements many browser APIs, such as referencing a window object, setting event listeners, launching Web Workers, making remote server requests with the Fetch() API, and more. But is it time to ditch Node? Deno is a new project with a lot of potentials. It is based on Node.js's experience and hard lessons. It has many technical advantages over Node.js. It is built with a cutting-edge technology stack. The big question is whether it will replace JavaScript and Typescript as the primary backend runtime. I believe it is too early to tell, but it will be very interesting to see what happens. 

What Is Deno, and Difference Between Deno & Node.js?

10K
What Is Deno, and Difference Between Deno & Node.js?

Deno is a JavaScript and TypeScript runtime based on the V8 JavaScript engine and the Rust programming language. It was created by Ryan Dahl, the original Node.js creator, and is geared toward productivity. Dahl made the announcement in 2018 during his talk "10 Things I Regret About Node.js."

Deno could be viewed as the successor to Node.js among all the old and new server-side runtimes/frameworks.

Architecture and inner workings:

Deno considered a variety of topics, including security, when designing the architecture. Deno put a lot of thought into creating a clean and performant way of communicating with the underlying OS without leaking details to the JavaScript side. Deno communicates with the Deno backend fromthe V8 using message-passing. The backend is the Rust component that interacts with the event loop and thus with the OS. 

Deno is made possible by four technological advances: 

  • V8 
  • TypeScript 
  • Tokio (event loop) 
  • Rust 

Core Features

List of Deno Features are: 

Out-of-the-box TypeScript support:

TypeScript extends JavaScript with optional types that make large-scale application development easier. It is a superset of JavaScript and is maintained by Microsoft. Deno's runtime is built with TypeScript in mind, and Deno's standard modules are written in TypeScript as well. It provides more control over the types of your project. In contrast to Node.js, it provides first-classTypeScript support.

Easy Installation:

Deno is simple to install because it only requires one executable file. There is no need to install any additional libraries, dependencies, or set up a development environment. It only takes a few clicks to install it and begin developing.

A More Modern and Complete Library:

Deno seeks to provide a more complete and ready-to-use environment that facilitates and accelerates development. It provides a standard set of high-quality modules that have been reviewed by the core team. It makes use of modern JavaScript and Node.js lessons to provide a seamless runtime scripting environment.

Decentralized Package Management: 

Deno does not have a package.json file or a large collection of node modules. It includes a package manager in the same executable that will fetch all resources for you. URLs are used to load modules into the application. This helps to eliminate the need for a centralised registry, such as npm for Node.js.

Security:

With Deno, a developer can grant scripts permission by using flags such as —allow-net and —allow-write. Deno provides a sandbox security layer via permissions. A programcan only access the executable's permissions as specified by the user. You're probably wondering, "How will I know which flags I need to add to execute the server?" Don't worry; a message will appear in the console log asking you to add a specific flag. 

The module system

Good news for developers! There isn't even a package.json file! Unlike Node's NPM, Deno has its own package manager. As we all know, when you install a package using npm, all required dependencies must also be installed, which adds to the complexity.  

Deno's decentralised module system performs admirably here. It includes some built-in tooling for gaining access to third-party modules. Third-party code or packages can be imported using HTTP URLs and a syntax familiar to modern JS and Angular. Packages are cached locally so that they do not need to be loaded on each run. 

However, there is a cache, so you only need to download packages and modules once. Here's an example: 

Create a file assertequals.ts and paste the following code in it. 

import { assertEquals } from "https://deno.land/std@0.100.0/testing/asserts.ts"; 
assertEquals(2 + 2, 4); 
console.log('success!') 
Run the above code using: 
deno run -A assertequals.ts 

You will see Output as: 

Deno directly imports the assertEquals symbol (which happens to be a function in the Deno standard library) from a URL in this case. It's worth noting that the URL includes version information (std@0.100.0), making it simple to support multiple versions of the same package. 

Deno has a curated list of packages available at https://deno.land but you can import packages from any URL. 

Node.js vs. Deno

Here are the key differences between Node.js and Deno. 

ES modules vs. CommonJS modules:

Deno fully supports ES modules, so we can use imports in the same way that you would in React. For example, the ES module has two significant advantages over require: the node way of importing dependencies loads resources synchronously, whereas import is synchronous, which is more performant. You can also save memory by importing only the packages you require. 

Node uses the CommonJS standard: 

const module = require(‘module-name’) 
Deno uses the standard EcmaScript modules: 
import module from ‘https://some-repo/module-name.ts' 

Note that Deno requires fully qualified module names including the extension. 

Built-in Typescript compiler vs. external support:

The typescript compiler is built into Deno by default; all you have to do is name your files with a .TSextension to use typescript in your code. Following that, you will require confirmation or installation. In Node, on the other hand, you must install a typescript update package. json, include a TS configuration file, and ensure that your modules have type support.

Decentralized Packages:

Deno eliminates the need for NPM packages and large Node modules folders. Packages are instead imported from the URL and cache to the hard drive. It means that the imported dependency is cached, and you won't have to download it again if you need to use it elsewhere.

Security:

Deno takes security seriously and prioritises it. Unlike Node, it executes the code in a sandbox, so our programdoes not have access to the file system, network, environment, variables, or the execution of other scripts by default. If we want to use these resources, we must request permissions or use the appropriate security flags when running our scripts.

Browser API:

Unlike Node, Deno has access to the browser API, which means you can use anything from the browser API without having to install any additional packages. You can, for example, use fetch right away. You must install the Node fetch package while in NodeJS. You have native access to window objectives, which lead to cleaner and fewer packaging ports.  

Installing Deno

Deno is compatible with macOS, Linux, and Windows. Deno consists of a single binary executable. 

Using Shell (macOS and Linux): 
curl -fsSL https://deno.land/x/install/install.sh | sh 
Using PowerShell (Windows): 
iwr https://deno.land/x/install/install.ps1 -useb | iex 
UsingScoop(Windows): 
scoop install deno 
UsingChocolatey(Windows): 
choco install deno 
UsingHomebrew(macOS): 
brew install deno 
UsingNix(macOS and Linux): 
nix-shell -p deno 
Build and install from source usingCargo: 
cargo install deno --locked

I use Windows so, I installed Deno on my system with PowerShell using following command: 

iwr https://deno.land/x/install/install.ps1 -useb | iex 

Use the deno command to check the version installed and use the access the REPL (Read Evaluate Print Loop) 

Your first Deno app

Create a folder with name deno-dmo and c reate a file called index.ts in the application's root folder to serve as the Deno application's starting point. To make building and routing easier, you'll use Opine, which is an Express clone for Deno. 

 

Deno differs from othersinthat there are no package managers for importing third-party libraries. You do this by entering the full URL of the library. Put that at the top of the index.ts file, and then create a simple web application. 

import { opine } from "https://deno.land/x/opine@2.0.0/mod.ts"; 
const app = opine(); 
app.get('/', (req, res) => { 
 res.send('Deno Sample'); 
}); 
app.listen(3000); 
console.log('running on port 3000'); 

To run the application, open the terminal and type: 

deno run -A index.ts 

You can see the output in the terminal as running on port 3000then go tohttp://localhost:3000you should seeDeno Sampleon a blank page. 

The -A is a development shortcut. Deno is completely locked down by default, so you'll need to pass arguments to the run command to allow access, such as —allow-net for networking and —allow-read for file system reading. The -A flag, in this case, allows everything, effectively disabling all security. 

Deno Runtime APIs

Web Platform APIs:

Deno intends to use web platform APIs (such as fetch) rather than inventing new proprietary APIs where possible. These APIs generally adhere to the specifications and should be compatible with Chrome and Firefox implementations. Because of Deno's different security model, it makes sense to deviate from the specification slightly in some cases.

Permission APIs:

When you run the deno command, the CLI grants you permissions. User code frequently assumes its own set of required permissions, but there is no guarantee that the set of granted permissions will match this during execution.

In some cases, ensuring a fault-tolerant programnecessitates a way for the program to interact with the permission system at runtime. 

Example: 

const desc1 = { name: "read", path: "/foo" } as const; 
console.log(await Deno.permissions.query(desc1)); 

When you run the above code on PowerShell, you will see output as:  

HTTP Server APIs:

Native HTTP server APIs were introduced in Deno 1.9 and later, allowing users to build robust and performant web servers in Deno. 

The API attempts to leverage as many web standards as possible while remaining simple and straightforward. 

To accept requests, you must first listen for a connection on a network port. Deno.listen() is used to accomplish this: 

const server = Deno.listen({ port: 3000}); 

If there is a problem opening the network port, Deno.listen() will throw, so in a server sense, you should wrap it in a try... catch block to handle exceptions, such as the port already being in use. 

Web Storage API:

Deno 1.10 added the Web Storage API, which allows you to store string keys and values. Persistent data functions similarly to a browser and has a storage limit of 10MB. LocalStorage persists data from execution to execution, whereas the global sessionStorage object only persists data for the current execution context.  

Workers:

Deno is compatible with the Web Worker API. 

Workers can be used to run code on multiple threads at the same time. Each Worker instance runs on a separate thread that is dedicated solely to that worker. 

Deno currently only supports module type workers; thus, when creating a new worker, the type: "module" option must be specified. 

The use of relative module specifiers in the main worker is only supported with the CLI option —location <href>. This is not a good option for portability. Instead, you can use the URL constructorand import.meta.url to quickly generate a specifier for a nearby script. Dedicated workers, on the other hand, have a location and this capability as a matter of course. 

Deploying Deno apps with Deno Deploy

Deno Deploy is an application deployer and a stripped-down runtime built on top of Deno. Deno Deploy only supports a subset of web APIs.  

Let’s create a simple application and deploy our deno application using Deno Deploy: 

Step 1: Create a folder by the name deno-deploy-demo and create a file index.js in it. 

Step 2: Add the below code in the index.js file: 

addEventListener("fetch", (event) => { 
  const response = new Response ("Hello World!", { 
    headers: {"content-type": "text/plan"}, 
  }); 
  event.respondWith(response); 
}); 

Step 3: Go tohttps://deno.com/deployand create your account.  

Step 4: Create a new project and name your project: 

Step 5: We have our project created, now add the project on your GitHub as a repository. For this article, I am considering that you have a GitHub account. 

Step 6: Now, go to the settings option and select Git. 

Step 7: Under the Git Integration part, select the repository you have created for the project on your GitHub account.  

Step 8: Now, go down in the File part and click on the small arrow to deploy your project. You will see a page like this:  

Step 9: Click on any of the link in the Domain Part to access your Deployed Application.  

Should you be usingDenoinstead of Node.js? 

Deno's goal is to be an alternative to Node, not a replacement for it. I'd say that the vast majority of developers are satisfied with the way Node.js is evolving and aren't looking to change things up. 

Deno's emphasis on security, as well as the ability to bundle the entire codebase into a single file., It presents an excellent opportunity for Deno to become the go-to tool for JavaScript developers when it comes to creating utility scripts that would otherwise be written in languages such as Bash or Python. 

Those who are already using TypeScript or coming from other languages may find the transition easier, but Node.js developers will have no trouble switching from Deno to Node.js and back again. 

Deno, on the other hand, has an exciting advantage: 

  • Its module system is identical to client-side JavaScript. 
  • It implements many browser APIs, such as referencing a window object, setting event listeners, launching Web Workers, making remote server requests with the Fetch() API, and more. 

But is it time to ditch Node? 

Deno is a new project with a lot of potentials. It is based on Node.js's experience and hard lessons. It has many technical advantages over Node.js. It is built with a cutting-edge technology stack. The big question is whether it will replace JavaScript and Typescript as the primary backend runtime. I believe it is too early to tell, but it will be very interesting to see what happens. 

Abhresh

Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

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