You are on page 1of 69

NODE JS

Introduction to Node.js
Installation
Features
Node.js Basics
Applications
Node. Js.REPL
Node.js NPM
Node.js Global objects
Node. Js local module
Node. Js assert module
Node. Js buffer module
Node. Js console module
Node. Js DNS module
Node. Js File system module
Node. Js Globals
Node. Js HTTP module
Node. Js OS module
Node. Js url module
Node. Js VM module
Node.js V8 module

Introduction
Node JS is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine
for executing JavaScript code outside of a browser. It provides an event-driven, non-blocking
(asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side
applications using JavaScript.
Most people are confused and understand it’s a framework or a programing language. We
often use NodeJS for building back-end services like APIs, Web App, or Mobile App. It’s
utilized in production by large companies like Paypal, Uber, Netflix, Walmart, etc.

Why to learn Node JS?

Learning JavaScript is necessary these days in the development field. Anyhow you have to
use JavaScript on the front end. So it is better to learn NodeJS rather than learn other
backend technologies like PHP, JAVA, Ruby, etc. NodeJS is the hottest technology across the
world, especially in Silicon Valley. It is the perfect skill to open up amazing career
opportunities for any software developer.

installation of Node JS

To install NodeJS, we have separate articles for Linux and windows please go through the
required process.
Setting up the Node Development Environment
The Node can be installed in multiple ways on a computer. The approach used by you
depends on the existing development environment in the system. There are different
package installer for different environments. You can install Node by grabbing a copy
of the source code and compiling the application. Another way of installing Node is by
cloning the GIT repository in all the three environments and then installing it on the
system.
Installing Node On Windows (WINDOWS 10):
You have to follow the following steps to install the Node.js on your Windows :
Step-1: Downloading the Node.js ‘.msi’ installer.
The first step to install Node.js on windows is to download the installer. Visit the
official Node.js website i.e) https://nodejs.org/en/download/ and download the .msi file
according to your system environment (32-bit & 64-bit). An MSI installer will be
downloaded on your system.

Step-2: Running the Node.js installer.


Now you need to install the node.js installer on your PC. You need to follow the
following steps for the Node.js to be installed:-
 Double click on the .msi installer.
The Node.js Setup wizard will open.
 Welcome To Node.js Setup Wizard.
Select “Next”

 After clicking “Next”, End-User License Agreement (EULA) will open.
Check “I accept the terms in the License Agreement”
Select “Next”


 Destination Folder
Set the Destination Folder where you want to install Node.js & Select “Next”


 Custom Setup
Select “Next”

 Ready to Install Node.js.


The installer may prompt you to “install tools for native modules”.
Select “Install”

 Installing Node.js.
Do not close or cancel the installer until the install is complete
 Complete the Node.js Setup Wizard.
Click “Finish”

Step 3: Verify that Node.js was properly installed or not.


To check that node.js was completely installed on your system or not, you can run the
following command in your command prompt or Windows Powershell and test it:-
C:\Users\Admin> node -v
If node.js was completely installed on your system, the command prompt will print the
version of the node.js installed.
If you get a message back saying node was not found, then add it to the path manually:
Adding to the path:
You should not need to do anything to the system variables, as the windows installer
takes care of the system variables itself while installing through the .msi installer.
If you use any other format for installing node.js on your PC, you should put the system
variable path for node.js as follows:
PATH : C:\Users\{username}\AppData\Roaming\npm C:\Program Files\{path
to the nodejs folder}
for example:
PATH : C:\Users\admin\AppData\Roaming\npm C:\Program Files\nodejs
Note: After adding to the PATH, restart the command line, because PATH is only
loaded when initializing new command line sessions.
Step 4: Updating the Local npm version.
The final step in node.js installed is the updation of your local npm version(if required)
– the package manager that comes bundled with Node.js.
You can run the following command, to quickly update the npm
npm install npm –global // Updates the ‘CLI’ client
Installation of Node.js on Linux
Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js can be
installed in multiple ways on your Ubuntu Linux machine. You can use Ubuntu’s
official repository to install Node.js or another way to use NodeSource repository.
Installation via NodeSource repository will allow you to choose latest version of
Node.js.
Installing Node On Ubuntu 18.04 and 16.04: There are two methods Ubuntu official
repository and NodeSouce repository to install Node.js on Ubuntu.
Install Node.js using Ubuntu official repository: Node.js is available in Ubuntu’s
repository and you can easily install it using a few commands. Follow the steps below
to install Node.js on your Ubuntu operating system.
 Step 1: Open your terminal or press Ctrl + Alt + T.

 Step 2: To install node.js use the following command:

sudo apt install nodejs


 Step 3: Once installed, verify it by checking the installed version using the
following command:

node -v or node –version


Note: It is recommended to install Node Package Manager(NPM) with Node.js. NPM is
an open source library of Node.js packages.
To install NPM, use the following commands:
sudo apt install npm
npm -v or npm –version
Node and NPM will be successfully installed on your Ubuntu machine.

Install Node.js using NodeSouce repository: The latest version of Node.js can be
installed from NodeSource repository. Follow the steps below to install the Node.js on
your Ubuntu.
 Step 1: Open your terminal or press Ctrl + Alt + T and use the following
commands to update and upgrade the package manager:

sudo apt-get update


sudo apt-get upgrade
 Step 2: Install Python software libraries using the following command:

sudo apt-get install python-software-properties

 Step 3: Add Node.js PPA to the system.

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash –


Note: Here, we are installing node.js version 10, if you want to install version
11, you can replace setup_10.x with setup_11.x.

 Step 4: To Install Node.js and NPM to your Ubuntu machine, use the
command given below:

sudo apt-get install nodejs

 Step 5: Once installed, verify it by checking the installed version using the
following command:

node -v or node –version


npm -v or npm –version

Finally, you have successfully installed Node.js and NPM on your Ubuntu machine.

NODE .JS BASICS


Node.js is a cross-platform JavaScript runtime environment. It allows the creation of
scalable Web servers without threading and networking tools using JavaScript and a
collection of “modules” that handle various core functionalities. It can make console-
based and web-based node.js applications.
Datatypes: Node.js contains various types of data types similar to JavaScript.
 Boolean
 Undefined
 Null
 String
 Number
Loose Typing: Node.js supports loose typing, which means you don’t need to specify
what type of information will be stored in a variable in advance. We use the var and let
keywords in Node.js declare any type of variable. Examples are given below:
Example:
 javascript

// Variable store number data type


let a = 35;
console.log(typeof a);

// Variable store string data type


a = "GeeksforGeeks";
console.log(typeof a);

// Variable store Boolean data type


a = true;
console.log(typeof a);

// Variable store undefined (no value) data type


a = undefined;
console.log(typeof a);

Output:
number
string
boolean
undefined
Objects & Functions: Node.js objects are the same as JavaScript objects i.e. the
objects are similar to variables and it contains many values which are written as name:
value pairs. Name and value are separated by a colon and every pair is separated by a
comma.
Example:
 javascript

let company = {
Name: "GeeksforGeeks",
Address: "Noida",
Contact: "+919876543210",
Email: "abc@geeksforgeeks.org"
};

// Display the object information


console.log("Information of variable company:", company);

// Display the type of variable


console.log("Type of variable company:", typeof company);

Output:
Information of variable company: {
Name: 'GeeksforGeeks',
Address: 'Noida',
Contact: '+919876543210',
Email: 'abc@geeksforgeeks.org'
}
Type of variable company: object
Functions: Node.js functions are defined using the function keyword then the name of
the function and parameters which are passed in the function. In Node.js, we don’t have
to specify datatypes for the parameters and check the number of arguments received.
Node.js functions follow every rule which is there while writing JavaScript functions.
Example:
 javascript

function multiply(num1, num2) {

// It returns the multiplication


// of num1 and num2
return num1 * num2;
}

// Declare variable
let x = 2;
let y = 3;

// Display the answer returned by


// multiply function
console.log("Multiplication of", x,
"and", y, "is", multiply(x, y));

Output:
Multiplication of 2 and 3 is 6
As you observe in the above example, we have created a function called “multiply”
with parameters the same as JavaScript.
String and String Functions: In Node.js we can make a variable a string by assigning
a value either by using single (”) or double (“”) quotes and it contains many functions
to manipulate strings. Following is the example of defining string variables and
functions in node.js.
Example:
 javascript

let x = "Welcome to GeeksforGeeks ";

let y = 'Node.js Tutorials';

let z = ['Geeks', 'for', 'Geeks'];

console.log(x);

console.log(y);

console.log("Concat Using (+) :", (x + y));

console.log("Concat Using Function :", (x.concat(y)));

console.log("Split string: ", x.split(' '));

console.log("Join string: ", z.join(', '));

console.log("Char At Index 5: ", x.charAt(5));

Output:
Welcome to GeeksforGeeks
Node.js Tutorials
Concat Using (+) : Welcome to GeeksforGeeks Node.js Tutorials
Concat Using Function : Welcome to GeeksforGeeks Node.js Tutorials
Split string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ]
Join string: Geeks, for, Geeks
Char At Index 5: m
Buffer: In node.js, we have a data type called “Buffer” to store binary data and it is
useful when we are reading data from files or receiving packets over the network.
 Javascript

let b = new Buffer(10000);//creates buffer


let str = " ";
b.write(str);
console.log(str.length);//Display the information
console.log(b.length); //Display the information

1
10000
Node.js console-based application: Make a file called console.js with the following
code.
 javascript

console.log('Hello this is the console-based application');

console.log('This all will be printed in console');

// The above two lines will be printed in the console.

To run this file, open the node.js command prompt and go to the folder where
the console.js file exists and write the following command. It will display content on
console.
The console.log() method of the console class prints the message passed in the method
in the console.
Node.js web-based application: Node.js web application contains different types of
modules which is imported using require() directive and we have to create a server and
write code for the read request and return response. Make a file web.js with the
following code.
Example:
 javascript

// Require http module


let http = require("http");

// Create server
http.createServer(function (req, res) {

// Send the HTTP header


// HTTP Status: 200 : OK
// Content Type: text/plain
res.writeHead(200, { 'Content-Type': 'text/plain' });

// Send the response body as "This is the example


// of node.js web based application"
res.end('This is the example of node.js web-based application \n');

// Console will display the message


}).listen(5000,
() => console.log('Server running at http://127.0.0.1:5000/'));

To run this file follow the steps as given below:


 Search the node.js command prompt in the search bar and open the node.js
command prompt.
 Go to the folder using cd command in command prompt and write the
following command node
web.js

 Now the server has started and go to the browser and open this
url localhost:5000

You will see the response which you have sent back from web.js in the browser. If any
changes are made in the web.js file then again run the command node web.js and
refresh the tab in the browser.
NODE.JS FIRST APPLICATION
Node.js is an open source, cross-platform server environment which executes
JavaScript using V8 JavaScript Engine. Node.js helps to write front-end and back-end
code in the same language. It helps to write efficient code for real-time applications. In
Node.js, the applications can be written using console-based method or web-based
method.
Console based Node.js Application: The Node.js console-based applications are run
using Node.js command prompt. Console module in Node.js provide a simple
debugging console. Node.js is a global console which can be used for synchronous as
well as asynchronous communication. The console.log() function is used to display
output on console. This function prints output to stdout with newline.
Syntax:
console.log([data][, ...]);
Here, data is the content to be displayed on console.
Example 1: Creating a Hello World application using Node.js. Create a geeks.js file
containing the following code:
console.log('Hello World');

Run the file on Node.js command prompt using command node geeks.js i.e. node
<file_name> .
Output:

Example 2: Creating a Hello World application receiving the user input. Create a gfg.js
file containing the following code.
console.log(process.argv.slice(2));

The process.argv is used to provide command line argument to a program. Use the slice
function with 2 as its argument to get all the elements of argv that comes after its
second element, i.e. the arguments the user entered The first argument is location of the
Node.js binary which runs the program and the second argument is location of the file
being run.
Output:

Web-based Node.js Application: A web-based Node.js application consists of the


following three important components:
 Import required modules: Load Node.js modules using the require
directive. Load http module and store returned HTTP instance into a variable.
Syntax:
var http = require("http");
 Create server: Create a server to listen the client’s requests. Create server
instance using createServer() method. Bind server to port 8080 using listen
method associated with server instance.
Syntax:
http.createServer().listen(8080);
 Read request and return response: Read the client request made using
browser or console and return the response. A function with request and
response parameters is used to read client request and return response.
Syntax:
http.createServer(function (request, response)
{...}).listen(8080);
Example: This example create a Hello World web-based application using Node.js.
Create a firstprogram.js file containing the following code.
// 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 command node firstprogram.js and
type http://127.0.0.1:8080/ in a web browser to see the output.
Output:

NODE. JS REPL(READ,EVAL,PRINT,LOOP)
Node.js is an open source server-side Javascript run-time environment built
on Chrome’s JavaScript Engine(V8). Node.js is used for building fast and scalable
applications and is an event driven, non-blocking I/O model.
REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell
(Unix/Linux) and command prompt. Node comes with the REPL environment when it
is installed. System interacts with the user through outputs of commands/expressions
used. It is useful in writing and debugging the codes. The work of REPL can be
understood from its full form:
Read : It reads the inputs from users and parses it into JavaScript data structure. It is
then stored to memory.
Eval : The parsed JavaScript data structure is evaluated for the results.
Print : The result is printed after the evaluation.
Loop : Loops the input command. To come out of NODE REPL, press ctrl+c twice
Getting Started with REPL:
To start working with REPL environment of NODE; open up the terminal (in case of
UNIX/LINUX) or the Command prompt (in case of Windows) and write node and
press ‘enter’ to start the REPL.
The REPL has started and is demarcated by the ‘>’ symbol. Various operations can be
performed on the REPL. Below are some of the examples to get familiar with the REPL
environment.
Example: Performing Arithmetical operations in REPL

Arithmetical operations in REPL

Example: Performing operations using libraries of NODE. MATH library is being


used in below example.

Math library methods gfg

Note: using ‘math’ shows error as the library is referenced as ‘Math’ in NODE and
not ‘math’.
Example: Using variables in REPL. The keyword var is used to assign values to
variables.
Using Variables in REPL

Example: Using loops in REPL. Loops can be used in REPL as in other editors.

Note: Use ctrl – c to terminate the command and ctrl – c twice to terminate the NODE
REPL.
.help is used to list out all the commands.

NODE.JS NPM
NPM (Node Package Manager) is the default package manager for Node.js and is
written entirely in Javascript. Developed by Isaac Z. Schlueter, it was initially released
in January 12, 2010. NPM manages all the packages and modules for Node.js and
consists of command line client npm. It gets installed into the system with installation
of Node.js. The required packages and modules in Node project are installed using
NPM.
A package contains all the files needed for a module and modules are the JavaScript
libraries that can be included in Node project according to the requirement of the
project.
NPM can install all the dependencies of a project through the package.json file. It can
also update and uninstall packages. In the package.json file, each dependency can
specify a range of valid versions using the semantic versioning scheme, allowing
developers to auto-update their packages while at the same time avoiding unwanted
breaking changes.
Some facts about NPM:
 At the time of writing this article, NPM has 580096 registered packages. The
average rate of growth of this number is 291/day which outraces every other
package registry.
 npm is open source
 The top npm packages in the decreasing order are: lodash, async, react,
request, express.
Installing NPM:
To install NPM, it is required to install Node.js as NPM gets installed with Node.js
automatically.
Install Node.js.
Checking and updating npm version:
Version of npm installed on system can be checked using following syntax:
Syntax:
npm -v

Checking npm version


If the installed version is not latest, one can always update it using the given syntax:
Syntax:
npm update npm@latest -g.
As npm is a global package, -g flag is used to update it globally.
Creating a Node Project:
To create a Node project, npm init is used in the folder in which user want to create
project. The npm command line will ask a number of questions like name, license,
scripts, description, author, keywords, version, main file etc. After npm is done
creating the project, a package.json file will be visible in project folder as a proof that
the project has been initialized.

npm init

Installing Packages:
After creating the project, next step is to incorporate the packages and modules to be
used in the Node Project. To install packages and modules in the project use the
following syntax:
Syntax:
npm install package_name
Example: Installing the express package into the project. Express is the web
development framework used by the Node.
Syntax:
npm install express
To use express in the Node, follow the below syntax:
Syntax:
var express = require('express');

Installing express module

Example: To install a package globally (accessible by all projects in system), add an


extra -g tag in syntax used to install the package.
Installing nodemon package globally.
npm install nodemon -g

Installing nodemon package globally

Controlling where the package gets installed:


To install a package and simultaneously save it in package.json file (in case using
Node.js), add –save flag. The –save flag is default in npm install command so it is
equal to npm install package_name command.
Example:
npm install express --save
By –save flag one can control where the packages are to be installed.
–save-prod : Using this packages will appear in Dependencies which is also by default.
–save-dev : Using this packages will get appear in devDependencies and will only be
used in the development mode.
Example: npm install node-color –save-dev

–save-dev example

If there is a package.json file with all the packages mentioned as dependencies already,
just type npm install in terminal. npm will look at package.json file and install all the
dependencies according to their mentioned versions. This command is typically used
when a Node project is forked and cloned. The node_modules being a big folder is
generally not pushed to a github repo and the cloner has to run npm install to install the
dependencies.
Note: NPM installs the dependencies in local mode (Default) which go to
the node_modules directory present in the folder of Node application. To see all the
locally installed modules use npm ls command.
Uninstalling Packages:
To uninstall packages using npm, follow the below syntax:
Syntax:
npm uninstall
Example: To uninstall the express package
Uninstalling express

To uninstall global packages, follow the below syntax:


Syntax:
npm uninstall package_name -g
Using Semantic Versioning to manage packages:

 To install a package of a specific version, mention the full and exact version
in the package.json file.
 To install the latest version of the package, mention “*” in front of the
dependency or “latest”. This will find the latest stable version of the module
and install it.
 To install any version (stable one) above a given version, mention it like in
the example below:
“express”:”^4.1.1″. in package.json file. The caret symbol (^) is used to tell
the npm to find a version greater than 4.1.1 and install it.
NODE.JS GLOBAL OBJECTS
Node.js is an open-source project that can be used for server-side scripting. Node.js
Global Objects are the objects that are available in all modules. Global Objects are
built-in objects that are part of the JavaScript and can be used directly in the application
without importing any particular module. The Node.js Global Objects are listed below:

1.Class: Buffer The Buffer class is an inbuilt globally accessible class that means it can
be used without importing any module. The Buffer class is used to deal with binary
data. Buffer class objects are used to represent binary data as a sequence of bytes.

 console: It is an inbuilt global object used to print to stdout and stderr.

 process: It is an inbuilt global object that is an instance of EventEmitter used


to get information on current process. It can also be accessed using require()
explicitly.
 global: It is a global namespace. Defining a variable within this namespace
makes it globally accessible.

var myvar
2.It is a global scope when declared within the browser. However, any variable defined
within a node.js file is accessible only within that file.
 setImmediate() method: It schedules the immediate execution of the
callback. The callback functions are queued and executed in the order in
which they are created. The callback queue is processed at every event loop
iteration. If there is a timer queued inside the executing callback, the timer
will not get triggered until the next event loop iteration.
 clearImmediate() method: It stops the immediate object returned by the
setImmediate() method.
 setInterval() method: It executes the callback function at repeated intervals.
If an interval is larger than 2147483647 or less than 1, the interval is set to 1.
Non-integer delays are truncated to the nearest integer.
 clearInterval() method: It stops the interval object created by setInterval()
method.

 setTimeout() method: It is a global function used to run a callback function


after at least delay in milliseconds. Node.js does not guarantee the exact
timing of when callbacks will fire but tries to maintain the timing as close as
possible to the specified delay. Any delay larger than 2147483647 or less
than 1, is set to 1 automatically. Non-integer delays are truncated to the
nearest integer.

function printHello() {
console.log( "Hello, World!");
}

// Now call above function after 2 seconds


var timeoutObj = setTimeout(printHello, 2000);
 clearTimeout() method: The clearTimeout() method is used to cancel or
stop a timeout that was set with setTimeout() method. The timeoutObj is the
object returned by setTimeout() method.

 queueMicrotask() method: A microtask is a short function that is executed


after the callback function exits and only if the JavaScript execution stack is
empty. The queueMicrotask() method is used to execute such functions after
the callback function completes successfully. If the callback function does
not return the control to other JavaScript code, the event loop runs all of the
microtasks in the microtask queue. The microtask queue is processed multiple
times per iteration of the event loop. If a microtask adds more microtasks to
the queue then the newly-added microtasks execute before the next task is
run. This is because the event loop keeps calling microtasks until there are
none left in the queue.
 TextEncoder: It is an implementation of the WHATWG Encoding Standard
TextEncoder API. All instances of TextEncoder are encoded in UTF-8 only.

3.TextDecoder: It is an implementation of the WHATWG Encoding Standard


TextDecoder API.
4.Class: URL The URL class instance is a global object and is implemented by the
following WHATWG URL Standard. The URL constructor creates a new URL object
as shown below. /foo is the input and https://www.helloworld.og/ is the base value.

5.URLSearchParams: URLSearchParams API is used to perform read and write


operations on the query of a URL.

const myURL = new URL('https://www.register.com/?name=gfg');


// It prints gfg
console.log(myURL.searchParams.get('name'));

myURL.searchParams.append('name', 'xyz');

// It prints https://www.register.com/?name=gfg&name=xyz
console.log(myURL.href);
6.WebAssembly: The global object that acts as a namespace for all W3C
WebAssembly related functionality. WebAssembly is a low level Assembly-like
language that can be run on modern browsers.
The following variables might appear to be global but actually exist only within the
scope of some modules.
 require(id) method: It is used to import modules and returns an object of
‘any’ datatype.
var express = require('express')
 exports: It is used to exports modules using module.exports.
 module: It is a reference to the current module and is not global rather local
to each module. It is used to make a particular module available through
require() in the application.

 __dirname: The output throws an error which proves that __dirname is not
globally defined in node.js. It requires a script to give the desired output as
__dirname is only defined in scripts.

 Create a demo.js file


 Paste the following code:
console.log("__dirname : "+ __dirname);
 Run the demo.js file
7.__filename: The output throws an error which proves that __filename is not globally
defined in node.js. It requires a script to give the desired output as __filename is only
defined in scripts.

 Create a demo.js file


 Paste the following code:
console.log("__filename : "+ __filename);
 Run the demo.js file

NODE.JS MODULES
In Node.js, Modules are the blocks of encapsulated code that communicate with an
external application on the basis of their related functionality. Modules can be a single
file or a collection of multiple files/folders. The reason programmers are heavily reliant
on modules is because of their reusability as well as the ability to break down a
complex piece of code into manageable chunks.
Modules are of three types:
 Core Modules
 local Modules
 Third-party Modules
Core Modules: Node.js has many built-in modules that are part of the platform and
come with Node.js installation. These modules can be loaded into the program by using
the required function.
Syntax:
const module = require('module_name');
The require() function will return a JavaScript type depending on what the particular
module returns. The following example demonstrates how to use the Node.js http
module to create a web server.

 javascript

const http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('Welcome to this page!');
res.end();
}).listen(3000);

In the above example, the require() function returns an object because the Http module
returns its functionality as an object. The function http.createServer() method will be
executed when someone tries to access the computer on port 3000. The res.writeHead()
method is the status code where 200 means it is OK, while the second argument is an
object containing the response headers. The following list contains some of the
important core modules in Node.js:

Core Modules Description

http creates an HTTP server in Node.js.

assert set of assertion functions useful for testing.

fs used to handle file system.

path includes methods to deal with file paths.

process provides information and control about the current Node.js process.

os provides information about the operating system.

querystring utility used for parsing and formatting URL query strings.

url module provides utilities for URL resolution and parsing.

Local Modules: Unlike built-in and external modules, local modules are created locally
in your Node.js application. Let’s create a simple calculating module that calculates
various operations. Create a calc.js file that has the following code:
Filename: calc.js
 javascript

exports.add = function (x, y) {


return x + y;
};

exports.sub = function (x, y) {


return x - y;
};

exports.mult = function (x, y) {


return x * y;
};

exports.div = function (x, y) {


return x / y;
};

Since this file provides attributes to the outer world via exports, another file can use its
exported functionality using the require() function.
Filename: index.js
 javascript

const calculator = require('./calc');

let x = 50, y = 10;

console.log("Addition of 50 and 10 is "


+ calculator.add(x, y));

console.log("Subtraction of 50 and 10 is "


+ calculator.sub(x, y));

console.log("Multiplication of 50 and 10 is "


+ calculator.mult(x, y));

console.log("Division of 50 and 10 is "


+ calculator.div(x, y));

Step to run this program: Run the index.js file using the following command:
node index.js
Output:
Addition of 50 and 10 is 60
Subtraction of 50 and 10 is 40
Multiplication of 50 and 10 is 500
Division of 50 and 10 is 5
Note: This module also hides functionality that is not needed outside of the module.
Third-party modules: Third-party modules are modules that are available online using
the Node Package Manager(NPM). These modules can be installed in the project folder
or globally. Some of the popular third-party modules are Mongoose, express, angular,
and React.
Example:
 npm install express
 npm install mongoose
 npm install -g @angular/cli

Node.js Local Module


Node.js comes with different predefined modules (e.g. http, fs, path, etc.) that we use
and scale our project. We can define modules locally as Local Module. It consists of
different functions declared inside a JavaScript object and we reuse them according to
the requirement. We can also package it and distribute it using NPM.
Defining local module: Local module must be written in a separate JavaScript file. In
the separate file, we can declare a JavaScript object with different properties and
methods.
Step 1: Create a local module with the filename Welcome.js
 javascript

const welcome = {

sayHello: function () {
console.log("Hello GeekforGeeks user");
},

currTime: new Date().toLocaleDateString(),

companyName: "GeekforGeeks"
}

module.exports = welcome

Explanation: Here, we declared an object ‘welcome’ with a function sayHello and two
variables currTime and companyName. We use the module.export to make the object
available globally.
Part 2: In this part, use the above module in the app.js file.
 javascript

const local = require("./Welcome.js");


local.sayHello();
console.log(local.currTime);
console.log(local.companyName);

Explanation: Here, we import our local module ‘sayHello’ in a variable ‘local’ and
consume the function and variables of the created modules.
Output:
Hello GeekforGeeks user
12/6/2019
GeekforGeeks

Node.js Assert module


Assert module in Node.js provides a bunch of facilities that are useful for the assertion
of the function. The assert module provides a set of assertion functions for verifying
invariants. If the condition is true it will output nothing else an assertion error is given
by the console.
Install the assert module using the following command:
npm install assert
Note: Installation is an optional step as it is inbuilt Node.js module.
Importing module:
const assert = require("assert");
Example 1:
console.clear()
const assert = require('assert');

let x = 4;
let y = 5;

try {

// Checking condition
assert(x == y);
}
catch {

// Error output
console.log(
`${x} is not equal to ${y}`);
}

Output:

Example 2:
console.clear()
const assert = require('assert');

let x = 4;
let y = 5;

assert(x > y);

Note: In this example, no try-catch is given so an assertion error of the kind given
below will be the output.
Output:
Node.js Buffers
Buffers are instances of the Buffer class in Node.js. Buffers are designed to handle
binary raw data. Buffers allocate raw memory outside the V8 heap. Buffer class is a
global class so it can be used without importing the Buffer module in an application.
Creating Buffers: Followings are the different ways to create buffers in Node.js:

 Create an uninitiated buffer: It creates the uninitiated buffer of given size.


Syntax:

var ubuf = Buffer.alloc(5);


 The above syntax is used to create an uninitiated buffer of 5 octets.
 Create a buffer from array: It creates the buffer from given array.
Syntax:

var abuf = new Buffer([16, 32, 48, 64]);


 The above syntax is used to create a buffer from given array.
 Create a buffer from string: It creates buffer from given string with
optional encoding.
Syntax:

var sbuf = new Buffer("GeeksforGeeks", "ascii");


 The above syntax is used to create a Buffer from a string and encoding type
can also be specified optionally.
Writing to Buffers in Node.js: The buf.write() method is used to write data into a
node buffer.
Syntax:

buf.write( string, offset, length, encoding )


The buf.write() method is used to return the number of octets in which string is
written. If buffer does not have enough space to fit the entire string, it will write a part
of the string.
The buf.write() method accepts the following parameters:

 string: It specifies the string data which is to be written into the buffer.
 offset: It specifies the index at which buffer starts writing. Its default value is
0.
 length: It specifies the number of bytes to write. Its default value is
buffer.length.
 encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.
Example: Create a buffer.js file containing the following codes.

javascript
// Write JavaScript code here
cbuf = new Buffer(256);
bufferlen = cbuf.write("Learn Programming with GeeksforGeeks!!!");
console.log("No. of Octets in which string is written : "+ bufferlen);

Output:

Reading from Buffers: The buf.toString() method is used to read data from a node
buffer.
Syntax:

buf.toString( encoding, start, end )


The buf.toString() method accepts the following parameters:

 encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.


 start: It specifies the index to start reading. Its default value is 0.
 end: It specifies the index to end reading. Its default value is complete buffer.
Example 1: Create a buffer.js file containing the following code.

javascript
// Write JavaScript code here
rbuf = new Buffer(26);
var j;

for (var i = 65, j = 0; i < 90, j < 26; i++, j++) {


rbuf[j] = i ;
}

console.log( rbuf.toString('ascii'));
Output:

Example 2: Read the data from Node.js buffer specifying the start and end point of
reading. Create a buffer.js file containing the following code.

javascript
// Write JavaScript code here
rbuf = new Buffer(26);
var j;

for (var i = 65, j = 0; i < 90, j < 26; i++, j++) {


rbuf[j] = i ;
}

console.log( rbuf.toString('utf-8', 3, 9));

Output:

Node.js Console
Node.js console module is a global object that provides a simple debugging console
similar to JavaScript to display different levels of message. It is provided by web
browsers. The console module contains two components:
 Console class: The console class methods are console.log(),
console.error() and console.warn() to display Node.js stream.
 global console: It is used without calling require(‘console’).
Example of Console class: Make a file and save it as example_console_class.js with
the following code in the file.
// It requires the fs module
const fs = require('fs');

const out = fs.createWriteStream('./stdout.log');

const err = fs.createWriteStream('./stderr.log');

const myobject = new console.Console(out, err);

// It will display 'This is the first example' to out

myobject.log('This is the first example');

// It will display 'This is the second example' to out

myobject.log('This is the %s example', 'second');

// It will display 'Error: In this we creating some error' to err

myobject.error(new Error('In this we creating some error'));

const num = 'third';

// It will display 'This is the third error' to err

myobject.warn(`This is the ${num} example`);

If you observe above example, we have created a simple object using Console class
with configurable output streams and we have created a Console class object by
using console.Console
Now, we will execute example_console_class.js script file in command prompt by
navigating to the folder where it exists like as shown below.
The above node.js example will create a log files (stdout & stderr) in the folder
where example_console_class.js file exists with required messages like as shown
below.

Example of Global Console Object: Create a file and save it as


example_console_object.js with the following code in the file.
// It will display 'This is the first object example' to stdout

console.log('This is the first object example');

// It will display 'This is the second object example' to stdout

console.log('This is the %s example', 'second object');

// It will display 'Error: New Error has happened' to stderr

console.error(new Error('New Error has happened'));

const obj = 'third object';


// It will display 'This is the third object example' to stderr

console.warn(`This is the ${obj} example`);

If you observe above code, we are trying to write a messages to node.js stream by
using global console object methods such as console.log(), console.error() and
console.warn(). Here, we are accessing global console object without importing it
using require directive.
Now, we will execute example_console_object.js file, for that open a command
prompt (cmd) and navigate to the folder that contains
a example_console_object.js file and write the command node
example_console_object.js and hit enter button like as shown below.

If you observe result, we are able to write a required messages to node.js stream by
using global console object.
Console Methods: Apart from above three methods (console.log(),
console.error(), console.warn()), few other methods also available in node.js
console object to write or print a messages in node.js stream.
 console.count(): It is used to count the number of times a specific label
has been called.
 console.clear(): It is used to clear the console history.
 console.info(): It is used to write a messages on console and it is an alias
of console.log() method.
 console.time(): It is used to get the starting time of an action.
 console.timeEnd(): It is used to get the end time of specific action.
 console.dir(): It use util.inspect() on object and prints the resulting string
to stdout.
NODE.JS DNS
DNS is a node module used to do name resolution facility which is provided by the
operating system as well as used to do an actual DNS lookup.
Advantage: No need for memorizing IP addresses – DNS servers provide a nifty
solution for converting domain or subdomain names to IP addresses.
Example 1: In this example, we will print the address of GeeksforGeeks on the
console.
 javascript

// Include 'dns' module and create its object


const dns = require('dns');

const website = 'geeksforgeeks.org';


// Call to lookup function of dns
dns.lookup(website, (err, address, family) =>; {
console.log('address of %s is %j family: IPv%s',
website, address, family);
});

// Execute using $ node <filename>;

Output:
address of geeksforgeeks.org is "52.25.109.230" family: IPv4
Example 2: In this example, we will print the address of the GeeksforGeeks.
 javascript

// Include 'dns' module and create its object


const dns = require('dns');

// Call to reverse function along with lookup function.


dns.lookup('www.geeksforgeeks.org',
function onLookup(err, address, family) {
console.log('address:', address);
dns.reverse(address, function (err, hostnames) {
console.log('reverse for ' + address + ': '
+ JSON.stringify(hostnames));
});
});

// Execute using $ node <filename>;


Output:
address: 52.222.176.140
reverse for 52.222.176.140: ["server-52-222-176-
140.bom52.r.cloudfront.net"]

NODE.JS FILE SYSTEM MODULE


Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js helps
developers to write JavaScript code to run on the server-side, to generate dynamic
content and deliver to the web clients. The two features that make Node.js stand-out
are:
 Event-driven
 Non-blocking I/O model
About Node.js file system: To handle file operations like creating, reading, deleting,
etc., Node.js provides an inbuilt module called FS (File System). Node.js gives the
functionality of file I/O by providing wrappers around the standard POSIX functions.
All file system operations can have synchronous and asynchronous forms depending
upon user requirements. To use this File System module, use the require() method:
var fs = require('fs');
Common use for File System module:
 Read Files
 Write Files
 Append Files
 Close Files
 Delete Files
What is Synchronous and Asynchronous approach?
 Synchronous approach: They are called blocking functions as it waits for
each operation to complete, only after that, it executes the next operation,
hence blocking the next command from execution i.e. a command will not be
executed until & unless the query has finished executing to get all the result
from previous commands.
 Asynchronous approach: They are called non-blocking functions as it
never waits for each operation to complete, rather it executes all operations in
the first go itself. The result of each operation will be handled once the result
is available i.e. each command will be executed soon after the execution of
the previous command. While the previous command runs in the background
and loads the result once it is finished processing the data.
 Use cases:

If your operations are not doing very heavy lifting like querying
huge data from DB then go ahead with Synchronous way otherwise
Asynchronous way.
 In an Asynchronous way, you can show some progress indicator to
the user while in the background you can continue with your
heavyweight works. This is an ideal scenario for GUI based apps.
 Example of asynchronous and synchronous: Create a text file
named input.txt with the following content:
GeeksforGeeks: A computer science portal
 Now let us create a js file named main.js with the following code:
 javascript

var fs = require("fs");

// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});

 Output:
Asynchronous read: GeeksforGeeks: A computer science portal

 javascript

var fs = require("fs");

// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

 Output:
Synchronous read: GeeksforGeeks: A computer science portal
Open a File: The fs.open() method is used to create, read, or write a file. The
fs.readFile() method is only for reading the file and fs.writeFile() method is only for
writing to the file, whereas fs.open() method does several operations on a file. First, we
need to load the fs class which is a module to access the physical file system. Syntax:
fs.open(path, flags, mode, callback)
Parameters:
 path: It holds the name of the file to read or the entire path if stored at other
locations.
 flags: Flags indicate the behavior of the file to be opened. All possible values
are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+).
 mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to
default as readwrite.


 err: If any error occurs.
 data: Contents of the file. It is called after the open operation is executed.
Example: Let us create a js file named main.js having the following code to open a
file input.txt for reading and writing.
 javascript

var fs = require("fs");

// Asynchronous - Opening File


console.log("opening file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File open successfully");
});

Output:
opening file!
File open successfully
Reading a File: The fs.read() method is used to read the file specified by fd. This
method reads the entire file into the buffer. Syntax:
fs.read(fd, buffer, offset, length, position, callback)
Parameters:
 fd: This is the file descriptor returned by fs.open() method.
 buffer: This is the buffer that the data will be written to.
 offset: This is the offset in the buffer to start writing at.
 length: This is an integer specifying the number of bytes to read.
 position: This is an integer specifying where to begin reading from in the
file. If the position is null, data will be read from the current file position.
 callback: It is a callback function that is called after reading of the file. It
takes two parameters:
 err: If any error occurs.

data: Contents of the file.
Example: Let us create a js file named main.js having the following code:
 javascript

var fs = require("fs");
var buf = new Buffer(1024);

console.log("opening an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("reading the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){


if (err){
console.log(err);
}
console.log(bytes + " bytes read");

// Print only read bytes to avoid junk.


if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
});

Output:
opening an existing file
File opened successfully!
reading the file
40 bytes read
GeeksforGeeks: A computer science portal
Writing to a File: This method will overwrite the file if the file already exists. The
fs.writeFile() method is used to asynchronously write the specified data to a file. By
default, the file would be replaced if it exists. The ‘options’ parameter can be used to
modify the functionality of the method. Syntax:
fs.writeFile(path, data, options, callback)
Parameters:

path: It is a string, Buffer, URL, or file description integer that denotes the
path of the file where it has to be written. Using a file descriptor will make it
behave similarly to fs.write() method.
 data: It is a string, Buffer, TypedArray, or DataView that will be written to
the file.
 options: It is a string or object that can be used to specify optional parameters
that will affect the output. It has three optional parameters:
 encoding: It is a string value that specifies the encoding of the file.
The default value is ‘utf8’.
 mode: It is an integer value that specifies the file mode. The
default value is 0o666.
 flag: It is a string value that specifies the flag used while writing to
the file. The default value is ‘w’.
 callback: It is the function that would be called when the method is executed.
 err: It is an error that would be thrown if the operation fails.
Example: Let us create a js file named main.js having the following code:
 javascript

var fs = require("fs");

console.log("writing into existing file");


fs.writeFile('input.txt', 'Geeks For Geeks', function(err) {
if (err) {
return console.error(err);
}

console.log("Data written successfully!");


console.log("Let's read newly written data");

fs.readFile('input.txt', function (err, data) {


if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});

Output:
writing into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Geeks For Geeks
Appending to a File: The fs.appendFile() method is used to synchronously append the
data to the file. Syntax:
fs.appendFile(filepath, data, options, callback);
or
fs.appendFileSync(filepath, data, options);
Parameters:
 filepath: It is a String that specifies the file path.
 data: It is mandatory and it contains the data that you append to the file.
 options: It is an optional parameter that specifies the encoding/mode/flag.
 Callback: Function is mandatory and is called when appending data to file is
completed.
Example 1: Let us create a js file named main.js having the following code:
 javascript

var fs = require('fs');

var data = "\nLearn Node.js";

// Append data to file


fs.appendFile('input.txt', data, 'utf8',

// Callback function
function(err) {
if (err) throw err;

// If no error
console.log("Data is appended to file successfully.")
});

Output:
Data is appended to file successfully.
Example 1: For synchronously appending
 javascript

var fs = require('fs');

var data = "\nLearn Node.js";

// Append data to file


fs.appendFileSync('input.txt', data, 'utf8');
console.log("Data is appended to file successfully.")

Output:
Data is appended to file successfully.
 Before Appending Data to input.txt file:
GeeksforGeeks: A computer science portal
 After Appending Data to input.txt file:
GeeksforGeeks: A computer science portal
Learn Node.js
Closing the File: The fs.close() method is used to asynchronously close the given file
descriptor thereby clearing the file that is associated with it. This will allow the file
descriptor to be reused for other files. Calling fs.close() on a file descriptor while some
other operation is being performed on it may lead to undefined behavior. Syntax:
fs.close(fd, callback)
Parameters:
 fd: It is an integer that denotes the file descriptor of the file for which to be
closed.
 callback: It is a function that would be called when the method is executed.
 err: It is an error that would be thrown if the method fails.
Example: Let us create a js file named main.js having the following code:
 javascript

// Close the opened file.


fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully.");
}

Output:
File closed successfully.
Delete a File: The fs.unlink() method is used to remove a file or symbolic link from the
filesystem. This function does not work on directories, therefore it is recommended to
use fs.rmdir() to remove a directory. Syntax:
fs.unlink(path, callback)
Parameters:
path: It is a string, Buffer or URL which represents the file or symbolic link
which has to be removed.
 callback: It is a function that would be called when the method is executed.
 err: It is an error that would be thrown if the method fails.
Example: Let us create a js file named main.js having the following code:
 javascript

var fs = require("fs");

console.log("deleting an existing file");


fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});

Output:
deleting an existing file
File deleted successfully!

IMPORT AND EXPORT NODE.js


Importing and exporting files are important parts of any programming language.
Importing functions or modules enhances the reusability of code. When the application
grows in size, maintaining a single file with all the functions and logic becomes
difficult. It also hinders the process of debugging. Therefore, it is good practice to
create separate files for specific functions and later import them as per requirement.
Node.js also allows importing and exporting functions and modules. Functions in one
module can be imported and called in other modules saving the effort to copy function
definitions into the other files. The module can be edited or debugged separately
making it easier to add or remove features.
Steps to include functions from other files:
1. Creating a Module: Modules are created in Node.js are JavaScript files.
Every time a new file with .js extension is created, it becomes a module.
2. Exporting a Module: Filename: func.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}

// Adding the code below to allow importing


// the functions in other files
module.exports = { add }

3. Importing a Module: We need to import the module to use the functions


defined in the imported module in another file. The result returned by
require() is stored in a variable which is used to invoke the functions using
the dot notation.
Filename: main.js
// Importing the func.js module

// The ./ says that the func module


// is in the same directory as
// the main.js file
const f = require('./func');

// Require returns an object with add()


// and stores it in the f variable
// which is used to invoke the required

const result = f.add(10, 5);

console.log('The result is:', result);

4. Output:
5. The result is: 15
Importing multiple functions from local file: Filename: func.js
function add(x, y) {
return x + y;
}

function subtract(x, y) {
return x - y;
}

module.exports = { add, subtract};

Filename: main.js
const f = require('./func');

console.log(f.add(4, 4));
console.log(f.subtract(8, 4));

We can also use the destructuring syntax to unpack the properties of the object returned
by require() function and store them in respective variables.

const { add, subtract} = require('./func');


console.log(add(4, 4));
console.log(subtract(8, 4));

Output:
8
4
Other ways to export a module
 Defining the functions inside module.exports object.

module.exports = {
add: function (x, y) {
return x + y;
},

subtract: function (x, y) {


return x - y;
},
};

 Defining each function independently as a method of module.exports


module.exports.add = function (x, y) {
return x + y;
};

module.exports.subtract = function (x, y) {


return x - y;
};

Importing a module from a directory: Importing lib.js file inside the directory, by
prefixing lib.js with the directory name.
const lib = require('./mod/lib');
console.log(lib.add(6, 4));
console.log(lib.subtract(12, 4));

There are three types of modules in Node.js


1. Importing from local module: These modules are created by the user and
can be imported as:
2. const var = require('./filename.js'); // OR
3. const var = require('./path/filename.js');
4. Importing from core modules: These modules are inbuilt in Node.js and can
be imported as:
const var = require('fs');
5. Importing from third party modules: These modules are installed using a
package manager such as npm. Examples of third party modules are express,
mongoose, nodemon, etc. These are imported as:
const express = require('express');
Thus above are few examples to import and export functions from different files in
Node.js .

NODE.js HTTP MODULE


o make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to
transfer data over the HTTP. To use the HTTP server in the node, we need to require
the HTTP module. The HTTP module creates an HTTP server that listens to server
ports and gives a response back to the client.
Syntax:
const http = require('http');

Example 1: In this example, we can create an HTTP server with the help
of http.createServer() method.
Filename: max.js
javascript
const http = require('http');

// Create a server
http.createServer((request, response) => {

// Sends a chunk of the response body


response.write('Hello World!');
// Signals the server that all of
// the response headers and body
// have been sent
response.end();
}).listen(3000); // Server listening on port 3000

console.log("Server started on port 3000");

Step to run this program: Run this max.js file using the below command:
node max.js

Output:
Console Output:

Browser Output:

To make requests via the HTTP module http.request() method is used.


Syntax:
http.request(options[, callback])

Example 2: In this example, we will see to make requests via the HTTP
module http.request() method.
Filename: max.js
javascript
const http = require('http');

let options = {
host: 'www.geeksforgeeks.org',
path: '/courses',
method: 'GET'
};

// Making a get request to


// 'www.geeksforgeeks.org'
http.request(options, (response) => {

// Printing the statusCode


console.log(`STATUS: ${response.statusCode}`);
}).end();

Step to run this program: Run this max.js file using the below command:
node max.js

Output:

NODE.JS OS MODULE
OS is a node module used to provide information about the computer operating system.
Advantages:
It provides functions to interact with the operating system. It provides the hostname of
the operating system and returns the amount of free system memory in bytes.
Example 1:
javascript
// Include os module and create its object
const os = require('os');

// return the cpu architecture


console.log("CPU architecture: " + os.arch());

// It returns the amount of free system memory in bytes


console.log("Free memory: " + os.freemem());

// It return total amount of system memory in bytes


console.log("Total memory: " + os.totalmem());

// It returns the list of network interfaces


console.log('List of network Interfaces: ' + os.networkInterfaces());

// It returns the operating systems default directory for temp files.


console.log('OS default directory for temp files : ' + os.tmpdir());

Output:

Example 2:
javascript
// Include os module and create its object
const os = require('os');

// return the endianness of system


console.log("Endianness of system: " + os.endianness());

// It returns hostname of system


console.log("Hostname: " + os.hostname());

// It return operating system name


console.log("Operating system name: " + os.type());

// It returns the platform of os


console.log('operating system platform: ' + os.platform());

// It returns the operating systems release.


console.log('OS release : ' + os.release());

Output:
NODE.JS URL MODULE
The url.hash is an inbuilt application programming interface of
class URL within url module which is used to get and set the fragment portion of the
URL.
Syntax:
url.hash
Return value: It gets and sets the fragment portion of the URL.
Below programs illustrate the use of url.hash Method:
Example 1:
 Javascript

// node program to demonstrate the


// url.hash API as Setter

// creating and initializing myURL


const myURL = new URL('https://example.org/foo#ram');

// Display href value of myURL before change


console.log("Before Change");
console.log(myURL.href);

// assigning fragment portion


// using hash
console.log();
myURL.hash = 'rahim';

// Display href value of myURL after change


console.log("After Change");
console.log(myURL.href);

Output:
Before Change
https://example.org/foo#ram

After Change
https://example.org/foo#rahim
Example 2:
 Javascript

// node program to demonstrate the


// url.hash API as Getter

// creating and initializing myURL


const myURL = new URL('https://example.org/foo#ram');

// getting the fragment portion


// using hash
const hash = myURL.hash;

// Display hash value


console.log(hash);

Output:
#ram

NODE.JS V8 MODULE
The v8.cachedDataVersionTag() method is an inbuilt application programming
interface of the v8 module which is used to get the version tag derived from the v8
version.
Syntax:
v8.cachedDataVersionTag();
Parameters: This method does not have any parameters.
Return Value: This method returns the version tag from the v8 version, command-line
flags, and detected CPU features.
Example 1: The below example illustrates the use of the v8.cachedDataVersionTag()
method in Node.js.
index.js
 javascript

// Accessing v8 module
const v8 = require('v8');

// Calling v8.cachedDataVersionTag()
tag = v8.cachedDataVersionTag();
console.log("cache data version tag is " + tag);

Run the index.js file using the following command:


node index.js
Output:
cache data version tag is 4151506697
Example 2: The below example illustrates the use of the v8.cachedDataVersionTag()
method in Node.js.
index.js
 javascript

// Accessing v8 module
const v8 = require('v8');

// User defined function


function getTagVersion() {

// Initializing with zero


let tagVersion = 0;

// Calling v8.cachedDataVersionTag()
tagVersion = v8.cachedDataVersionTag();
return tagVersion;
}

// Function call
let result = getTagVersion();

// Printing Tag version


console.log("The Cache Data Version is:", result);

Run the index.js file using the following command:


node index.js
Output:
The Cache Data Version is: 1165837633

NODE.JS VM MODULE
The Constructor: new vm.Script() method creates a new vm.Script object and
compiles the stated code but it does not run the code. Moreover, the
compiled vm.Script can run afterwards as many times as required. Here, the code is not
connected to any global object, rather it’s connected before each run, just for that
particular run.
Syntax:
Constructor: new vm.Script( code, options )
Parameters: This method accept two parameters as mentioned above and described
below.
 code: It is the JavaScript code to compile.
 options: It is optional parameter and it returns Object or string. If it returns a
string, then it defines the filename.
Below examples illustrate the use of Constructor: new vm.Script() in Node.js:
Example 1:
// Node.js program to demonstrate the
// Constructor: new vm.Script() method

// Including vm and util module


const util = require('util');
const vm = require('vm');

// Creating context
const context = {
number: 2
};

// Calling the constructor


const script = new vm.Script('Type = "Int"; number *= 2;');

// Contextifying object
vm.createContext(context);

// Calling runInContext method


script.runInContext(context);

// Displays output
console.log(context);

Output:
{ number: 4, Type: 'Int' }
Example 2:
// Node.js program to demonstrate the
// Constructor: new vm.Script() method

// Including vm and util module


const util = require('util');
const vm = require('vm');

// Creating context
const context = {
value: 1.0
};

// Calling the constructor


const script = new vm.Script('Type = "Float"; value += 2*0.1;');

// Contextifying object
vm.createContext(context);

// Calling runInContext method


script.runInContext(context);

// Displays output
console.log(context);

Output:
{ value: 1.2, Type: 'Float' }

You might also like