Node.js tutorial
  1. Node.js – Introduction
  2. What is Node.js?
  3. What is a Node.js File?
  4. Why Node.js?
  5. Advantages of Node.js
  6. Node.js – Environment Setup
  7. Install Node.js on Mac/Linux
  8. Node.js – REPL Terminal
  9. Syntax to install any Node.js module 
  10. Attributes of Package.json
  11. Node.js – Callbacks Concept
  12. Non-Blocking Code Example

Node.js – Introduction

Node.js is a powerful platform built on Google Chrome’s JavaScript V8 Engine. Node.js is open source, totally free, and used by a huge number of developers around the world. This tutorial is intended mainly for software developers who wish to become familiar with the basics of Node.js and its structural concepts. 

What is Node.js?

Node.js was introduced by Ryan Dahl in 2009 and its recent version is v0.10.36. Node.js cross-platform runtime environment for developing highly scalable server-side and networking applications with JavaScript. Its applications are written in JavaScript and can run inside the Node.js runtime on OS X, Microsoft Windows, and Linux. 

Also check:

Apache Hadoop Tutorial |What is Apache Hadoop?
Selenium Tutorial
R Tutorial
A Beginner’s Guide to Programming | How to Start Coding

What is a Node.js File?

  • Node.js files consist of tasks that is to be executed on specific events
  • A regular event is someone attempting to access a port on the server
  • Node.js files must be initiated on the server prior to having any impact
  • Node.js files have extension “.js”

Why Node.js?

A typical task for a web server can be to open a file on the server and return the content to the client.

Here is the manner by which PHP or ASP handles a file request:

  1. Directs the task to the computer’s file system.
  2. Waits during the file system open and reads the file.
  3. Returns the content to the client.
  4. Ready to deal the next request.

Here is the manner by which Node.js handles a file request:

  1. Directs the task to the computer’s file system.
  2. Ready to deal the next request.
  3. Once the file system has opened and read the file, the server returns the content to the user.

Node.js kills the waiting, and simply proceeds with the following request.

Node.js uses single-threaded program, no buffering, asynchronous and event driven programming, which is very memory efficient.

Node.js is best suitable for:

  • Real-time web applications
  • Streaming applications
  • Messaging apps
  • Chat programs
  • Social media apps
  • Virtual emulators
  • Multiplayer games
  • Collaboration tools
  • API

Advantages of Node.js

  1. Node.js offers an Easy Scalability
  2. Easy to Learn
  3. Node.js is a Single Programming Language
  4. The Benefit of Fullstack JS
  5. Known for Offering High Performance
  6. The Support of Large and Active Community
  7. The Advantage of Caching
  8. Offers the Freedom to Develop Apps
  9. Getting Support for Commonly Used Tools
  10. Handles the Requests Simultaneously
  11. Node.js is Highly Extensible

Node.js – Environment Setup

To get started make sure that the following things are available in your system

  1. IDE (Integrated Development Environment) or Text editor

Text editor can be notepad or notepad++ if you are using a windows machine. Name and version of text editor may vary for different operating systems. The source files are the one that you create with editor and it consists of program source code. These source files for Node.js programs are generally saved with extension .js.  An IDE that provisions for auto complete features for Node.js API is suggested e.g. Visual Studio, Sublime text, Eclipse, Aptana etc.

  1. The Node.js

Java script is used to write source code. The Node.js interpreter is utilised to interpret and execute your javascript code.

The following section guides you on how to install Node.js binary distribution on your system.

Download Node.js

Go to the official Node.js website for installing Node.js: https://nodejs.org

Download Node.js installer for windows

Download node MSI for windows by clicking on 14.15.0 LTS or 15.2.0 Current button. Here we used the latest version 15.2.0 for windows throughout this tutorial.

Once you have downloaded the MSI, double-click on it to start the installation process, as shown below.

Just click on next button and accept the License Agreement and finally click on install. Do remember the location where Node.js is being installed during the installation process, this is just to verify whether it is installed properly or not. If you can observe during this process Runtime manager and Package manager etc., will be provided by default. Here Runtime manger is used to execute the programs and Package Manager will provide predefined modules. After clicking on install Node.js will be installed on your computer. Finally click on finish to complete the installation process.

The installer should set the path in in window’s PATH environment variable. To check Node.js directory, right click over This PC- Go to Properties- A window will be opened there on the left side you will find Advanced System Settings, click on it- Next a window will be opened and in this click on Environment Variables present on the bottom right side- Here in the System Variables section you will find path variable, double click on it- Next a window will be displayed where you will find C:\Program Files\node.js\ this is the path where Node.js is installed.

Cross verify installation

After successfully installing Node.js on your computer, just verify it by opening command prompt and type node -v. if it is successfully installed then it will show the version of the Node.js installed on your computer.

Install Node.js on Mac/Linux

Visit Node.js official web site https://nodejs.org/en/download. Click on corresponding installer for Mac (.pkg or .tar.gz) or Linux to download the Node.js installer.

Once downloaded, to install click on the installer to start the Node.js installation wizard. Click on Continue and follow the steps. After successful installation, it will show summary of installation regarding the location where it is installed Node.js and NPM.

After installation is done, verify the Node.js installation using terminal window and enter the following command. It will show the version number of Node.js installed on your Mac.

$  node -v

Alternatively, for Mac or Linux users, you can install directly Node.js from the command line with the help of Homebrew package manager for Mac OS or Linuxbrew package manager for Linux Operating System.

$  brew install node

Node.js – First Application

Node.js is an open sourced cross-platform server environment which executes JavaScript utilizing V8 JavaScript Engine. Node.js assists with composing front-end and back-end code in the same language. It helps to code efficiently for real-time applications. In Node.js, the applications can be composed using 

  1. console-based method or
  2. web-based method.
  1. Console based Node.js Application: Node.js command prompt is used to run console-based applications. Console module in Node.js provide a straightforward debugging console. Node.js is a worldwide console which can be used for synchronous as well as asynchronous correspondence. The console.log() function is used to show the result on console. This function prints result to stdout with newline.

Syntax:

console.log([data][, …]);

Here, data is the content to be shown on the console.

Example 1:

Creating a “Hello World” application using Node.js. Create a GK1.js file containing the following code:

console.log(‘Hello World’); 

By using Node.js command prompt run the file with command node <file_name> 

Output:

Example 2:

Creating a Hello World application by receiving the input from the user. Create a GK2.js file containing the following code.

console.log(process.argv.slice(2));

The process.argv is used to give command line argument to a program. Use the slice function with argument 2 to get all the elements of argv that comes after its subsequent element, i.e. the arguments the user enters. The first argument is for the Node.js binary which is used to run the program and the second one is location of the file being run.


Output:

  1. Web-based Node.js Application:

First, we will go through what are the components present in Node.js application, then we create an actual “Hello, World!” application with Node.js. A Node.js application comprises of the following three significant segments –

  • Import required modules – With the help of require directive we load Node.js modules.
  • Create server − A server like the Apache HTTP Server will listen to client’s requests.
  • Read request and return response − The server created in previous step will read the HTTP request made by the user that can be a browser or a console and returns the response.

Example: 

Below example develops a Hello World web-based application using Node.js. Create a file named firstprogram.js and follow below steps.

Step 1 – Import Required Module

In order to load the http module and store the returned HTTP instance into an http variable we make use of the require directive. 

Syntax:

var http = require(“http”);

Step 2 – Create Server

By using the created http instance we call the http.createServer() method to create a server instance. Then, we bind it at port 8080 with the listen method related with the server instance. Pass the method with a function including parameters request and response. Code a sample application to always return “Hello World”.

// Create server 
http.createServer(function (req, res) { 
// HTTP Status: 200 : OK 
// Content Type: text/html 
res.writeHead(200, {'Content-Type': 'text/html'}); 
// Send the response body as "Hello World!"   
res.end('Hello World!'); 
}).listen(8080);

Step 3 – Testing Request & Response

Let’s combine step 1 and 2 together in a file called firstprogram.js and start our HTTP server as shown below −

// Require http header 
var http = require('http'); 
// Create server 
http.createServer(function (req, res) { 
    // HTTP Status: 200 : OK 
    // Content Type: text/html 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    // Send the response body as "Hello World!"   
    res.end('Hello World!'); 
}).listen(8080); 
Run the file on Node.js command prompt using the below command.
$ node firstprogram.js 


Output:

Type url- http://127.0.0.1:8080/ in a web browser to see the output.

Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8080.

Node.js – REPL Terminal

Node.js accompanies with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop. This virtual environment is similar to Windows console or Unix/Linux shell where a command is entered and the system shows result in an intelligent mode. It is a quick, very useful in experimenting and easy way to test simple Node.js/JavaScript code. It performs the following tasks–

  • Read − Reads client’s input, passes input to the JavaScript data-structure, and stores in memory.
  • Eval − Takes and assesses the data structure.
  • Print − Prints the outcome.
  • Loop − Loops the above order until the user presses ctrl-c twice.

Starting with REPL

To get started with, we need to launch REPL (Node shell) by opening command prompt for Windows or terminal for Mac or UNIX/Linux and type node as mentioned below. 

$ node

This will show you REPL Command prompt as > where you can write any Node.js command –

You can now pretty much test any Node.js/JavaScript expression in REPL. Try to write “30 + 20” and then you can see the displayed result as 50 immediately in next line. Let us try few more mathematics at Node.js REPL command prompt-

The + operator also concatenates strings as in browser’s JavaScript see below example

Use variables

You can also use variables to store values and print them later. If you don’t use var keyword, then that value will be stored and printed.

If you use var keyword, that variable will be stored but not printed out. Consol.log() is used to print variables.

Multiline Expression

If you want to write multi line JavaScript expression then do press Enter whenever you want to write in the next line as a continuation of your code. The REPL terminal will show three dots (…), stating that you can continue on next line. To get out of continuity mode write .break

For instance, you can define a function and run it as shown below.

You can also execute an external JavaScript file by mentioning node fileName command. For example, assume that node1.js is on C drive of your PC with below code.

console.log(“Hello World”);

you can execute node1.js from command prompt as shown below.

Stopping REPL

If you want to exit out of REPL terminal, press Ctrl + C twice or write .exit and press Enter.

Hence you can execute any Node.js/JavaScript in the REPL which gives the same result as in the case you get in the console of any browser.

REPL commands

Below table shows list of REPL commands.

REPL CommandDescription
.helpDisplay help on all the commands
tab KeysDisplay the list of all commands.
Up/Down KeysSee previous commands applied in REPL.
.save filenameSaves current Node REPL session to a file.
.load filenameLoads the predetermined file in the current Node REPL session.
ctrl + cTerminate the current command.
ctrl + c (twice)Exit from the REPL.
ctrl + dExit from the REPL.
.breakExit from multiline expression.
.clearExit from multiline expression.

Node.js – Package Manager

Node Package Manager (NPM) is a command line tool that is used to install, update or uninstall Node.js packages in your application. It is additionally an online repository for open-source Node.js packages. The node community around the world creates useful and valuable modules and publishes them as packages in this repository.

NPM is incorporated with Node.js installation. After you install Node.js, confirm NPM installation by writing the below command in terminal or command prompt.

Updating npm

Npm tends to be updated more frequently. If you have an older version of NPM and you want to update it to the latest version use the following command. 

To get to NPM help, write npm help in the command prompt or terminal window.

NPM does the operation in two modes: global and local. In the global mode, NPM does operations which influence and effects all the Node.js applications on the computer while in the local mode, NPM performs operations on the specific local directory which influences an application in that particular directory only.

Install Package Locally

As a matter of course, NPM installs any dependency in the local mode. Here local mode denotes to the package installation in node_modules directory lying in the folder where Node application is available. The require() method is used to access locally deployed packages. For example, when we install express module, it created node_modules directory in the current directory where it installed the express module.

Below is a simple syntax to install any Node.js module 

$ npm install <Module Name>

For instance, below is the command to install a well-known Node.js web framework module named express –

$ npm install express

The above command creates ExpressJS folder under node_modules folder in the root folder of your project and there installs Express.js.

You can use this module in your js file now as shown below –

var express = require(‘express’);

Installing a Specific Version of a Package

Let’s us consider we now want to install the Underscore package in the version we want. For this we use the @ sign to append a version number:

$ npm install underscore@1.9.1

Install Package Globally

System directory contains globally installed packages/dependencies. Such dependencies can be utilized in CLI (Command Line Interface) function of any node.js yet cannot be transferred into using require() in Node application legitimately. Use -g in the install command to install any package globally. For instance, the following command installs ExpressJS globally.

$ npm install express -g

This will give the same result but the module will be installed globally. Here, the first line indicates the module version and the path where it is being installed.

express@4.12.2 /usr/lib/node_modules/express

├── merge-descriptors@1.0.0

├── utils-merge@1.0.0

├── cookie-signature@1.0.6

├── methods@1.1.1

├── fresh@0.2.4

├── cookie@0.1.2

├── escape-html@1.0.1

├── range-parser@1.0.2

├── content-type@1.0.1

├── finalhandler@0.3.3

├── vary@1.0.0

├── parseurl@1.3.0

├── content-disposition@0.5.0

├── path-to-regexp@0.1.3

├── depd@1.0.0

├── qs@2.3.3

├── on-finished@2.2.0 (ee-first@1.1.0)

├── etag@1.5.1 (crc@3.2.1)

├── debug@2.1.3 (ms@0.7.0)

├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9)

├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)

├── serve-static@1.9.2 (send@0.12.2)

├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)

└── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)

Add Dependency into package.json

At the end of the install command use –save to add dependency entry into package.json of your application.

For instance, the below command will be installing ExpressJS in your application and correspondingly adds dependency entry into the package.json.

$ npm install express –save

The package.json of NodejsConsoleApp project will look similar like below example.

{
  "name": "NodejsConsoleApp",
  "version": "0.0.0",
  "description": "NodejsConsoleApp",
  "main": "app.js",
  "author": {
    "name": "Dev",
    "email": ""
  },
  "dependencies": {
    "express": "^4.13.3"
  }
}

Attributes of Package.json

  • name − name of the package
  • version − version of the package
  • description − description of the package
  • homepage − homepage of the package
  • author − author of the package
  • contributors − name of the contributors to the package
  • dependencies − list of dependencies. In the node_module folder of the package NPM automatically installs all the dependencies mentioned here.
  • repository − type of repository and URL of the package
  • main − entry point of the package
  • keywords − keywords

Update Package

To update the package that is installed locally in your Node.js project, go to the command prompt or terminal window path to the project folder and write the below update command.

$ npm update express

Uninstall Packages

Use the below command to uninstall a particular Node.js module. Here example uninstalls express module.

$ npm uninstall express

After NPM uninstalls the package, you can confirm it by looking at the content of /node_modules/ directory or by typing the following command –

$ npm ls

Updating a Module

To update package.json and modify the version of the dependency run the following command.

$ npm update express

Search a Module

Search a package name using NPM.

$ npm search express

Create a Module

Creating a module requires package.json to be generated. Let’s create package.json using NPM, which will create the basic skeleton of the package.json.

$ npm init

This utility will take you through generating a package.json file. It covers the most mutual items, and tries to guess sane defaults.

Refer ‘npm help json’ for definitive documentation on these fields and precisely what they do.

Use ‘npm install <pkg> –save’ afterwards to install a package and in the package.json file save it as a dependency.

Press ^C at any time to quit.

name: (webmaster)

It is necessary to provide all the required information about your module. You can refer the above-mentioned package.json file to understand the meanings of several information demanded. When package.json is created, use the below command to register yourself with NPM repository site with the help of a valid email address.

$ npm adduser

Username: mahi

Password:

Email: (this IS public) mahi@gmail.com

Now the time has come to publish your module. Use below command to publish your module.

$ npm publish

If the whole thing is fine with your module created, then it will be published in the repository and will be available to install using NPM like any other Node.js module.

Node.js – Callbacks Concept

A callback is a function that is called when a task is completed, thus helping in preventing any kinds of blocking and a callback function allows other code to run in the meantime. ‘Callback’ is called when a task gets finished and is asynchronous equal for a function. Using Callback, Node.js can process a high number of requests without waiting for any other function to return the result making Node.js highly scalable. For eg: In Node.js, when a function starts reading the file, it returns the control to execution environment instantly so that the next instruction can be executed. Once after file I/O gets finished, the callback function will get called to avoid blocking or waiting for File I/O.

Blocking Code Example

Code for reading a file synchronously in Node.js. Create a text fille inputfile1.txt with the following content:

Hello Programmer!!!

Learn NodeJS with Great Lakes.

Now create a js file named sync.js with the following code:

// Write JavaScript code 
// To handle file-system related operations,  fs library is loaded
var fs = require("fs"); 
// 
var filedata = fs.readFileSync('inputfile1.txt'); 
console.log(filedata.toString()); 
console.log("End of Program execution"); 

In the above example, the readFileSync() function is synchronous and blocks execution until finished. The function blocks the program until it completes reading the file and then only it proceeds to end the program.

Now run the sync.js to see the result –

$ node sync.js

Output:

Non-Blocking Code Example

Create a text file named inputfile2.txt with the following content.

Hello Programmer!!!

Learn NodeJS with Great Lakes.

Create a async.js file with the following code:

// Write a JavaScript code 
// To handle file-system related operations,  fs library is loaded
var fs = require("fs");   
fs.readFile('inputfile1.txt', function (ferr, filedata) {   
    if (ferr) return console.error(ferr);   
    console.log(filedata.toString());   
});  
console.log("End of Program execution");  

In the above example, the readFile() function is asynchronous and control returns immediately to the next instruction in the program mean while the function keep running in the background. A callback function is passed which gets called when the task running in the background is finished. 

Now run the async.js to see the result –

$ node async.js

Output:

Thus, a blocking program executes particularly in sequence. From the programming point of view, it is simpler to implement the logic however non-blocking programs do not execute in sequence. In case a program needs to utilize any data to be processed, it should be kept within the similar block to make it sequential execution.

Check out Great Learning Academy to find amazing free courses on all kinds of domains and fields of professional learning.

java
0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

2 × 1 =