Course Discount

Search

7 Things to Keep in Mind Before Your Next Web Development Interview

Websites are an integral component of any business. According to research by Techjury, there are approximately 4.3 billion internet users in the world, which makes the internet the single largest source for an audience. Organizations have identified this factor, and every business today has a website that represents them online. In fact, many companies, like ecommerce stores and food and beverage companies, for example, make their largest profits directly from their website. The requirement for website development, revamping and maintenance makes web developers sought-after candidates for every company. As a web developer, your options are many, and by regularly upskilling yourself, you can ensure a lucrative career. Before you attend your next interview, make sure to go through interview questions and answers online to be prepared. In this article, we cover seven tips for web developers to crack their next interview. 1. Learn how to design In most companies, design and development are handled by different teams, and rightly so since they are two different disciplines that require a different skill set. The former is in the creative field, and the latter is technical. However, a candidate who can handle both is always going to be preferred. As a developer, you need to know the basics of design, the rules of UI and UX, and understand brand guidelines. These basic design skills will help you be more involved in the project and be a plus point to crack your next interview.  2. Be proficient in basic languages Every web developer needs to have a strong grasp on the ground level languages: HTML, CSS, PHP and JavaScript. Whether you develop on WordPress or code in Angular, your knowledge on these four languages will be tested. Prepare by going through knowledge base articles for each of these and looking for interview questions online, especially JavaScript interview questions because a lot of companies look for animations that are triggered through JavaScript. 3. Learn multiple platforms Technology is ever-evolving. Make it a point to stay updated and learn new languages on a regular basis. Many websites and web apps today are built on different platforms: AngularJS, Python, React, Django, etc. Knowing more than just the basic languages will give you an edge over other candidates and pave the way for faster career growth. 4. Learn the basics of editing tools We have already discussed how important it is to add design as a skill to your portfolio. One way to do this would be to learn how to use editing tools such as Photoshop and Illustrator. This will also reduce your dependency on the design team whenever you need basic design edits like resizing or recolouring of images or layouts. Not only will you be able to complete projects faster, but you will also add bonus skills to your resume that interviewers pick up on.  5. Create an Online PortfolioThe best resume for a web developer is a website! If you can create a visually stunning website that is also agile, you can impress interviewers just by showcasing it. An online portfolio is a great way to show in real-time what you’re capable of, and also to showcase all your previous projects. It also helps potential employers find you online.  6. Be prepared to create a mock website Companies nowadays place a premium on seeing you walk the talk. Rather than asking you a bunch of questions, they give you a single page design and ask you to develop it at the interview. There usually aren’t any restrictions and interviewers let you choose the language and platform (unless the interview is for a specific language). Go into the interview prepared for this scenario by deciding beforehand what your strengths are and what platform you can complete this task on within the fastest time possible.  7. Relax, there are plenty of opportunities We began this article by giving you an idea of how much in demand web developers are. With many start-ups springing up and companies constantly revamping their websites, there are going to be numerous opportunities for you to land a well-paying web developer job. You can also look for freelance projects online on websites like Fiverr. Ace your next web development interview These are just a few suggestions of the key areas where every web developer must become proficient. With stiff competition in today's world, mastering just one skill is never enough. Fortunately, there are a plethora of online courses and articles that will help you prepare and bag a career-defining web development job.
Rated 4.0/5 based on 13 customer reviews

7 Things to Keep in Mind Before Your Next Web Development Interview

7K
7 Things to Keep in Mind Before Your Next Web Development Interview

Websites are an integral component of any business. According to research by Techjurythere are approximately 4.3 billion internet users in the world, which makes the internet the single largest source for an audience. Organizations have identified this factor, and every business today has a website that represents them online. In fact, many companies, like ecommerce stores and food and beverage companies, for example, make their largest profits directly from their website. 

The requirement for website development, revamping and maintenance makes web developers sought-after candidates for every company. As a web developer, your options are many, and by regularly upskilling yourself, you can ensure a lucrative career. Before you attend your next interview, make sure to go through interview questions and answers online to be prepared. In this article, we cover seven tips for web developers to crack their next interview. 

1. Learn how to design 

In most companies, design and development are handled by different teams, and rightly so since they are two different disciplines that require a different skill set. The former is in the creative field, and the latter is technical. However, a candidate who can handle both is always going to be preferred. As a developer, you need to know the basics of design, the rules of UI and UX, and understand brand guidelines. These basic design skills will help you be more involved in the project and be a plus point to crack your next interview. 

 2. Be proficient in basic languages 

Every web developer needs to have a strong grasp on the ground level languages: HTML, CSS, PHP and JavaScript. Whether you develop on WordPress or code in Angular, your knowledge on these four languages will be tested. Prepare by going through knowledge base articles for each of these and looking for interview questions online, especially JavaScript interview questions because a lot of companies look for animations that are triggered through JavaScript. 

3. Learn multiple platforms 

Technology is ever-evolving. Make it a point to stay updated and learn new languages on a regular basis. Many websites and web apps today are built on different platforms: AngularJS, Python, React, Django, etc. Knowing more than just the basic languages will give you an edge over other candidates and pave the way for faster career growth. 

4. Learn the basics of editing tools 

We have already discussed how important it is to add design as a skill to your portfolio. One way to do this would be to learn how to use editing tools such as Photoshop and Illustrator. This will also reduce your dependency on the design team whenever you need basic design edits like resizing or recolouring of images or layouts. Not only will you be able to complete projects faster, but you will also add bonus skills to your resume that interviewers pick up on. 

 5. Create an Online Portfolio

The best resume for a web developer is a website! If you can create a visually stunning website that is also agile, you can impress interviewers just by showcasing it. An online portfolio is a great way to show in real-time what you’re capable of, and also to showcase all your previous projects. It also helps potential employers find you online. 

 6. Be prepared to create a mock website 

Companies nowadays place a premium on seeing you walk the talk. Rather than asking you a bunch of questions, they give you a single page design and ask you to develop it at the interview. There usually aren’t any restrictions and interviewers let you choose the language and platform (unless the interview is for a specific language). Go into the interview prepared for this scenario by deciding beforehand what your strengths are and what platform you can complete this task on within the fastest time possible. 

 7. Relax, there are plenty of opportunities 

We began this article by giving you an idea of how much in demand web developers are. With many start-ups springing up and companies constantly revamping their websites, there are going to be numerous opportunities for you to land a well-paying web developer job. You can also look for freelance projects online on websites like Fiverr. 

Ace your next web development interview 

These are just a few suggestions of the key areas where every web developer must become proficient. With stiff competition in today's world, mastering just one skill is never enough. Fortunately, there are a plethora of online courses and articles that will help you prepare and bag a career-defining web development job.

KnowledgeHut

KnowledgeHut

Author

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

Join the Discussion

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

Suggested Blogs

How to Read files with Node.js?

In this tutorial, we will explore different ways we can read files in Node.js.  In software development, reading files is a regular part of the job. However, this simple process very often becomes complicated and tedious. Fortunately, that's not the case in Node.js. Node.js provides a built-infile system(fs) module, to carry out file operations. Before we start, let us make sure we have the basic prerequisites. You will need to ensure you have: Node.js  Code Editor (Ex. VS Code, Atom) For this tutorial, my environment setup includes: Node.js - v12.16.1 Code Editor - VS Code fs module fs module is a built-in module in the Node.js. You do notnecessarily need to install it.  The fs module supports both Synchronous and Asynchronous function calls. Getting started I am assuming you have installed the NodeJS. Create a new directory node-fs.  Create 2 files inside the node-fs, data.txt and index.js. Paste the dummy data in the data.txt.Lorem ipsum dolor sit amet, consecteturadipiscingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Open this directory in the code editor. From the index.js, we will read the test.txt.  Read file Synchronously using readFileSync The readFileSync is a synchronous method to read a file. Syntax fs.readFileSync(path[, options]) pathfilepath options encoding string or buffer Default null flag string DefaultrOpen index.js in the Code Editor. Paste the below code.// import the fs module const fs = require("fs"); // read file synchronously const readData = fs.readFileSync("./data.txt"); console.log(readData);Open the terminal or cmd in the node-fs directory and run the below command.$ node index.js It has returned the content in the buffer format. The readFileSync by default returns the content in the Buffer format.To get the content in normal string format, we need to pass the utf8 encoding as a parameter.Change the code.// import the fs module const fs = require("fs"); // read file synchronously const readData = fs.readFileSync("./data.txt", "utf8"); console.log(readData);run it.$ node index.jsLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Read file Asynchronously using readFileAsynchronous methods are great when you don’t want to wait for a process to complete.  fs module provides an asynchronous method to read a file. It returns a callback.Syntaxfs.readFileSync(path[, options], callback)pathfilepathoptionsencoding string or buffer Default nullflag string Defaultrcallback functionerr Errordata string | BufferSyntax is similar tothe synchronous method except it returns a callback function.// import the fs module const fs = require("fs"); // read file asynchronously fs.readFile("./data.txt", "utf8", (err, data) => {     if (!err) {         console.log(data);     } else {         console.error("Something went wrong while reading the file.");     } });Run the code.$ node index.jsLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Read file using Stream Reading file using fs.readFileis an ideal way if the file size is less. If the size is huge, the read will consume the complete Memory and you may find your system hanging. In such scenarios, Stream is the best option. This breaks the file into small chunks of data and sends a piece at a time. In this way, the system can continue with other tasks without allocating the complete memory to it.   Let us code and understand. Node.js provides a createReadStreammethod to stream the file. createReadStreamreturns a fs.ReadStreamobject. The readStream events like data, end, or error. To read the file, we have to listen to these events.  The data event will return the content of the file in chunks.  The end event will notify that, there is no data left in the file to read. The error event returns an error. // import the fs module constfs = require("fs");  // read file using stream const streamRead = async () => {  return new Promise((resolve, reject) => {  try {  // create a read stream const streamRead = fs.createReadStream("./data.txt", {  encoding:"utf8",        });  // listen to data event streamRead.on("data", (data) => {  console.log(data);        });  // listen to end event  stream Read.on("end", () => {  resolve("File read complete");        });  // listen to error event  streamRead.on("error", (error) => {  throwError(  "Something went wrong while streaming the file.",  error.message          );        });      } catch (error) {  reject(error);      }    });  };  streamRead().then((res, err) => {  if(!err) console.log(res);  elseconsole.error(err);  }); Run the code.$ node index.jsLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. File read completeExperiment time! For the purpose of the experiment, I created a file of 20MB to check the performance of readFileSync, readFileand createReadStream.  The average memory consumption of VS Code is 600-700MB in my machine. This is a screenshot before running any of the commands. readFileSync Check the screenshot. This operation took 373MB and it went on to upto ~450MB. readFile (Asynchronous)Check the screenshot. This operation took 506MB and it went on to upto ~600MB.createReadStream Check the screenshot. This operation took 287MB and it reached upto ~300MB.  Conclusion Node.js provides multiple methods to read a file. It completely depends on the file size and the requirement, which method to choose. From our performance tests, streaming turns out to be the most efficient method to use.  The performance may vary from machine to machine and file size. One must note that what we have demonstrated is just for the sake of a demo, so this must not be taken to be the final words. There are other npm packages available for file system, for example,fs-extra.  Hope this tutorial has helped. Taking a formal training course in Node.js would be a great way to fast-track your career.  Happy coding!
Rated 4.0/5 based on 34 customer reviews
5906
How to Read files with Node.js?

In this tutorial, we will explore different ways w... Read More

Essential Angular 9 development cheat sheet

Introduction to Angular Angular is a front-end web-development framework and platform that is used to build Single-page web Applications (or SPAs) using TypeScript as the primary programming language. Angular is itself written in TypeScript. Angular is an opinionated framework which means that it specifies a certain style and establishes certain rules that developers need to , learn, follow and adhere to while developing apps with Angular, therefore you need to learn Angular and the various modules, components, tools that are used and that make up an Angular app. There are way too many versions of Angular that you hear about and as a beginner, it is likely that may get confused with so many different versions out there for the same framework. There are versions like AngularJS, Angular 2, Angular 4, Angular 5, Angular 6, Angular 7, Angular 8 and now Angular 9 that you may have heard of. Too many versions, right? Well, in reality, there are just two different frameworks - AngularJS and Angular. AngularJS was the initial release and was called as AngularJS. It was the JavaScript-based web development framework which was first released in 2010 and is maintained by Google. Later, in September 2016, Angular 2 was announced which was a complete rewrite of the whole framework using TypeScript which is a super-set language of JavaScript. Since modern browsersdo not understand TypeScript, a TypeScript compiler or transpiler is required to convert the TypeScript code to regular JavaScript code. In this article, we will talk about everything about Angular that you can use as a quick reference guide. We will go through the core concepts, commands, utilities, etc. The Angular CLI Angular CLI or the command-line interface is a very powerful and sophisticated tool that allows you to perform a lot of actions in an Angular project by using simple commands. From scaffolding a brand-new Angular project to building the project for production, the CLI takes care of everything.  CLI also allows you to debug the application during development locally using a development server that monitors the source files for changes and when you change any of the files, it automatically recompiles the source code files and refreshes the app in the browser. Pretty neat! You can use the CLI tool directly in a command shell, or indirectly through an interactive UI such as Angular Console. Let’s have a look at some of the most common ways we use the Angular CLI. ng helpGives you options to get help about any command ot utility.ng versionPrints the version info of the currently installed CLI.ng new   Generates a new Angular project with the provided name.ng serveSpins up the local development server and launches the web app locally in the browser. The command takes more parameters like port and open. The server automatically rebuilds the app and reloads the page when you change any of the source files.ng buildComplies and builds the Angular app into a directory that can be deployed on the web server.ng generateUsed to generate modules, services, components, classes, providers, pipes, etc.Angular Component Lifecycle An Angular app is composed of components. Each component can contain more components which essentially makes an Angular app a tree of components. A component is made up of an HTML template, a typescript class and a stylesheet file. These three pieces together form an Angular component. Each component in Angular has a lifecycle which is managed by Angular itself.  Angular creates it, renders it, creates and renders it’s children, checks it when it’s data-bound properties change, and destroys it before removing it from the DOM. Angular allows you to hook into significant lifecycle events using hooks. Here are these hooks and their brief significancengOnChangesThis hook is executed before the content is processed or child views are loaded. It is also executed when the input properties of the component change.ngOnInitThis hook is used to initialize data in a component. It is called after input values are set and the component is initialized and it is executed only once.ngDoCheckThis hook is called when any change detection runs are made.ngAfterContentInitThis hook is called after ngOnInit when the component's or directive's content has been initialized.ngAfterContentCheckedThis hook is called every time the ngDoCheck is called.ngAfterViewInitThis hook is called after Angular initializes component’s and child components’ content.ngAfterViewCheckedThis hook is after every check of the component's views and child views.ngOnDestroyThis hook is called once right before the component is destroyed. This can be used to clean up memory and release allotted resources and subscriptions.Interpolation Interpolation is a way to use the properties in the component’s TypeScript class within the HTML template. Interpolation has a very simple syntax. Here is an example. Consider the following property of string type in the component’s TS class. company_name: string = "KnowledgeHut" The same value can be used in the HTML template using the following interpolation syntax. {{ company_name }} The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. Interpolation can also be used to concatenate strings, or perform simple mathematical operations right within the template. The evaluated result is rendered on the page. An example - name: string = "KnowledgeHut";  age: number = 25; {{ name + " is " + age + " years old today!" }} Another example -  number1: number = 22;  number2: number = 23;  {{ "Sum of "  + number1 + " and " + number2 + " is " + (number1 + number2) }} The same technique can also be used while specifying the values of properties. Here is an example.  Clearly, using property binding is much readable and recommended syntax if you intend to use the values of component properties in the template. Bindings in Angular Binding in Angular is used to define values of HTML properties and events using class members.  Here are a few examples of property binding in Angular.  In the above snippet, the title property is bound to a variable called company_name in the template. The same property needs to exist in the component’s typescript class, otherwise you will get an error. Similarly, you can bind to any properties exposed by HTML. Here is another example.  The placeholder_text property needs to exist in the component’s class. You can also bind events to methods in Angular. Most HTML elements have events that they emit when certain conditions are met. Binding methods to these events allow you to perform an action in your code. For example, executing a method on the click of a button is the most common use-case of event binding. Here is a code snippet for the same.  In the above code snippet, you can see that the click event is bound to a method called sendFOrmData(). Whenever the user clicks on the button, the function will be executed. Keep in mind that the sendFormData() method needs to be a member function inside the TypeScript class of the component otherwise you will run into errors. The most popular and powerful feature of Angular is two-way binding. With the help of two-way binding, when data changes in the component, it’s immediately reflected in the template. You need to use the ngModel directive with the special binding syntax to use two-way binding. Here is an example.   The name you entered is {{ username }}! Using the above code snippet, if you type in some text in the input field, the value of the username property will change as you type which in turn will update the value in the HTML template as well. All of this happens in real-time. Structural Directives There are two structural directives in Angular - NgFor and NgIf. The ngIf directive is used to add or remove an HTML element from the DOM completely based on a certain condition. The value passed to ngIf should either be a boolean value or should be an expression that evaluates to a boolean value. Here is an example.  In the above snippet, the showButton property is used to decide if the button will be displayed on the page or not. Do not confuse ngIf with the hidden HTML property. The hidden property only hides the HTML element, which ngIf completely removed it from the DOM. Another structural directive is used to render HTML elements on the page based on an array or iterable. Here is an example. users: any[] = [{  "name": "Bob"  }, {  "name": "Alice"  }, {  "name": "Tabor"  }, {  "name": "Mock"  }];     {{ user.name }}  If you execute the above code snippet, you will see a list rendered out on the page with the data based on the array. If you make changes to the array, the list will be updated automatically. Pipes and Services Pipes and services are also TypeScript classes just like the component classes. The only difference is the functionality that they offer. They are marked differently by using the decorators. @Component({...})  class AppComponent() { } This declares that the class is a component and also provides metadata about the component. @Pipe({...})  class MyPipe() { } This declares that the class is a pipe and provides metadata about the pipe. Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. They are all available for use in any template. Here is how you would use a pipe in Angular number1: number = 12.927;  {{ number1 | number:"1.2-2"}} // prints 12.93  @Injectable()  class MyService() { } This declares that the class contains dependency injectors, this means the data provided by the injector should be injected into the constructor when creating an instance of this class. Basically, this marks the class as a service to be used by other classes. To create a pipe, you need to use the following CLI command. ng generate pipe  Similarly, to create a service, you need to execute the following CLI command. ng generate service  Component Inputs and Output Angular is all about components that have to interact with one another. Inputs and Outputs are used to allow interaction between two components. Inputs allow a component to receive some data from the parent component and outputs allows the component to send some data outside the component back to the parent component. So inputs and outputs are used to implement parent-child interaction within components.  Let’s have a look at how we can allow a component to receive an input. The key here is using the @Input decorator. @Input() username: string; The above code snippet is added to the component’s TypeScript class. Now, the component can accept an input called “username” as shown below.  The value “KnowledgeHut” can now be accessed within the component using the username property. The other direction of communication is from child to parent. In this case, the child emits some data using an event. The parent subscribes to this event using event binding and receives the data. Here is an example. Inside the child component - @Output() onUsernameChange = new EventEmitter(); To emit the event, this.onUsernameChange.emit("KnowledgeHut"); That’s all in the child component. Here is how the parent used the child component with outputs.  Reactive Forms in Angular The Reactive approach of form building uses the classes like FormBuilder, FormGroup, FormControl, Validators, etc. We define the structure of the form using a form builder and then bind each form element to a form control. This approach is different from template-driven forms where we use ngModel directive to bind input fields to corresponding model properties. Here is how you would define a simple form with two input fields, one for the email and another one for the password. this.myGroup = new FormGroup({  email: new FormControl('john@doe.com'),  password: new FormControl('')  }); Next, we need to bind the form and the input fields as shown below.     Email:     Password:   This approach allows you to define Validators on individual form controls and on the form as well. The Angular Router Angular router is one of the most powerful modules in Angular which allows navigation within an Angular application. It takes care of lazy-loading components as and when required.  Here is an example of how you would define routes for an Angular app using the RouterModule. const routes: Routes = [{  path: '', redirectTo: 'home', pathMatch: 'full'  }, {  path: 'home',  component: HomeComponent  }, {  path: 'login', component: LoginComponent  }, {  path: 'myblogs', component: MyblogsComponent  }, {  path: 'profile/:id', component: ProfileComponent  }, {  path: '**', redirectTo: 'home'  }];  const routing = RouterModule.forRoot(routes); In the template, you need to use the RouterOutlet directive to load the component in a placeholder based on the URL. The Angular Router takes care of loading and unloading components in the placeholder RouterOutlet.   The routerLink directive can be used to navigate to a desired router. It creates a link to a different view based on a route instruction consisting of a route path, required and optional parameters, query parameters, and a fragment.    To navigate to a root route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the ../ prefix. Auth Guards Auth Guards in Angular are the way to prevent unauthorized access to your routes. They work very well in combination with the Angular Router. It secures your routes. Let’s have a look at an example. Consider the following route definition. const routes: Routes = [{  path: '', redirectTo: 'home', pathMatch: 'full'  }, {  path: 'home',  component: HomeComponent  }, {  path: 'login', component: LoginComponent  }, {  path: 'myblogs', component: MyblogsComponent, canActivate: [AuthGuard]  }, {  path: 'profile/:id', component: ProfileComponent  }, {  path: '**', redirectTo: 'home'  }]; As you can see, we have defined a canActivate property on a route and set its values as an array with the AuthGuard as the only element. Basically, you can have multiple auth guards for your routes but for now, we only have one. Here is how you can create the guard. ng generate guard AuthGurard This generates a new guard typescript file and it has a function defined inside of it. All you need to do is implement the function and return true or false based on the user’s state. If the guard returns true for the user, the route access if grant, else not. Here is an example implementation of the function, canActivate. canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean {        return new Promise((resolve, reject) => {  // return or resolve with true or false        }  } Build the App The Angular CLI allows you to build the app.  ng build The above command compiles the project and generates the final build inside the dist folder. You can however customize the build environment using the --prod flag. You can also change the build destination folder using the --outputPath flag. The following command is another simple example. ng build --prod --outputPath=myBuildFolder There are a few more flags available. prod outputPath localize aot baseHref buildOptimizer index verbose optimization Conclusion Angular may seem daunting at first but with steady learning and practicing, it becomes easy to understand and implementation of complex concepts seems simple. It offers a lot of tools, utilities and external packages to build amazing applications. Some of the most common external packages for Angular are -  NgxBootstrap Angular Material Ng2-Charts Ngx-Text-Editor NgxDataTable Use this cheat sheet to quickly look for help or use it as a reference. Check Angular docs for more info: https://angular.io/docs 
Rated 4.0/5 based on 34 customer reviews
6442
Essential Angular 9 development cheat sheet

Introduction to Angular Angular is a front-end we... Read More

Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email in Node.js using the nodemailer npm package.For the email provider, we are going to use Sendinblue. Prerequisites Node.js (>v6.0.0 for nodemailer module) Code Editor (For Ex. VS Code, Atom) An account in SendinblueStart by creating a free account in Sendinblue. A Sendinblue free account offers 300 mails/day. Its setup is easy and straightforward. An introduction to Nodemailer Nodemailer, an open source project started in 2010, is annpm module for Node.js applications to send emails. Today, nodemailer is a de facto to send an email in Node.js. Highlights of Nodemailer It is a single module with zero dependencies  It supports HTML Content  Allows you to easily add attachments to messages Supports SMTP as default transport method; other supported transport methods are SES, Sendmail, Stream. OAuth2 authenticationGetting Started For this tutorial, I am using Nodejs v12.16.1 and VS Code as the Code Editor. Create a new directory nodemailer-example.  Open the terminal or cmd inside the directory and run  $ npminit --yes It will initialize a new npm package. Install dependencies Following different npm packages, we are going to use in this project. nodemailer – To send the mail express – To create APIs cors – To resolve the cross originresource sharing body-parser – To extract the body from the API request dotenv – To access the environment variables $ npm install --save nodemailer express cors body-parser dotenv This command will install all the dependencies. Now, we can start the coding. Project Structure Open the nodemailer-example in the code editor and create the following folders and files in it; not to worry, I will be explaining all the files and commands involved.  nodemailer-example    |- routes      |- mail-api.js    |- src      |- send-mail.js    |- template      |- mail.html    |- .env    |- index.js Sendinmail Setup Login to your Sendinmail account. From the top-left menu, select SMTP & API. Select the SMTP tab. Click on Create a new SMTP key. Copy the key at some safe place.  You can deactivate the SMTP key anytime. Now, open the .env file and create 2 key-value pair. USER=YOUREMAILADDRESS  PASS=xxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx USER: The email address using which you created the sendinmail account. PASS:SMTP Key By using .env file we are not exposing the credentials to the web.  Using environment variables in the project is an industrial standard.  Source Code Open the send-mail.js in the editor. Copy and paste the below code in it."use strict";  require("dotenv").config();  constnodemailer = require("nodemailer");  /**   * sendEmail   * @param{Object}mailObj - Email information   * @param{String}from- Email address of the sender   * @param{Array}to- Array of recipients email address   * @param{String}subject - Subject of the email   * @param{String}text - Email body   */  constsendEmail = async (mailObj) => {  const{ from, to, subject, text } = mailObj;  try {  // Create a transporter  lettransporter = nodemailer.createTransport({  host:"smtp-relay.sendinblue.com",  port:587,  auth: {  user:process.env.USER,  pass:process.env.PASS,        },      });  // send mail with defined transport object  letinfo = awaittransporter.sendMail({  from:from, // sender address  to:to, // list of receivers  subject:subject, // subject line  text:text, // plain text body      });  console.log(`Message sent: ${info.messageId}`);  return`Message sent: ${info.messageId}`;    } catch (error) {  console.error(error);  thrownewError(  `Something went wrong in the sendmail method. Error: ${error.message}`      );    }  };  module.exports = sendEmail; Code Walk Through In the beginning, we are importing dotenv to get the environment variables from the .env file and nodemailer to send the email. The sendEmailfunction accepts an object. This object has from, to, subject, text fields. Please note that, from and USER must be same. The nodemailer.createTransportreturns a mail object. The transporter variable is storing the mail object.  let transporter = nodemailer.createTransport({       host: "smtp-relay.sendinblue.com",       port: 587,       auth: {         user: process.env.USER,         pass: process.env.PASS,       },     });Open SMTP tab in your sendinmail account and cross check the host and port.In the auth object, we are passing the user and password from the environment variable.Send the mail using sendMail method.// send mail with defined transport object     let info = await transporter.sendMail({       from: from, // sender address       to: to, // list of receivers       subject: subject, // Subject line       text: text, // plain text body     });It returns a Promise of Send Message Info. In the end, it is returning the message id.  Express Route The sendEmail method is ready.  Let’s create an express route for it. This is the API endpoint using which we can access the sendEmail function. Open the mail-api.js in the code editor and paste the below code. constexpress = require("express");  constrouter = express.Router();  constsendMailMethod = require("../src/send-mail");  // Post request to send an email  router.post("/sendmail", async (req, res) => {  try {  constresult = awaitsendMailMethod(req.body);  // send the response  res.json({  status:true,  payload:result          });      } catch (error) {  console.error(error.message);  res.json({  status:false,  payload:"Something went wrong in Sendmail Route."          })      }  }) module.exports = router; The express framework provides a Router method to create different HTTP methods. Here, we have created a POST method to send the mail.  Instead of extracting the req.body parameters, we passed it as it is. The benefit of this approach is that if there is a change in argument or position, then we would not have to change it in all the places.  In the end, we are exporting the router. Now, this can be used in the server side. Express Server Now, it’s time to create a server and expose the routes on it. Open the index.js and paste the below code in it. "use strict";  constexpress = require("express");  constbodyParser = require("body-parser");  constcors = require("cors");  constapp = express();  constmailAPI = require("./routes/mail-api.js");  // Express body parser  app.use(cors());  app.use(bodyParser.json());  app.use(  bodyParser.urlencoded({  limit:"50mb",  extended:false,  parameterLimit:50000    })  );  // use the routes specified in route folder  app.use("/api/v1", mailAPI);  constport = process.env.PORT || 4444;  //listen to the server  app.listen(port, function () {  console.log(`listening to the port ${port} .....`);  }); The route is available on /api/v1/sendmail. Run the server. $ node index.js  listening to the port 4444 ..... Send an Email using API There are couple of methods to test the API. Using the Postmanor using the Curl command. Using Postman Install Postman on your machine if it is not installed. Create a POST request. URL: http://localhost:4444/api/v1/sendmail Content Type: JSON – Body tab > select JSON from dropdown Request Body:  {  "from": "hello@schadokar.dev",  "to": ["shubham@schadokar.dev"],  "subject": "Mail from Nodemailer",  "text": "Sending an email using nodemailer package."  } Hit Send. Make sure the server is running. On Success, the response returns the message id. Now, check your mailbox. If you are unable to find the mail in your Inbox, check the promotional mail folder. Using Curl CommandOpen the terminal or cmd.In the below curl command, change the parameters and enter.curl -X POST http://localhost:4444/api/v1/sendmail -H "Content-Type:application/json" -d '{"from": "hello@schadokar.dev","to": ["shubham@schadokar.dev"],"subject": "Mail from Nodemailer", "text": "Sending an email using nodemailer package."}'In this example, we have sent a simple text message to the recipient.  Nodemailer also gives you an option to send the message in HTML format. Mail template Open the mail.html in the code editor and paste the below code. 
Rated 4.0/5 based on 13 customer reviews
6550
Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email ... Read More