NODE.JS TUTORIAL

NODE.JS-TUTORIAL

Our Node.js tutorial is purely beginner-friendly and provides the basic concepts of Node.js. You will also learn to build a simple Node.js app and a video streaming website from scratch.

Before jumping into the topic, you have to know why Node.js. It is the most efficient and greatest tool for creating highly scalable, data-intensive, and real-time backend services that power web applications. Node.js is easy to start and great for prototyping and agile development. It has an ecosystem of open-source libraries that are considered to be the largest in the industry. It also has a cleaner and more consistent codebase. 

However, Node.js is not a programming language or a framework. It is only a runtime environment for executing javascript code outside of a browser.

Note: To go through this tutorial, you should have a basic understanding of javascript, HTML, and CSS.

What Is Node.Js?

Node.js is an open-source and cross-platform often used in the backend and Application Programming Interfaces (API). It is nothing other than a v8 javascript engine of chrome embedded inside the C++ program. It has additional modules (npm) that give us interesting capabilities which are not available inside a browser. It works with file systems, networks, and so on.

Node.js uses an event-based model, which makes it efficient when handling events such as user input or database interactions. As mentioned above, Node.js is open source, so developers can inspect the code before using it in their projects. It incorporates industry best practices such as HTTP/2 support for faster page loads and reduced network traffic. 

It uses non-blocking I/O, which makes the application more responsive and prevents the database from blocking read or write operations. Furthermore, since NodeJS runs in a single process thread instead of spawning multiple threads like other server frameworks do, debugging is easy as all traffic goes only through your Browser.

Node.js v/s Browser

Node.js and Browser are two different things that allow for creating interactive websites. Node.js is a platform-independent, single-threaded runtime environment for building large web applications using JavaScript. At the same time, browsers like Chrome or Firefox run all HTML, CSS, and JavaScript inside their own process so that the website runs as fast as possible in the user’s Browser.

The node can be used to speed up page load time by running scripts on the server rather than the client side, which can result in a more responsive experience when browsing your website. Additionally, node also enables you to use modules so that you don’t have to write code twice – once for your front end and again for backends such as databases or storage services (e.g., MongoDB).

A node can control the environment, and anyone can deploy it anywhere. Node.js always moves with the latest update of javascript codes, while browsers are a little bit slow in the case of upgrading.

In Node.js, we can use either require() method or import, but in browsers, it is limited to import only.

Node.js Modules

The module is a word that comes with Node.js. Modules can simply be defined as sets of codes wrapped in a function or as libraries. Node js modules are classes or functions that you can include in your codebase to make it easier for you to work with particular types of data. 

There are three types of Modules:

  • Core Modules

They are the in-built modules within Node.js.The Node js core modules are the essential building blocks for developing applications with node js. They provide APIs that enable you to interact with different parts of the operating system, database systems, web servers, and other third-party libraries. The require() function is used to call those modules.

Syntax: var module = require(“module_name”)

Here, we stored the functionality as an object which is returned from the particular module as the variable named “module.”

Important Modules:

  • Http Module

Syntax: var http = require(‘http’)

Here we create an http server in Node.js

  • File system Module

Syntax: var fs = require(‘fs’)

Using this module, we can read, create, update, rename and delete a file

  • URL Module

Syntax: var url = require(‘url’)

This module can split a web address so that it could read. url.parse() method can return the host, pathname, and so on as properties.

  • Event Module

Syntax: var events = require(‘events’)

Using the eventEmitter object in the event module, we can assign event handlers to our own event

  • Local Modules

Nodejs local modules is a feature that was introduced in Node.js version 8. It allows you to load your own module into the current context without having to reload the entire stack. This can be useful if you need to inject code into a specific part of the application or just want to use a particular module from time to time without restarting everything.

The main advantage of using node js local modules over external loading files is that it takes up less memory and processing resources. Additionally, because nodes will only load the necessary dependencies for your module, it can speed up startup times when used in tandem with other lightweight modules or libraries. 

  • Third-Party Modules

They are a great way to extend the functionality of your node.js applications. They allow you to add new features or modify existing ones without having to build them from scratch.

A great example is the NPM module, which we always install before working with Node.js. Actually, it is a package manager which provides all files needed for a module. We can easily download packages as we need using the command prompt.

E.g., npm install upper-case

Now, the system has created a folder called node_modules where the package upper-case is placed.

Environment Setup

  • Install Node.js

In Linux, open the terminal and use the command “sudo apt install nodejs”. Verify by checking the version of installed Node.js using the command “node -v” or “node-version.”

In windows, download the node.js‘.msi’ installer from the official website of Node.js. Follow the instructions and finish installing process. Then verify it by checking the version in the command prompt using the command “node -v.”

  • Install npm package

In Linux, open the terminal and use the command “sudo apt install npm” and verify by the command “npm -v” or “npm-version”

In Windows, there will be a local npm version after installing Node.js. To update the version, use the command, “npm install npm –global // Updates the ‘CLI’ client.”

  • Install VS code

Download the appropriate package of Visual Studio Code from its official website “https://code.visualstudio.com/Download

Install the following extensions in VS Code to make ease the writing and documenting of coding:

  • JavaScript(ES6)
  • Prettier – Code formatter
  • Live Server
  • Node.js Extension Pack

Data Types

The data types of Node.js is the same as the data types of javascript.

  • Number

            It can be positive, negative, decimal, or non-decimal numbers. In Node.js, the number data type is a 64-bit floating point.

Eg: let x =5;

      let y=25.78;

  • Boolean

            This data type has only two values, either true or false. It is mainly in conditional testing.

E.g., let x=5;

      let y=5;

      (x==y)        => returns true

The data type boolean is also used to control the structure of the program or in logical representations.

  • String

A string can be anything that is wrapped inside single or double quotation marks

E.g., var s= “Hello World.”

  • Function

The function is a grouped set of codes so that it can be reused. Apart from the above-mentioned data types, a function should be declared using the keyword function.

Here the name of the function we have created is the message. The name is an argument of the function message and is placed inside a bracket after the function name. The last line is the function calling so that only the function is executed. While calling this particular function, we passed a string David to the argument name. So, the output of this particular function will be Hello David

  • Array

            An array is a data type where we can store multiple numbers of values.

Printing “Hello World”

In Terminal

Create a file named “main.js” and open it in VS Code. Copy and save the following code in it.

console.log(“Hello World”)

Execute the file using the command node main.js in the terminal; thereby, the terminal shows the message “Hello World.”

In The Window

For this, we are using the http module which is one of the core modules of Node.js

  • Import http module to a variable named http

var http = require(“http”);

  • Create a server using the function createServer in the http module.

Here, we stored the code of printing hello world in the localhost:8080.

  • Run the command node main.js in the terminal. To view the window, just search localhost:8080 in the search bar of the browser

REPL Environment

REPL implies Read, Evaluate Print, and Loop. It is an environment in an interactive mode where the user enters a command, and the system provides its output within the terminal. REPL comes along with the Node.js installation. It is useful to experiment and to check Node.js or javascript codes.

It Reads the command, Evaluates the command, Prints the output, and Loops the process until ctrl+c is pressed twice.

Initiates REPL Environment

We can start REPL simply by running the command node in the command prompt or in the terminal. You can type Node.js commands after the symbol “>” and can see the output.

Simple mathematical calculation

Sum of two numbers using variables

You can even carry out calculations using variables

Print 0-10 numbers

Let’s print the first 11 numbers from 0 using for loop

Global Objects

Global objects are those objects which can be used in every module. _dirname_filenameexports, module, require(), and so on are maybe global objects but are not.

However, we have to learn those objects since they have solid importance in Node.js.

  1. _dirname – stored the directory name of the executing code.

            Eg: console.log(_dirname);

Run the code after saving it in main.js file using the command node main.js.

  • _filename – used to print the name of the file where the code has been written which is to be executed.

            Eg: console.log(_filename);

Run and observe the output.

  • setTimeOut – This object is used to delay a particular output or we can say that it is used to set a timer before executing output.

            Eg: function printMsg(){

console.log(“Hello World”)

       }

       setTimeOut(printMsg, 3000) 

When we execute the file having this code, the message “Hello World” will only print in the

console after 3 seconds of running the code.

  • clearTimeOut – To delete the timer which is previously created.

            Eg: function printMsg(){

console.log(“Hello World”)

       }

      Var t= setTimeOut(printMsg, 3000) ;

      clearTimeOut(t); 

When we execute the file having this code, the message “Hello World” without any delay

  • setIntervel(cb,ms) – After every ms time of intervals cb is executed.

            Eg: Eg: function printMsg(){

console.log(“Hello World”)

       }

       setInterval(printMsg, 3000) 

Hello world will print infinitely after every 3 seconds without any limit. This process only can stop by using clearInterval(t)

Video Streaming website

This is a simple project idea that can created using Node.js. Follow the  steps.

1.Setting up the prerequisities

Create a folder named videoStreaming and open it in VS Code.

Initiate npm by using the command npm init in the terminal of VS Code. package.json will be visible.

Install express module by running npm install –save express nodemon

express is a Node.js module which is used as framework. nodemon is used to restartevry time you save the files. Now, you can see the file package-lock.json.

2.Index.html

Create a file named index.html.Give a title, style to the body and a video tag for streaming video. Do not forget to add a video folder and to link it in the html page.

3.Create index.js.

Import express module using require() and store the functionalities in the variable express.Return the values of the function express to the variable app.

Add start script to package.json to run the server using the command npm start and verify by running the command npm start.

4.Final setup of index.js

First of all download a video a save it as stream.mp4 and sync it the fs variable where we store the functionalities of fs module. Provide a range for the video and ensure it.Add size and path of the video to respective variables. Create headers for the video.

Conclusion

So far, we have discussed very basic aspects of node.js. Node.js provides a strong base regardless of whether the topic is the delivery of services at a small scale, the creation of portable mobile applications, or the integration of non-web frameworks with serverless systems. Along with this, some of the most significant needs that keep growing include speedy performance, enhanced flexibility, and efficient memory utilization.

So, it has a brighter future as a career too. In the end, this tutorial has given you a primary idea of Node.js and how to implement a simple web app. Hope this was helpful to you. Explore Node.js at your maximum by building your own ideas.

Facebook
Twitter
LinkedIn
Pinterest

Leave a Reply

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