0% found this document useful (0 votes)
33 views

Nodejs-01-Getting Started With Node - Js Simplilearn

This document provides an overview and introduction to Node.js, including: - What Node.js is and some of its key features and advantages - The Node.js architecture including its event-driven, non-blocking model - The Node Package Manager (NPM) and how to install packages - Common Node.js modules like HTTP and file system - How to create a basic web server and handle events - The Express framework for building web applications - How Node.js can interface with databases like MySQL and MongoDB - An example weather application that will be built called "Weatherly"
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Nodejs-01-Getting Started With Node - Js Simplilearn

This document provides an overview and introduction to Node.js, including: - What Node.js is and some of its key features and advantages - The Node.js architecture including its event-driven, non-blocking model - The Node Package Manager (NPM) and how to install packages - Common Node.js modules like HTTP and file system - How to create a basic web server and handle events - The Express framework for building web applications - How Node.js can interface with databases like MySQL and MongoDB - An example weather application that will be built called "Weatherly"
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

The Ultimate Tutorial to Getting Started With Node.

js

Lesson 1 of 9 By Nikita Duggal

Last updated on Jul 21, 2023 70667

Previous Next

Tutorial Playlist

Table of Contents

What is Node.js?

Node.js Architecture

Node Package Manager (NPM)

Node.js Modules

Node.js HTTP module

View More

Node.js is a compelling JavaScript-based platform that's built on Google Chrome's JavaScript V8 Engine. It is used
to develop I/O intensive web applications, such as video streaming sites, single-page applications, online chat
applications, and other web apps. Large, established companies and newly-minted startups alike (Net�ix, Paypal,
NASA, and Walmart, to name a few) use it often. Eager to know more? This tutorial will help you in getting started
with node.js.

Node.js is open-source and completely free, and thousands of developers around the world use it. The platform
brings plenty of advantages to the table, making it a better choice than other server-side platforms, like Java or
PHP.

Basics to Advanced - Learn It All!

Caltech PGP Full Stack Development


EXPLORE PROGRAM

First, we'll go through some of the basic concepts required in getting started with node.js, and then we will create
our own Weather App. This application will enable us to search for weather conditions anywhere in the world.

Let us now begin our tutorial on NodeJS by understanding what is node.js.

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment and library used to run web applications
outside the client's browser. Ryan Dahl developed it in 2009, and the latest version, v13.8.0, was released on Jan.
30. Node.js is used to create server-side web applications and is perfect for data-intensive applications since it
uses an asynchronous, event-driven model.

Fig: Node.js logo

Now that we have learned the basics of getting started with node.js, let us next learn the architecture of node.js

Basics to Advanced - Learn It All!

Caltech PGP Full Stack Development

EXPLORE PROGRAM

Node.js Architecture

Node.js uses the "Single Threaded Event Loop" architecture to handle multiple concurrent clients. The Node.js
processing model is based on the JavaScript event-based model, along with the JavaScript callback mechanism.
Fig: Node.js architecture

• Clients send requests to Web Server.

Requests can be:

• Querying for data

• Deleting data

• Updating the data, etc.

• Node.js adds the requests to the Event Queue

• Event Loop checks if the requests are simple enough not to require any external resources

• Event Loop processes simple requests and returns the responses to the corresponding clients

• A single thread from Thread Pool is assigned to a single complex request

• Thread Pool performs the required task and returns the response to Event Loop, which in turn, returns the
response to the client

Node Package Manager (NPM)

Node Package Manager provides two main functionalities:

• Online repositories for Node.js packages/modules, which are searchable on Node.js documents

• A command-line utility to install Node.js packages, do version management, and dependency management of
Node.js packages

When you install Node.js, NPM is also installed. The following command in CMD can verify if NPM is properly
installed: npm --version
Fig: NPM veri�cation

Now that we have covered what is Node.js, Node.js Architecture, and NPM as part of this Node.js tutorial, let us
now look at different Node.js Modules.

Node.js Modules

Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions. To
include a module in a Node.js application, use the require() function with the parenthesis containing the name of
the module.

Fig: Include a module in Node.js

Node.js has many modules that provide the basic functionality needed for a web application. Some of them are
mentioned in this table:

Fig: Node.js modules table

Node.js HTTP module


Node.js has a built-in module called HTTP. This module enables Node.js to transfer data over the internet. We use
the require() method to include the HTTP module in an application.

Now, let's create a simple Web server using the HTTP module:

Fig: Web server using HTTP module

• We use the require() method to include the HTTP module in the application

• Then, we create a server object using the createServer method

• After that, we write a response 'Hello World!' to the client and then end it

• We set the web server to listen at port - 8080

Fig: Web server output

This is what the output looks like on the web browser when we go to the URL with the correct port.

Node.js File System

Next in the getting started with node.js tutorial we will look at node.js �le system. The Node.js �le system module
enables the �le system to work on a computer. We use the require() method to include the �le system module in the
web application.

Node.js Events

Every action on a computer is considered an event. For example, opening a �le, connecting to the internet, etc.
Node.js has a built-in events module, where users can create, trigger, and listen for events.
Let's look at a basic implementation of the Events module in a Node.js application:

Fig: Node.js Events implementation

• We use the require() method to include events in our application

• Then, we create an EventEmitter object, which is a module that facilitates interaction between objects in Node.js

• After that, we create an event handler and assign it to the event 'click'

• Finally, we emit/trigger the event

Fig: Node.js Events output

The 'myEventHandler' method is called, and the console shows the output when you trigger the event using the
'emit()' method.

We will now cover an important aspect of the Node.js application framework as part of this Node.js tutorial. The
Node.js Express Framework.

Node.js Express Framework

Next up in the getting started with node.js tutorial we will look at node.js. Express is a �exible Node.js web
application framework that provides a wide set of features to develop both web and mobile applications. It's a layer
built on the top of Node.js that helps manage a server and routing.

Let's have a look at some of the core features of the Express framework:

• Used for designing single-page, multi-page, and hybrid web applications

• Enables developers to set up middleware to respond to HTTP Requests

• De�nes a routing table to perform different actions based on the HTTP method and URL

• Enables dynamic rendering of HTML pages based on passing arguments to templates


Enables dynamic rendering of HTML pages based on passing arguments to templates

Let's look at an example of a simple "Hello World" program developed using Express Framework to gain a better
understanding.

Fig: Node.js Express framework "Hello World"

• var express: Importing Express framework into our Node.js application

• app.get(): Callback function with the parameters' request' and 'response'

• Request object: The HTTP request that contains properties for the request query string, parameters, body, HTTP
headers, etc.

• Response object: The HTTP response that an Express app sends when it gets an HTTP request

• The application will listen to the de�ned port, which in this case is "8081," and variables "host" and "port" will
contain the address and the port respectively

• console.log: This is used to show the address and port in the command prompt or terminal.

Basics to Advanced - Learn It All!

Caltech PGP Full Stack Development

EXPLORE PROGRAM

Node.js with Database

Next in the getting started with node.js tutorial we will look at how Node.js can be used with various databases to
enable web applications to store data and perform operations with that data.

MySQL

MySQL is among the more popular databases that can be connected to Node.js. It is the most popular open-source
relational SQL database management system. It also is one of the best RDBMS used to develop various web-based
software applications.

You can install the MySQL module using the following command prompt, and then add it to your �le:
You can install the MySQL module using the following command prompt, and then add it to your �le:

var mysql = require(‘mysql’)

MongoDB

MongoDB is also a popular database choice to connect with Node.js. It is an open-source document database and
a leading NoSQL database. This database is often used for high-volume data storage.

You can install the MongoDB module using the following command prompt and then add it to your �le:

var mongodb = require(‘mongodb’)

Fig: MongoDB Compass

MongoDB Compass is a tool that lets users connect to a database and view or edit the data from the dashboard.
This tool is installed while installing MongoDB.

The next section of this Node.js tutorial shows you how to create an application using Node.js.

Create a Node.js application: Weatherly

We are going to make our Node.js-powered weather application: Weatherly. This application will enable us to search
for weather conditions anywhere in the world.
Fig: Weatherly Application

Prerequisites

Node.js Installation

1. Download the Node.js from https://nodejs.org/en/download/. Select the installer according to your operating
system and environment.

Fig: Node.js download page

2. Run the Node.js installer. Accept the license agreement. You can leave other settings as default. The installer will
install Node.js and prompt you to click on the �nish button.

Fig: Node.js setup

3. Verify that Node.js was properly installed by opening the command prompt and typing this command: node
--version
--version

Fig: Node.js veri�cation

4. When we install Node.js, NPM (Node Package Manager) is also installed. NPM includes many libraries that are
used in web applications, such as React. Verify whether it is installed or not with the following command in CMD:
npm --version

That's all we need to do to install Node.js in a Windows system successfully!

API Setup

For this project, we'll be using the free OpenWeather API. Head over to this link and sign up for an account with an
email and a password.

Fig: OpenWeatherMap dashboard

Once signed in, select the API Keys tab. Here, you can create a key on the right-hand side of the page. Enter a name
for your application and select generate. The API key will appear on the left. We will use this key later in our code.

Basics to Advanced - Learn It All!

Caltech PGP Full Stack Development

EXPLORE PROGRAM
Text Editor

Install a text editor of your choice. We are using Visual Studio Code in this tutorial, but you can also use other
editors, like Atom and Sublime Text, if you are more comfortable with those.

Fig: Visual Studio Code download page

Project Setup

1. Create an empty directory named weatherly.

2. Open the newly created directory in VS Code, and inside the terminal, type npm init to initialize the project. Press
the Enter key to leave the default settings as they are.

Fig: VS Code project

3. Within the weatherly directory, create a �le named server.js, which will contain the code for our application.

Server.js

Create a �le called server.js in the project directory. This �le in our application acts as the main server because it
contacts OpenWeatherMap using the API key and returns the weather conditions of the inputted location.

Let’s go ahead and learn what task each snippet of code carries out in this �le.

1. const express = require('express');

2. const bodyParser = require('body-parser');

3. const request = require('request');

4. const app = express()

5.

6. const apiKey = '**********************';

7.

8. app.use(express.static('public'));

9. app.use(bodyParser.urlencoded({ extended: true }));

10. app.set('view engine', 'ejs')

11.

12. app.get('/', function (req, res) {

13. res.render('index', {weather: null, error: null});

14. })

15.

16. app.post('/', function (req, res) {

17. let city = req.body.city;

18. let url = `http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=${apiKey}`

19. console.log(req.body.city)

20. request(url, function (err, response, body) {

21. if(err){

22. res.render('index', {weather: null, error: 'Error, please try again'});

23. } else {

24. let weather = JSON.parse(body)

25. if(weather.main == unde�ned){

26. res.render('index', {weather: null, error: 'Error, please try again'});

27. } else {

28. let weatherText = `It's ${weather.main.temp} degrees with ${weather.weather[0].main} in ${weather.name}!`;

29. res.render('index', {weather: weatherText, error: null});


30. console.log("body:", body)

31. }

32. }

33. });

34. })

35.

36. app.listen(3000, function () {

37. console.log('Weatherly app listening on port 3000!')

38. })

• Line 1 - 3: We are importing three modules in the application: express, body-parser, and request. We can add
these modules using the terminal inside the VS Code.

• Line 4: Create an Express object called app

• Line 6: Add the API key to our application

• Line 8: This line of code is used to access the CSS �le we added in the public folder inside the project directory
to make the application look better

• Line 9: Access the request body

• Line 10: Set up the EJS template engine with this line of code

• Line 12-14: Use the GET method for rendering the index.ejs (front-end HTML) �le as a response

• Line 16 - 34: Use the POST method to request the server for weather conditions at a given location:

• Store the city from the request body in the city variable

• Send the URL with the city name and API key

• If there is an error, send an error message to be rendered on index.ejs

• Otherwise, send the weather conditions to be rendered on index.ejs

• Line 36 - 38: Set the application to listen at port: 3000, and log the message to the console

Learn From The Best Mentors in the Industry!

Automation Testing Masters Program


EXPLORE PROGRAM

Index.ejs

Instead of responding with text when someone visits the root page, we'd like to respond with an HTML �le. For this,
we'll be using EJS (Embedded JavaScript). EJS is a templating language.

To add this feature to our application, we have to install it using the terminal the same way we added modules. Use
this command: npm install --save ejs

EJS is accessed by default in the views directory. Create a new folder named views in the application directory.
Within that views folder, add a �le named index.ejs. This is how the project directory should look:

Fig: Project directory_1

Now, let's go ahead and add the code for this �le and then learn what exactly each line of code does.

1. <!DOCTYPE html>

2. <html>

3. <head>

4. <meta charset="utf-8" />

5. <title>Weatherly</title>

6. <link rel="stylesheet" type="text/css" href="/css/style.css" />

7. <link

8. href="https://fonts.googleapis.com/css?family=Open+Sans:300"

9. rel="stylesheet"

10. type="text/css"

11. />

12. </head>
12. </head>

13. <body>

14. <div class="container">

15. <�eldset>

16. <form action="/" method="post">

17. <input

18. name="city"

19. type="text"

20. class="ghost-input"

21. placeholder="Enter a City"

22. required

23. />

24. <input

25. id="submit"

26. type="submit"

27. class="ghost-button"

28. value="Get Weather"

29. />

30. </form>

31. <% if(weather !== null){ %>

32. <p><%= weather %></p>

33. <% } %> <% if(error !== null){ %>

34. <p><%= error %></p>

35. <% } %>

36. </�eldset>

37. </div>

38. </body>

39. </html>

40.

The above code is exactly like what you would write to create an HTML form. Since this is not an HTML tutorial, I'll
explain only the EJS part of the code:

• Line 31 - 35: If the application can fetch the weather from the server, weather conditions are displayed on the
• Line 31 - 35: If the application can fetch the weather from the server, weather conditions are displayed on the
screen. Otherwise, an error is displayed in that �eld.

Style.css

You can add the following CSS code to your application to make it look exactly like the one in this Node.js tutorial.
You are free to tweak the CSS styles according to your preferences, too.

Fig: Project directory_2

Add the following CSS styles in the style.css �le and keep the �le inside the public/css folder inside the project
directory to make the styles work with the application.

/*

Styles from this codepen:

https://codepen.io/o�cial_naveen/pen/rgknI

*/

body {

width: 800px;

margin: 0 auto;

font-family: 'Open Sans', sans-serif;

background: url("../images/weather.jpg");

background-size: cover;

.container {
width: 600px;

margin: 0 auto;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

opacity: .7;

background-color: darkgray;

border-radius: 10px;

�eldset {

display: block;

-webkit-margin-start: 0px;

-webkit-margin-end: 0px;

-webkit-padding-before: 0em;

-webkit-padding-start: 0em;

-webkit-padding-end: 0em;

-webkit-padding-after: 0em;

border: 0px;

border-image-source: initial;

border-image-slice: initial;

border-image-width: initial;

border-image-outset: initial;

border-image-repeat: initial;
min-width: -webkit-min-content;

padding: 30px;

.ghost-input, p {

display: block;

font-weight:300;

width: 100%;

font-size: 25px;

border:0px;

outline: none;

width: 100%;

-webkit-box-sizing: border-box;

-moz-box-sizing: border-box;

box-sizing: border-box;

color: #4b545f;

background: #fff;

font-family: Open Sans,Verdana;

padding: 10px 15px;

margin: 30px 0px;

-webkit-transition: all 0.1s ease-in-out;

-moz-transition: all 0.1s ease-in-out;

-ms-transition: all 0.1s ease-in-out;

-o-transition: all 0.1s ease-in-out;

transition: all 0.1s ease-in-out;


}

.ghost-input:focus {

border-bottom:1px solid #ddd;

.ghost-button {

background-color: transparent;

border:2px solid #ddd;

padding:10px 30px;

width: 100%;

min-width: 350px;

-webkit-transition: all 0.1s ease-in-out;

-moz-transition: all 0.1s ease-in-out;

-ms-transition: all 0.1s ease-in-out;

-o-transition: all 0.1s ease-in-out;

transition: all 0.1s ease-in-out;

color: white;

font-weight: bold;

.ghost-button:hover {

border:2px solid #515151;

p{

color: #E64A19;

You might also like