header banner
Default

Starting Off With Node Js | Simplilearn


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 (Netflix, 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. 

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.

    node_js

    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

    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.

    node-js-archi

    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

    npm

    Fig: NPM verification

    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.

    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:

    core-module

    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:

    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

    web-server

    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 file system. The Node.js file system module enables the file system to work on a computer. We use the require() method to include the file system module in the web application.

    require-fs.

    Node.js Events

    Every action on a computer is considered an event. For example, opening a file, 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 flexible 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
    • Defines 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

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

    hello-world

    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 defined 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.

    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

    VIDEO: Node.js Ultimate Beginner’s Guide in 7 Easy Steps
    Fireship

    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 file:

    var mysql = require(‘mysql’)

    MongoDB

    VIDEO: Node.js Tutorial for Beginners: Learn Node in 1 Hour
    Programming with Mosh

    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 file:

    var mongodb = require(‘mongodb’)

    employee-db

    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.

    weatherly.

    Fig: Weatherly Application

    Prerequisites

    Node.js Installation

    VIDEO: Introduction and Getting Started - Node.js Tutorial 1
    Caleb Curry

    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 finish button.

    Fig: Node.js setup

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

    Fig: Node.js verification

    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

    VIDEO: Your First Node.js Web Server
    Web Dev Simplified

    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.

    open-weather

    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.

    Text Editor

    VIDEO: Node.js / Express Course - Build 4 Projects
    freeCodeCamp.org

    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.

    texteditor

    Fig: Visual Studio Code download page

    Project Setup

    VIDEO: RESTful APIs in 100 Seconds // Build an API from Scratch with Node.js Express
    Fireship

    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.

    vs-code

    Fig: VS Code project

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

    Server.js

    VIDEO: DevOps In 5 Minutes | What Is DevOps?| DevOps Explained | DevOps Tutorial For Beginners |Simplilearn
    Simplilearn

    Create a file called server.js in the project directory. This file 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 file.

    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 == undefined){
    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.

    problems

    • 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 file 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)  file 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

    Index.ejs

    VIDEO: What is NPM, and why do we need it? | Tutorial for beginners
    Coder Coder

    Instead of responding with text when someone visits the root page, we'd like to respond with an HTML file. 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 file named index.ejs. This is how the project directory should look:

    project-direct

    Fig: Project directory_1

    Now, let's go ahead and add the code for this file 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>
    13.   <body>
    14.     <div class="container">
    15.       <fieldset>
    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.       </fieldset>
    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 screen. Otherwise, an error is displayed in that field.

    Style.css

    VIDEO: Build Restful CRUD API with Node.js, Express and MongoDB in 45 minutes for Beginners from Scratch
    Devtamin

    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.

    project-dir2

    Fig: Project directory_2

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

    /*

      Styles from this codepen:

      https://codepen.io/official_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;

      }

      fieldset {

        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;

      }

    Final Result

    VIDEO: Node JS Full Course - Learn Node.js in 7 Hours | Node.js Tutorial for Beginners | Edureka
    edureka!

    Next in the getting started with node.js tutorial let’s focus on the industry trends. Node.js developers are in demand around the world due to the wide adoption of this JavaScript library. It is among the top 10 most in-demand jobs, according to Forbes.

    Weatherly Application

    Fig: Weatherly Application

    In the last section of this Node.js tutorial, let us look at some of the industry trends and demands associated with Node.js.

    Node.js developers are in demand around the world due to the wide adoption of this JavaScript library. It is among the top 10 most in-demand jobs, according to Forbes.

    node-js-source

    Fig: Node.js Source Report

    • The total number of Node.js downloads increased by 40 percent in 2018, according to Node Source
    • The use of Node.js in production has significantly increased since its release in 2010

    With adopters such as Netflix, PayPal, and other tech companies, Node.js has seen an exponential increase in web development.

    The popularity of Node.js is also due to the fact that it's built in JavaScript. Since JavaScript is the most popular programming language, as evident from the survey conducted by Stack Overflow in 2019, many developers can start working on the Node.js library without too steep of a learning curve.

    prog

    Source: Stack Overflow Report 2019

    • Node.js developers are being offered better salary options than other web technology developers

    payscale-node

    The average salary for a Node.js developer in India is ₹6,13,000 per year!

    payscale-dev

    The average salary for a Node.js developer in the United States is $104,964 per year!

    To sum up all that’s required in getting started with node.js, check out the Node.js tutorial video.

    Get Ahead of the Curve and Master Node.js Today

    In this tutorial, you have learned about Node.js architecture, Node.js Modules, creating applications with Node.js and all the basics of getting started with node.js. If you are wondering how to obtain the skills necessary to take advantage of its rising popularity, there are some great options to learn this exciting and practical skill set at your own pace. Simplilearn's Node.js Certification training course will give you a great foundation in this popular platform, combining live, instructor-led training, self-paced tutorials, and hands-on projects to help you become career-ready upon completion. Get started today and seize your future! 

    Sources


    Article information

    Author: Karen Jackson

    Last Updated: 1704125403

    Views: 2094

    Rating: 4.1 / 5 (65 voted)

    Reviews: 80% of readers found this page helpful

    Author information

    Name: Karen Jackson

    Birthday: 1976-10-29

    Address: 724 Ashley Plain Suite 170, Coleport, MO 09221

    Phone: +3899132638087365

    Job: Zoologist

    Hobby: Chocolate Making, Bowling, Web Development, Knitting, Wine Tasting, Rock Climbing, Raspberry Pi

    Introduction: My name is Karen Jackson, I am a exquisite, audacious, strong-willed, forthright, Colorful, apt, clever person who loves writing and wants to share my knowledge and understanding with you.