0% found this document useful (0 votes)
120 views69 pages

Node JS

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 I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript. The document discusses installing Node.js on Windows and Linux, the basics of Node.js including data types, objects, functions, and loose typing, and provides examples of each. It also lists some common Node.js modules like the assert, buffer, console, DNS, file system, HTTP, OS, URL, and VM modules.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views69 pages

Node JS

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 I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript. The document discusses installing Node.js on Windows and Linux, the basics of Node.js including data types, objects, functions, and loose typing, and provides examples of each. It also lists some common Node.js modules like the assert, buffer, console, DNS, file system, HTTP, OS, URL, and VM modules.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NODE JS

Introduction to [Link]
Installation
Features
[Link] Basics
Applications
Node. [Link]
[Link] NPM
[Link] 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
[Link] 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 [Link] on your Windows :
Step-1: Downloading the [Link] ‘.msi’ installer.
The first step to install [Link] on windows is to download the installer. Visit the
official [Link] website i.e) [Link] 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 [Link] installer.


Now you need to install the [Link] installer on your PC. You need to follow the
following steps for the [Link] to be installed:-
 Double click on the .msi installer.
The [Link] Setup wizard will open.
 Welcome To [Link] 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 [Link] & Select “Next”


 Custom Setup
Select “Next”

 Ready to Install [Link].


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

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

Step 3: Verify that [Link] was properly installed or not.


To check that [Link] 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 [Link] was completely installed on your system, the command prompt will print the
version of the [Link] 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 [Link] on your PC, you should put the system
variable path for [Link] 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 [Link] installed is the updation of your local npm version(if required)
– the package manager that comes bundled with [Link].
You can run the following command, to quickly update the npm
npm install npm –global // Updates the ‘CLI’ client
Installation of [Link] on Linux
[Link] is a JavaScript runtime built on Chrome’s V8 JavaScript engine. [Link] can be
installed in multiple ways on your Ubuntu Linux machine. You can use Ubuntu’s
official repository to install [Link] or another way to use NodeSource repository.
Installation via NodeSource repository will allow you to choose latest version of
[Link].
Installing Node On Ubuntu 18.04 and 16.04: There are two methods Ubuntu official
repository and NodeSouce repository to install [Link] on Ubuntu.
Install [Link] using Ubuntu official repository: [Link] is available in Ubuntu’s
repository and you can easily install it using a few commands. Follow the steps below
to install [Link] on your Ubuntu operating system.
 Step 1: Open your terminal or press Ctrl + Alt + T.

 Step 2: To install [Link] 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 [Link]. NPM is
an open source library of [Link] 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 [Link] using NodeSouce repository: The latest version of [Link] can be
installed from NodeSource repository. Follow the steps below to install the [Link] 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 [Link] PPA to the system.

curl -sL [Link] | sudo -E bash –


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

 Step 4: To Install [Link] 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 [Link] and NPM on your Ubuntu machine.

NODE .JS BASICS


[Link] 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 [Link] applications.
Datatypes: [Link] contains various types of data types similar to JavaScript.
 Boolean
 Undefined
 Null
 String
 Number
Loose Typing: [Link] 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 [Link] declare any type of variable. Examples are given below:
Example:
 javascript

// Variable store number data type


let a = 35;
[Link](typeof a);

// Variable store string data type


a = "GeeksforGeeks";
[Link](typeof a);

// Variable store Boolean data type


a = true;
[Link](typeof a);

// Variable store undefined (no value) data type


a = undefined;
[Link](typeof a);

Output:
number
string
boolean
undefined
Objects & Functions: [Link] 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@[Link]"
};

// Display the object information


[Link]("Information of variable company:", company);

// Display the type of variable


[Link]("Type of variable company:", typeof company);

Output:
Information of variable company: {
Name: 'GeeksforGeeks',
Address: 'Noida',
Contact: '+919876543210',
Email: 'abc@[Link]'
}
Type of variable company: object
Functions: [Link] functions are defined using the function keyword then the name of
the function and parameters which are passed in the function. In [Link], we don’t have
to specify datatypes for the parameters and check the number of arguments received.
[Link] 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
[Link]("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 [Link] 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 [Link].
Example:
 javascript

let x = "Welcome to GeeksforGeeks ";

let y = '[Link] Tutorials';

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

[Link](x);

[Link](y);

[Link]("Concat Using (+) :", (x + y));

[Link]("Concat Using Function :", ([Link](y)));

[Link]("Split string: ", [Link](' '));

[Link]("Join string: ", [Link](', '));

[Link]("Char At Index 5: ", [Link](5));

Output:
Welcome to GeeksforGeeks
[Link] Tutorials
Concat Using (+) : Welcome to GeeksforGeeks [Link] Tutorials
Concat Using Function : Welcome to GeeksforGeeks [Link] Tutorials
Split string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ]
Join string: Geeks, for, Geeks
Char At Index 5: m
Buffer: In [Link], 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 = " ";
[Link](str);
[Link]([Link]);//Display the information
[Link]([Link]); //Display the information

1
10000
[Link] console-based application: Make a file called [Link] with the following
code.
 javascript

[Link]('Hello this is the console-based application');

[Link]('This all will be printed in console');

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

To run this file, open the [Link] command prompt and go to the folder where
the [Link] file exists and write the following command. It will display content on
console.
The [Link]() method of the console class prints the message passed in the method
in the console.
[Link] web-based application: [Link] 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 [Link] with the
following code.
Example:
 javascript

// Require http module


let http = require("http");

// Create server
[Link](function (req, res) {

// Send the HTTP header


// HTTP Status: 200 : OK
// Content Type: text/plain
[Link](200, { 'Content-Type': 'text/plain' });

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


// of [Link] web based application"
[Link]('This is the example of [Link] web-based application \n');

// Console will display the message


}).listen(5000,
() => [Link]('Server running at [Link]

To run this file follow the steps as given below:


 Search the [Link] command prompt in the search bar and open the [Link]
command prompt.
 Go to the folder using cd command in command prompt and write the
following command node
[Link]

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

Run the file on [Link] command prompt using command node [Link] i.e. node
<file_name> .
Output:

Example 2: Creating a Hello World application receiving the user input. Create a [Link]
file containing the following code.
[Link]([Link](2));

The [Link] 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
[Link] binary which runs the program and the second argument is location of the file
being run.
Output:

Web-based [Link] Application: A web-based [Link] application consists of the


following three important components:
 Import required modules: Load [Link] 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:
[Link]().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:
[Link](function (request, response)
{...}).listen(8080);
Example: This example create a Hello World web-based application using [Link].
Create a [Link] file containing the following code.
// Require http header
var http = require('http');

// Create server
[Link](function (req, res) {

// HTTP Status: 200 : OK


// Content Type: text/html
[Link](200, {'Content-Type': 'text/html'});

// Send the response body as "Hello World!"


[Link]('Hello World!');
}).listen(8080);

Run the file on [Link] command prompt using command node [Link] and
type [Link] in a web browser to see the output.
Output:

NODE. JS REPL(READ,EVAL,PRINT,LOOP)
[Link] is an open source server-side Javascript run-time environment built
on Chrome’s JavaScript Engine(V8). [Link] 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.

[Link] NPM
NPM (Node Package Manager) is the default package manager for [Link] 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 [Link] and
consists of command line client npm. It gets installed into the system with installation
of [Link]. 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 [Link] file. It can
also update and uninstall packages. In the [Link] 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 [Link] as NPM gets installed with [Link]
automatically.
Install [Link].
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 [Link] 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 [Link] file (in case using
[Link]), 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 [Link] file with all the packages mentioned as dependencies already,
just type npm install in terminal. npm will look at [Link] 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 [Link] 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 [Link] file. The caret symbol (^) is used to tell
the npm to find a version greater than 4.1.1 and install it.
[Link] GLOBAL OBJECTS
[Link] is an open-source project that can be used for server-side scripting. [Link]
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 [Link] Global Objects are listed below:

[Link]: 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
[Link] is a global scope when declared within the browser. However, any variable defined
within a [Link] 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. [Link] 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() {
[Link]( "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.

[Link]: It is an implementation of the WHATWG Encoding Standard


TextDecoder API.
[Link]: 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 [Link] is the base value.

[Link]: URLSearchParams API is used to perform read and write


operations on the query of a URL.

const myURL = new URL('[Link]


// It prints gfg
[Link]([Link]('name'));

[Link]('name', 'xyz');

// It prints [Link]
[Link]([Link]);
[Link]: 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 [Link].
 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 [Link]. It requires a script to give the desired output as
__dirname is only defined in scripts.

 Create a [Link] file


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

 Create a [Link] file


 Paste the following code:
[Link]("__filename : "+ __filename);
 Run the [Link] file

[Link] MODULES
In [Link], 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: [Link] has many built-in modules that are part of the platform and
come with [Link] 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 [Link] http
module to create a web server.

 javascript

const http = require('http');


[Link](function (req, res) {
[Link](200, { 'Content-Type': 'text/html' });
[Link]('Welcome to this page!');
[Link]();
}).listen(3000);

In the above example, the require() function returns an object because the Http module
returns its functionality as an object. The function [Link]() method will be
executed when someone tries to access the computer on port 3000. The [Link]()
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 [Link]:

Core Modules Description

http creates an HTTP server in [Link].

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 [Link] 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 [Link] application. Let’s create a simple calculating module that calculates
various operations. Create a [Link] file that has the following code:
Filename: [Link]
 javascript

[Link] = function (x, y) {


return x + y;
};

[Link] = function (x, y) {


return x - y;
};

[Link] = function (x, y) {


return x * y;
};

[Link] = 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: [Link]
 javascript

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

let x = 50, y = 10;

[Link]("Addition of 50 and 10 is "


+ [Link](x, y));

[Link]("Subtraction of 50 and 10 is "


+ [Link](x, y));

[Link]("Multiplication of 50 and 10 is "


+ [Link](x, y));

[Link]("Division of 50 and 10 is "


+ [Link](x, y));

Step to run this program: Run the [Link] file using the following command:
node [Link]
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

[Link] Local Module


[Link] 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 [Link]
 javascript

const welcome = {

sayHello: function () {
[Link]("Hello GeekforGeeks user");
},

currTime: new Date().toLocaleDateString(),

companyName: "GeekforGeeks"
}

[Link] = welcome

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

const local = require("./[Link]");


[Link]();
[Link]([Link]);
[Link]([Link]);

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

[Link] Assert module


Assert module in [Link] 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 [Link] module.
Importing module:
const assert = require("assert");
Example 1:
[Link]()
const assert = require('assert');

let x = 4;
let y = 5;

try {

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

// Error output
[Link](
`${x} is not equal to ${y}`);
}

Output:

Example 2:
[Link]()
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:
[Link] Buffers
Buffers are instances of the Buffer class in [Link]. 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 [Link]:

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


Syntax:

var ubuf = [Link](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 [Link]: The [Link]() method is used to write data into a
node buffer.
Syntax:

[Link]( string, offset, length, encoding )


The [Link]() 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 [Link]() 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
[Link].
 encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.
Example: Create a [Link] file containing the following codes.

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

Output:

Reading from Buffers: The [Link]() method is used to read data from a node
buffer.
Syntax:

[Link]( encoding, start, end )


The [Link]() 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 [Link] 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 ;
}

[Link]( [Link]('ascii'));
Output:

Example 2: Read the data from [Link] buffer specifying the start and end point of
reading. Create a [Link] 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 ;
}

[Link]( [Link]('utf-8', 3, 9));

Output:

[Link] Console
[Link] 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 [Link](),
[Link]() and [Link]() to display [Link] 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 = [Link]('./[Link]');

const err = [Link]('./[Link]');

const myobject = new [Link](out, err);

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

[Link]('This is the first example');

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

[Link]('This is the %s example', 'second');

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

[Link](new Error('In this we creating some error'));

const num = 'third';

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

[Link](`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 [Link]
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 [Link] 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

[Link]('This is the first object example');

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

[Link]('This is the %s example', 'second object');

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

[Link](new Error('New Error has happened'));

const obj = 'third object';


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

[Link](`This is the ${obj} example`);

If you observe above code, we are trying to write a messages to [Link] stream by
using global console object methods such as [Link](), [Link]() and
[Link](). 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 [Link] stream by
using global console object.
Console Methods: Apart from above three methods ([Link](),
[Link](), [Link]()), few other methods also available in [Link]
console object to write or print a messages in [Link] stream.
 [Link](): It is used to count the number of times a specific label
has been called.
 [Link](): It is used to clear the console history.
 [Link](): It is used to write a messages on console and it is an alias
of [Link]() method.
 [Link](): It is used to get the starting time of an action.
 [Link](): It is used to get the end time of specific action.
 [Link](): It use [Link]() on object and prints the resulting string
to stdout.
[Link] 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 = '[Link]';


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

// Execute using $ node <filename>;

Output:
address of [Link] is "[Link]" 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.


[Link]('[Link]',
function onLookup(err, address, family) {
[Link]('address:', address);
[Link](address, function (err, hostnames) {
[Link]('reverse for ' + address + ': '
+ [Link](hostnames));
});
});

// Execute using $ node <filename>;


Output:
address: [Link]
reverse for [Link]: ["server-52-222-176-
[Link]"]

[Link] FILE SYSTEM MODULE


[Link] is a JavaScript runtime built on Chrome’s V8 JavaScript engine. [Link] 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 [Link] stand-out
are:
 Event-driven
 Non-blocking I/O model
About [Link] file system: To handle file operations like creating, reading, deleting,
etc., [Link] provides an inbuilt module called FS (File System). [Link] 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 [Link] with the following content:
GeeksforGeeks: A computer science portal
 Now let us create a js file named [Link] with the following code:
 javascript

var fs = require("fs");

// Asynchronous read
[Link]('[Link]', function (err, data) {
if (err) {
return [Link](err);
}
[Link]("Asynchronous read: " + [Link]());
});

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

 javascript

var fs = require("fs");

// Synchronous read
var data = [Link]('[Link]');
[Link]("Synchronous read: " + [Link]());

 Output:
Synchronous read: GeeksforGeeks: A computer science portal
Open a File: The [Link]() method is used to create, read, or write a file. The
[Link]() method is only for reading the file and [Link]() method is only for
writing to the file, whereas [Link]() 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:
[Link](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 [Link] having the following code to open a
file [Link] for reading and writing.
 javascript

var fs = require("fs");

// Asynchronous - Opening File


[Link]("opening file!");
[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File open successfully");
});

Output:
opening file!
File open successfully
Reading a File: The [Link]() method is used to read the file specified by fd. This
method reads the entire file into the buffer. Syntax:
[Link](fd, buffer, offset, length, position, callback)
Parameters:
 fd: This is the file descriptor returned by [Link]() 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 [Link] having the following code:
 javascript

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

[Link]("opening an existing file");


[Link]('[Link]', 'r+', function(err, fd) {
if (err) {
return [Link](err);
}
[Link]("File opened successfully!");
[Link]("reading the file");

[Link](fd, buf, 0, [Link], 0, function(err, bytes){


if (err){
[Link](err);
}
[Link](bytes + " bytes read");

// Print only read bytes to avoid junk.


if(bytes > 0){
[Link]([Link](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
[Link]() 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:
[Link](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 [Link]() 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 [Link] having the following code:
 javascript

var fs = require("fs");

[Link]("writing into existing file");


[Link]('[Link]', 'Geeks For Geeks', function(err) {
if (err) {
return [Link](err);
}

[Link]("Data written successfully!");


[Link]("Let's read newly written data");

[Link]('[Link]', function (err, data) {


if (err) {
return [Link](err);
}
[Link]("Asynchronous read: " + [Link]());
});
});

Output:
writing into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Geeks For Geeks
Appending to a File: The [Link]() method is used to synchronously append the
data to the file. Syntax:
[Link](filepath, data, options, callback);
or
[Link](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 [Link] having the following code:
 javascript

var fs = require('fs');

var data = "\nLearn [Link]";

// Append data to file


[Link]('[Link]', data, 'utf8',

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

// If no error
[Link]("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 [Link]";

// Append data to file


[Link]('[Link]', data, 'utf8');
[Link]("Data is appended to file successfully.")

Output:
Data is appended to file successfully.
 Before Appending Data to [Link] file:
GeeksforGeeks: A computer science portal
 After Appending Data to [Link] file:
GeeksforGeeks: A computer science portal
Learn [Link]
Closing the File: The [Link]() 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 [Link]() on a file descriptor while some
other operation is being performed on it may lead to undefined behavior. Syntax:
[Link](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 [Link] having the following code:
 javascript

// Close the opened file.


[Link](fd, function(err) {
if (err) {
[Link](err);
}
[Link]("File closed successfully.");
}

Output:
File closed successfully.
Delete a File: The [Link]() 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 [Link]() to remove a directory. Syntax:
[Link](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 [Link] having the following code:
 javascript

var fs = require("fs");

[Link]("deleting an existing file");


[Link]('[Link]', function(err) {
if (err) {
return [Link](err);
}
[Link]("File deleted successfully!");
});

Output:
deleting an existing file
File deleted successfully!

IMPORT AND EXPORT [Link]


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.
[Link] 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 [Link] are JavaScript files.
Every time a new file with .js extension is created, it becomes a module.
2. Exporting a Module: Filename: [Link]
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
[Link] = { 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: [Link]
// Importing the [Link] module

// The ./ says that the func module


// is in the same directory as
// the [Link] 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 = [Link](10, 5);

[Link]('The result is:', result);

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

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

[Link] = { add, subtract};

Filename: [Link]
const f = require('./func');

[Link]([Link](4, 4));
[Link]([Link](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');


[Link](add(4, 4));
[Link](subtract(8, 4));

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

[Link] = {
add: function (x, y) {
return x + y;
},

subtract: function (x, y) {


return x - y;
},
};

 Defining each function independently as a method of [Link]


[Link] = function (x, y) {
return x + y;
};

[Link] = function (x, y) {


return x - y;
};

Importing a module from a directory: Importing [Link] file inside the directory, by
prefixing [Link] with the directory name.
const lib = require('./mod/lib');
[Link]([Link](6, 4));
[Link]([Link](12, 4));

There are three types of modules in [Link]


1. Importing from local module: These modules are created by the user and
can be imported as:
2. const var = require('./[Link]'); // OR
3. const var = require('./path/[Link]');
4. Importing from core modules: These modules are inbuilt in [Link] 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
[Link] .

[Link] HTTP MODULE


o make HTTP requests in [Link], there is a built-in module HTTP in [Link] 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 [Link]() method.
Filename: [Link]
javascript
const http = require('http');

// Create a server
[Link]((request, response) => {

// Sends a chunk of the response body


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

[Link]("Server started on port 3000");

Step to run this program: Run this [Link] file using the below command:
node [Link]

Output:
Console Output:

Browser Output:

To make requests via the HTTP module [Link]() method is used.


Syntax:
[Link](options[, callback])

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

let options = {
host: '[Link]',
path: '/courses',
method: 'GET'
};

// Making a get request to


// '[Link]'
[Link](options, (response) => {

// Printing the statusCode


[Link](`STATUS: ${[Link]}`);
}).end();

Step to run this program: Run this [Link] file using the below command:
node [Link]

Output:

[Link] 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


[Link]("CPU architecture: " + [Link]());

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


[Link]("Free memory: " + [Link]());

// It return total amount of system memory in bytes


[Link]("Total memory: " + [Link]());

// It returns the list of network interfaces


[Link]('List of network Interfaces: ' + [Link]());

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


[Link]('OS default directory for temp files : ' + [Link]());

Output:

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

// return the endianness of system


[Link]("Endianness of system: " + [Link]());

// It returns hostname of system


[Link]("Hostname: " + [Link]());

// It return operating system name


[Link]("Operating system name: " + [Link]());

// It returns the platform of os


[Link]('operating system platform: ' + [Link]());

// It returns the operating systems release.


[Link]('OS release : ' + [Link]());

Output:
[Link] URL MODULE
The [Link] 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:
[Link]
Return value: It gets and sets the fragment portion of the URL.
Below programs illustrate the use of [Link] Method:
Example 1:
 Javascript

// node program to demonstrate the


// [Link] API as Setter

// creating and initializing myURL


const myURL = new URL('[Link]

// Display href value of myURL before change


[Link]("Before Change");
[Link]([Link]);

// assigning fragment portion


// using hash
[Link]();
[Link] = 'rahim';

// Display href value of myURL after change


[Link]("After Change");
[Link]([Link]);

Output:
Before Change
[Link]

After Change
[Link]
Example 2:
 Javascript

// node program to demonstrate the


// [Link] API as Getter

// creating and initializing myURL


const myURL = new URL('[Link]

// getting the fragment portion


// using hash
const hash = [Link];

// Display hash value


[Link](hash);

Output:
#ram

[Link] V8 MODULE
The [Link]() 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:
[Link]();
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 [Link]()
method in [Link].
[Link]
 javascript

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

// Calling [Link]()
tag = [Link]();
[Link]("cache data version tag is " + tag);

Run the [Link] file using the following command:


node [Link]
Output:
cache data version tag is 4151506697
Example 2: The below example illustrates the use of the [Link]()
method in [Link].
[Link]
 javascript

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

// User defined function


function getTagVersion() {

// Initializing with zero


let tagVersion = 0;

// Calling [Link]()
tagVersion = [Link]();
return tagVersion;
}

// Function call
let result = getTagVersion();

// Printing Tag version


[Link]("The Cache Data Version is:", result);

Run the [Link] file using the following command:


node [Link]
Output:
The Cache Data Version is: 1165837633

[Link] VM MODULE
The Constructor: new [Link]() method creates a new [Link] object and
compiles the stated code but it does not run the code. Moreover, the
compiled [Link] 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 [Link]( 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 [Link]() in [Link]:
Example 1:
// [Link] program to demonstrate the
// Constructor: new [Link]() 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 [Link]('Type = "Int"; number *= 2;');

// Contextifying object
[Link](context);

// Calling runInContext method


[Link](context);

// Displays output
[Link](context);

Output:
{ number: 4, Type: 'Int' }
Example 2:
// [Link] program to demonstrate the
// Constructor: new [Link]() 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 [Link]('Type = "Float"; value += 2*0.1;');

// Contextifying object
[Link](context);

// Calling runInContext method


[Link](context);

// Displays output
[Link](context);

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

You might also like