Node.js for Beginners: An Easy Guide

Node.js for Beginners: An Easy Guide

Introduction🚀

Node.js

  • Node.js is an open-source language that runs on Google Chrome’s V8 engine.

  • V8 is an open-source engine developed by Google for the Google Chrome browser

  • It is a server-side programming framework that uses JS as its programming lang

      import generateName from "Sillyname";
    
  • Heavy emphasis on concurrent programming with a lightweight language.

  • A single-threaded application that handles results when they are complete.

Backend Responsibility

LoadScalabilityOther Backend Responsibilities
No. of concurrent usersApp ability to handle changes in load affecting performanceSecurity
No. of concurrent transactionsEssential for client-server application successAuthentication
Amount of concurrent data transfer between clients & serversMalware Prevention
Performance

Node.js Functionality

  • Developers frequently use js to code client-side capabilities. Node.js is a server component in the same language.

  • It is event-driven & uses asynchronous , non-blocking I/O

Node.js Usage

  • Developers can now use Node.js in the same components of the architecture where they use Java, Perl, C++, Python & Ruby

  • It is used in production by companies like user, PayPal, etc.

Package Manager

A set of tools to deal with modules & packages containing dependencies called a package management system, Maintain a database of dependencies & versioning, Ensure software has correct dependencies

Package manager responsibilities

i) Automate:-

  • Finding

  • Installing

  • upgrading

  • configuring

  • maintaining

  • removing

NPM (Node Package Manager)

  • It’s a place that collects modules that people have built for Node & the GitHub Organization creates it

  • NPM comes with a pre-bundled Node

  • For Node.js, it serves as the default package management.

  • It provides a CLI to publish & download packages

  • It behaves as an online repository of JS. package

  • The repository is a database of packages that tracks package versions.

Package.json: the module manifest

  • A package consists of one or more modules

  • Every package has a package.json file that describes details about a Node.js module.

Package.json File

  • File located in a project’s root directory

  • NPM uses package.json to determine dependencies

  • contains key-value pairs that identify the project

  • Must contain

  1. Project name

  2. Project Version

{
"name" : "thisproject",
"version" : "0.0.1",
}

Local Install

  • NPM Package can be installed locally or globally

  • use local install for use with packages within your application

  • run the local install command from the directory you want the package installed in

  • Use NPM CLI - npm install <package_name>

  • This command creates a directory named node_modules with the package & its dependencies in your current working directory

Global Install

  • Packages can also be installed globally

  • All applications on the machine will use a globally installed package

  • use judiciary

  • NPM CLI for Global - npm install -g <package_name>

Dependencies

  • code in the form of a library or a package revised in a program

  • Libraries & packages contain many dependencies

  • A library does not depend on code outside of it to function

Node.js Modules

  • Every JS file is a module in Node.js

  • multiple modules can be grouped into a package

Native Node Module

  • It has many modules for specific purposes & there are many methods present in the modules

  • Related, encapsulated js code

  • serves a single purpose

  • can be a single file or a folder containing files

  • reusable

Importing Node.js modules

Each Node.js module consisting of a single script uses the required function with a relative path to the script file.

Export functions & Properties

  • Each Node.js module that consists of a single script uses the required function with a relative path to the script file.

  • To make a function or a value available to node.js applications that import your modules, add a property to exports

Accessing Exported properties

  • When you import a Node.js module, the required function returns a JS object representing an instance of the module.

  • To access the properties of the module, retrieve the property from the variable

Purpose of import() & require

when an external application needs to use the code in a module

ECMAScript Modules

Node 12 version as ECMAScript so here we use the keyword import as require a keyword is used in previous versions

Type CJS

var generateName = require("Sillyname");

Type ES

import generateName from "Sillyname";

Difference Between require() & import()

require() - common jsimport() - ES
can be called anywhere in the codecan only be called at the beginning of the file
can be called with conditionals & functionscannot be called within conditionals or function
DynamicStatic
Binding errors are not identified until runtimeBinding errors identified at compile time
SynchronousAsynchronous
Import a module use - require()Import a module use - import()
Export from a module use - module.exportsExport from a module use -export

Note - To specify a difference main script for your module, specify a relative path to the node.js script from the module directory

Packages & Specifications

  • Package - a directory with one or more modules

  • Module Specifications:- conventions & standards used to create packages, common Js, ES

Initialize a Node.js Project

  1. npm init

  2. Give all information for the package.json file

  3. Hit yes to create it

Install NPM Package

npm install <something> //Here something is the name of the module

Create a simple web server: HTTP

let server = http.createServer(function(request, response)){
let body = "Hello world!";
response.writeHead(200, {
'content-length' : body.length,
'content-Type' : text/plain
});
resonse.end(body)
});
server.listen(8080);

Asynchronous I/O

  • Network operations run asynchronously, for ex - the response from a web service call might not return immediately

  • When an application blocks (or waits) for a network operation to complete, that application wastes processing time on the server.

  • Node.js makes all network operations in a non-blocking manner

  • Every network operation returns immediately

  • To handle the result from a network call, you can write a callback function that Node.js calls when the network operation completes

Callback Functions

  • A function passes as an argument to another function

  • Used to ensure an action is executed only after callback

Example -

const message = function(){
console.log("This message is shown after 3 seconds");
}
setTimeout(message,3000);

Sending an HTTP Request

let options = {
host : 'w1.weather.gov',
path : '/xml/current_obs/KSFO.xml'
};

http.request(options, function(response){
let buffer = "";
let result = "";

response.on('data',function(chunk)){              // when the Node.js module calls this anonymous func events occur while receiving parts of the http response message
buffer += chunk;
)};
response.on('end', function(){                   //In the actual coding , we may need to use https
console.log(buffer);
});
}).end();

HTTP request options & callback

  • The HTTP request function calls the callback function parameter when it receives part of the HTTP response

  • The callback function parameter is optional, you can send an HTTP request & disregard the response message (object)

  • Example - http.request(options , [callback function])

HTTP response options & callback

  • when an HTTP request calls the callback function, it passes a response object in the first parameter

  • Example - http.request(options, function(response){ … });

Handling response events

http.request(options , function (response){
let buffer = '';                          
response.on('data', function(chunk)){
buffer += chunk;
});
response.on('end',function(){
console.log(buffer);
});
}).end();
  • In node.js, the object.on() func defines an event handler that the framework calls when an event occurs

  • Forex - the response object in the http.request callback function emits events when the node.js module receives parts of the HTTP response message from the remote server

  • The response object emits a ‘data’ event when the Node.js module receives a part of the HTTP response message, the response object emits an ‘end’ event

Handling error events

  • If the request fails, there is an ‘error’ event followed by the ‘end’ event
request.on('error',function(e){
result callback(e.message);
});
request.end();
  • With the http.client Response object, you can :
  1. Write data to the HTTP request message body.

  2. Add headers to the HTTP request message body.

  3. Define an event handler for errors that Node.js encounters while sending the request

  • call clientRequest.end() to complete sending the request, Ex - request.end()

Propagating Errors

  • Node.js makes extensive use of callback functions to return the result to the calling function

  • Node.js modules pass an error object as the 1st parameter in a callback functions


 [Call function(error)] - Node.js Modules
                  |
               callback
  • With this convention, the callback function checks if the first parameter holds an error object.

    function (error parameter1 , parameter2 ,..){…}

  • If an error is defined, the callback function handles the error & cleans up any open network or database connections

  • If error is not defined, then the callback function examines the result from the call

Callback with Error Handling

weather.current(location, function(error , temp_f){
if(error){
console.error(error);
return;
};
console.log(
"The current weather reading is %s degrees";
temp_f
);
});
response.end("..${temp_f}..")
// If the error parameter is defined , print the error
// Otherwise, the weather.current function call completed successfully
// Print the result from the function call

Passing an error Object

exports.current = function(location, result(callback){
http.request(options , function(response){
let buffer = '';
let result = '';
response.on('data', function(chunck){
buffer += chunk;
});
response.on('end', function(){
parseString(buffer, function(error, result){
if (error){
result callback(erorr);
return;
}
result callback(null , result.current_observation.temp_f[0]);
});
});
});

// If the parseString passes an error object, pass the error back to the result callback function of the origional caller (main application)
//set the first parameter as null if there is no erorr

One Callback at each level

  • when one Node.js application calls a module in a non-blocking manner, the application must provide a callback function to process the result

  • If the main application calls a function that calls http.request(), two callback functions are involved:-

    1. The custom module has a callback function to handle the HTTP response message from http.request()

    2. The main application has a callback function that processes the result captured in the 1st callback function

Promises

  • An object returned by an asynchronous method

  • States: pending, resolved, rejected

  • Uses: API requests, I/O Operations

JSON

  • JSON is mostly used for API data exchange because it is the standard representation of JS Objects, Node.js handles JSON easily

  • We have a method in javascript known as JSON.parse() , this method used to parse a JSON string to a JS object

  • We have another method known as JSON.stringify() , this method used to convert a JS object to a JSON string

Extend Node.js with 3rd party packages

  • The Node.js provides a small amount of features for building apps.

  • For Example, Node.js does not provide a parsing function for extensible markup language(XML) messages.

  • Developers rely on 3rd party packages to extend Node.js features

Conclusion
This article provides a comprehensive overview of Node.js, its functionality, usage, and key responsibilities in backend development, covering installation, package management, web server creation, asynchronous I/O, callback functions, HTTP requests, error handling, and module systems.

Follow Me On Socials :

LinkedIn

Twitter

GitHub

Like👍| Share📲| Comment💭

Did you find this article valuable?

Support MOHD NEHAL KHAN by becoming a sponsor. Any amount is appreciated!