Node JS
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.
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.
Destination Folder
Set the Destination Folder where you want to install [Link] & Select “Next”
Custom Setup
Select “Next”
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:
Step 4: To Install [Link] and NPM to your Ubuntu machine, use the
command given below:
Step 5: Once installed, verify it by checking the installed version using the
following command:
Finally, you have successfully installed [Link] and NPM on your Ubuntu machine.
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]"
};
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
// Declare variable
let x = 2;
let y = 3;
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
[Link](x);
[Link](y);
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
1
10000
[Link] console-based application: Make a file called [Link] with the following
code.
javascript
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
// Create server
[Link](function (req, res) {
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:
// Create server
[Link](function (req, res) {
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
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
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');
–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 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.
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.
function printHello() {
[Link]( "Hello, World!");
}
[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.
[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
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]:
process provides information and control about the current [Link] process.
querystring utility used for parsing and formatting URL query strings.
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
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
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
const welcome = {
sayHello: function () {
[Link]("Hello GeekforGeeks user");
},
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
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
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;
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]:
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:
javascript
// Write JavaScript code here
rbuf = new Buffer(26);
var j;
[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;
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');
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.
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
Output:
address of [Link] is "[Link]" family: IPv4
Example 2: In this example, we will print the address of the GeeksforGeeks.
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");
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);
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");
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');
// 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');
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
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");
Output:
deleting an existing file
File deleted successfully!
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;
}
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.
Output:
8
4
Other ways to export a module
Defining the functions inside [Link] object.
[Link] = {
add: 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));
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) => {
Step to run this program: Run this [Link] file using the below command:
node [Link]
Output:
Console Output:
Browser Output:
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'
};
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');
Output:
Example 2:
javascript
// Include os module and create its object
const os = require('os');
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
Output:
Before Change
[Link]
After Change
[Link]
Example 2:
Javascript
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);
// Accessing v8 module
const v8 = require('v8');
// Calling [Link]()
tagVersion = [Link]();
return tagVersion;
}
// Function call
let result = getTagVersion();
[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
// Creating context
const context = {
number: 2
};
// Contextifying object
[Link](context);
// Displays output
[Link](context);
Output:
{ number: 4, Type: 'Int' }
Example 2:
// [Link] program to demonstrate the
// Constructor: new [Link]() method
// Creating context
const context = {
value: 1.0
};
// Contextifying object
[Link](context);
// Displays output
[Link](context);
Output:
{ value: 1.2, Type: 'Float' }