Professional Documents
Culture Documents
Introduction to Node.js
Installation
Features
Node.js Basics
Applications
Node. Js.REPL
Node.js NPM
Node.js Global objects
Node. Js local module
Node. Js assert module
Node. Js buffer module
Node. Js console module
Node. Js DNS module
Node. Js File system module
Node. Js Globals
Node. Js HTTP module
Node. Js OS module
Node. Js url module
Node. Js VM module
Node.js V8 module
Introduction
Node JS is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine
for executing JavaScript code outside of a browser. It provides an event-driven, non-blocking
(asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side
applications using JavaScript.
Most people are confused and understand it’s a framework or a programing language. We
often use NodeJS for building back-end services like APIs, Web App, or Mobile App. It’s
utilized in production by large companies like Paypal, Uber, Netflix, Walmart, etc.
Learning JavaScript is necessary these days in the development field. Anyhow you have to
use JavaScript on the front end. So it is better to learn NodeJS rather than learn other
backend technologies like PHP, JAVA, Ruby, etc. NodeJS is the hottest technology across the
world, especially in Silicon Valley. It is the perfect skill to open up amazing career
opportunities for any software developer.
installation of Node JS
To install NodeJS, we have separate articles for Linux and windows please go through the
required process.
Setting up the Node Development Environment
The Node can be installed in multiple ways on a computer. The approach used by you
depends on the existing development environment in the system. There are different
package installer for different environments. You can install Node by grabbing a copy
of the source code and compiling the application. Another way of installing Node is by
cloning the GIT repository in all the three environments and then installing it on the
system.
Installing Node On Windows (WINDOWS 10):
You have to follow the following steps to install the Node.js on your Windows :
Step-1: Downloading the Node.js ‘.msi’ installer.
The first step to install Node.js on windows is to download the installer. Visit the
official Node.js website i.e) https://nodejs.org/en/download/ and download the .msi file
according to your system environment (32-bit & 64-bit). An MSI installer will be
downloaded on your system.
Destination Folder
Set the Destination Folder where you want to install Node.js & Select “Next”
Custom Setup
Select “Next”
Install Node.js using NodeSouce repository: The latest version of Node.js can be
installed from NodeSource repository. Follow the steps below to install the Node.js on
your Ubuntu.
Step 1: Open your terminal or press Ctrl + Alt + T and use the following
commands to update and upgrade the package manager:
Step 4: To Install Node.js 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 Node.js and NPM on your Ubuntu machine.
Output:
number
string
boolean
undefined
Objects & Functions: Node.js objects are the same as JavaScript objects i.e. the
objects are similar to variables and it contains many values which are written as name:
value pairs. Name and value are separated by a colon and every pair is separated by a
comma.
Example:
javascript
let company = {
Name: "GeeksforGeeks",
Address: "Noida",
Contact: "+919876543210",
Email: "abc@geeksforgeeks.org"
};
Output:
Information of variable company: {
Name: 'GeeksforGeeks',
Address: 'Noida',
Contact: '+919876543210',
Email: 'abc@geeksforgeeks.org'
}
Type of variable company: object
Functions: Node.js functions are defined using the function keyword then the name of
the function and parameters which are passed in the function. In Node.js, we don’t have
to specify datatypes for the parameters and check the number of arguments received.
Node.js functions follow every rule which is there while writing JavaScript functions.
Example:
javascript
// 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 Node.js we can make a variable a string by assigning
a value either by using single (”) or double (“”) quotes and it contains many functions
to manipulate strings. Following is the example of defining string variables and
functions in node.js.
Example:
javascript
console.log(x);
console.log(y);
Output:
Welcome to GeeksforGeeks
Node.js Tutorials
Concat Using (+) : Welcome to GeeksforGeeks Node.js Tutorials
Concat Using Function : Welcome to GeeksforGeeks Node.js Tutorials
Split string: [ 'Welcome', 'to', 'GeeksforGeeks', '' ]
Join string: Geeks, for, Geeks
Char At Index 5: m
Buffer: In node.js, we have a data type called “Buffer” to store binary data and it is
useful when we are reading data from files or receiving packets over the network.
Javascript
1
10000
Node.js console-based application: Make a file called console.js with the following
code.
javascript
To run this file, open the node.js command prompt and go to the folder where
the console.js file exists and write the following command. It will display content on
console.
The console.log() method of the console class prints the message passed in the method
in the console.
Node.js web-based application: Node.js web application contains different types of
modules which is imported using require() directive and we have to create a server and
write code for the read request and return response. Make a file web.js with the
following code.
Example:
javascript
// Create server
http.createServer(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 web.js in the browser. If any
changes are made in the web.js file then again run the command node web.js and
refresh the tab in the browser.
NODE.JS FIRST APPLICATION
Node.js is an open source, cross-platform server environment which executes
JavaScript using V8 JavaScript Engine. Node.js helps to write front-end and back-end
code in the same language. It helps to write efficient code for real-time applications. In
Node.js, the applications can be written using console-based method or web-based
method.
Console based Node.js Application: The Node.js console-based applications are run
using Node.js command prompt. Console module in Node.js provide a simple
debugging console. Node.js is a global console which can be used for synchronous as
well as asynchronous communication. The console.log() function is used to display
output on console. This function prints output to stdout with newline.
Syntax:
console.log([data][, ...]);
Here, data is the content to be displayed on console.
Example 1: Creating a Hello World application using Node.js. Create a geeks.js file
containing the following code:
console.log('Hello World');
Run the file on Node.js command prompt using command node geeks.js i.e. node
<file_name> .
Output:
Example 2: Creating a Hello World application receiving the user input. Create a gfg.js
file containing the following code.
console.log(process.argv.slice(2));
The process.argv is used to provide command line argument to a program. Use the slice
function with 2 as its argument to get all the elements of argv that comes after its
second element, i.e. the arguments the user entered The first argument is location of the
Node.js binary which runs the program and the second argument is location of the file
being run.
Output:
// Create server
http.createServer(function (req, res) {
Run the file on Node.js command prompt using command node firstprogram.js and
type http://127.0.0.1:8080/ in a web browser to see the output.
Output:
NODE. JS REPL(READ,EVAL,PRINT,LOOP)
Node.js is an open source server-side Javascript run-time environment built
on Chrome’s JavaScript Engine(V8). Node.js is used for building fast and scalable
applications and is an event driven, non-blocking I/O model.
REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell
(Unix/Linux) and command prompt. Node comes with the REPL environment when it
is installed. System interacts with the user through outputs of commands/expressions
used. It is useful in writing and debugging the codes. The work of REPL can be
understood from its full form:
Read : It reads the inputs from users and parses it into JavaScript data structure. It is
then stored to memory.
Eval : The parsed JavaScript data structure is evaluated for the results.
Print : The result is printed after the evaluation.
Loop : Loops the input command. To come out of NODE REPL, press ctrl+c twice
Getting Started with REPL:
To start working with REPL environment of NODE; open up the terminal (in case of
UNIX/LINUX) or the Command prompt (in case of Windows) and write node and
press ‘enter’ to start the REPL.
The REPL has started and is demarcated by the ‘>’ symbol. Various operations can be
performed on the REPL. Below are some of the examples to get familiar with the REPL
environment.
Example: Performing Arithmetical operations in REPL
Note: using ‘math’ shows error as the library is referenced as ‘Math’ in NODE and
not ‘math’.
Example: Using variables in REPL. The keyword var is used to assign values to
variables.
Using Variables in REPL
Example: Using loops in REPL. Loops can be used in REPL as in other editors.
Note: Use ctrl – c to terminate the command and ctrl – c twice to terminate the NODE
REPL.
.help is used to list out all the commands.
NODE.JS NPM
NPM (Node Package Manager) is the default package manager for Node.js and is
written entirely in Javascript. Developed by Isaac Z. Schlueter, it was initially released
in January 12, 2010. NPM manages all the packages and modules for Node.js and
consists of command line client npm. It gets installed into the system with installation
of Node.js. The required packages and modules in Node project are installed using
NPM.
A package contains all the files needed for a module and modules are the JavaScript
libraries that can be included in Node project according to the requirement of the
project.
NPM can install all the dependencies of a project through the package.json file. It can
also update and uninstall packages. In the package.json file, each dependency can
specify a range of valid versions using the semantic versioning scheme, allowing
developers to auto-update their packages while at the same time avoiding unwanted
breaking changes.
Some facts about NPM:
At the time of writing this article, NPM has 580096 registered packages. The
average rate of growth of this number is 291/day which outraces every other
package registry.
npm is open source
The top npm packages in the decreasing order are: lodash, async, react,
request, express.
Installing NPM:
To install NPM, it is required to install Node.js as NPM gets installed with Node.js
automatically.
Install Node.js.
Checking and updating npm version:
Version of npm installed on system can be checked using following syntax:
Syntax:
npm -v
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 package.json file with all the packages mentioned as dependencies already,
just type npm install in terminal. npm will look at package.json file and install all the
dependencies according to their mentioned versions. This command is typically used
when a Node project is forked and cloned. The node_modules being a big folder is
generally not pushed to a github repo and the cloner has to run npm install to install the
dependencies.
Note: NPM installs the dependencies in local mode (Default) which go to
the node_modules directory present in the folder of Node application. To see all the
locally installed modules use npm ls command.
Uninstalling Packages:
To uninstall packages using npm, follow the below syntax:
Syntax:
npm uninstall
Example: To uninstall the express package
Uninstalling express
To install a package of a specific version, mention the full and exact version
in the package.json file.
To install the latest version of the package, mention “*” in front of the
dependency or “latest”. This will find the latest stable version of the module
and install it.
To install any version (stable one) above a given version, mention it like in
the example below:
“express”:”^4.1.1″. in package.json file. The caret symbol (^) is used to tell
the npm to find a version greater than 4.1.1 and install it.
NODE.JS GLOBAL OBJECTS
Node.js is an open-source project that can be used for server-side scripting. Node.js
Global Objects are the objects that are available in all modules. Global Objects are
built-in objects that are part of the JavaScript and can be used directly in the application
without importing any particular module. The Node.js Global Objects are listed below:
1.Class: Buffer The Buffer class is an inbuilt globally accessible class that means it can
be used without importing any module. The Buffer class is used to deal with binary
data. Buffer class objects are used to represent binary data as a sequence of bytes.
var myvar
2.It is a global scope when declared within the browser. However, any variable defined
within a node.js file is accessible only within that file.
setImmediate() method: It schedules the immediate execution of the
callback. The callback functions are queued and executed in the order in
which they are created. The callback queue is processed at every event loop
iteration. If there is a timer queued inside the executing callback, the timer
will not get triggered until the next event loop iteration.
clearImmediate() method: It stops the immediate object returned by the
setImmediate() method.
setInterval() method: It executes the callback function at repeated intervals.
If an interval is larger than 2147483647 or less than 1, the interval is set to 1.
Non-integer delays are truncated to the nearest integer.
clearInterval() method: It stops the interval object created by setInterval()
method.
function printHello() {
console.log( "Hello, World!");
}
myURL.searchParams.append('name', 'xyz');
// It prints https://www.register.com/?name=gfg&name=xyz
console.log(myURL.href);
6.WebAssembly: The global object that acts as a namespace for all W3C
WebAssembly related functionality. WebAssembly is a low level Assembly-like
language that can be run on modern browsers.
The following variables might appear to be global but actually exist only within the
scope of some modules.
require(id) method: It is used to import modules and returns an object of
‘any’ datatype.
var express = require('express')
exports: It is used to exports modules using module.exports.
module: It is a reference to the current module and is not global rather local
to each module. It is used to make a particular module available through
require() in the application.
__dirname: The output throws an error which proves that __dirname is not
globally defined in node.js. It requires a script to give the desired output as
__dirname is only defined in scripts.
NODE.JS MODULES
In Node.js, Modules are the blocks of encapsulated code that communicate with an
external application on the basis of their related functionality. Modules can be a single
file or a collection of multiple files/folders. The reason programmers are heavily reliant
on modules is because of their reusability as well as the ability to break down a
complex piece of code into manageable chunks.
Modules are of three types:
Core Modules
local Modules
Third-party Modules
Core Modules: Node.js has many built-in modules that are part of the platform and
come with Node.js installation. These modules can be loaded into the program by using
the required function.
Syntax:
const module = require('module_name');
The require() function will return a JavaScript type depending on what the particular
module returns. The following example demonstrates how to use the Node.js http
module to create a web server.
javascript
In the above example, the require() function returns an object because the Http module
returns its functionality as an object. The function http.createServer() method will be
executed when someone tries to access the computer on port 3000. The res.writeHead()
method is the status code where 200 means it is OK, while the second argument is an
object containing the response headers. The following list contains some of the
important core modules in Node.js:
process provides information and control about the current Node.js 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 Node.js application. Let’s create a simple calculating module that calculates
various operations. Create a calc.js file that has the following code:
Filename: calc.js
javascript
Since this file provides attributes to the outer world via exports, another file can use its
exported functionality using the require() function.
Filename: index.js
javascript
Step to run this program: Run the index.js file using the following command:
node index.js
Output:
Addition of 50 and 10 is 60
Subtraction of 50 and 10 is 40
Multiplication of 50 and 10 is 500
Division of 50 and 10 is 5
Note: This module also hides functionality that is not needed outside of the module.
Third-party modules: Third-party modules are modules that are available online using
the Node Package Manager(NPM). These modules can be installed in the project folder
or globally. Some of the popular third-party modules are Mongoose, express, angular,
and React.
Example:
npm install express
npm install mongoose
npm install -g @angular/cli
const welcome = {
sayHello: function () {
console.log("Hello GeekforGeeks user");
},
companyName: "GeekforGeeks"
}
module.exports = welcome
Explanation: Here, we declared an object ‘welcome’ with a function sayHello and two
variables currTime and companyName. We use the module.export to make the object
available globally.
Part 2: In this part, use the above module in the app.js file.
javascript
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
console.log(
`${x} is not equal to ${y}`);
}
Output:
Example 2:
console.clear()
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:
Node.js Buffers
Buffers are instances of the Buffer class in Node.js. Buffers are designed to handle
binary raw data. Buffers allocate raw memory outside the V8 heap. Buffer class is a
global class so it can be used without importing the Buffer module in an application.
Creating Buffers: Followings are the different ways to create buffers in Node.js:
string: It specifies the string data which is to be written into the buffer.
offset: It specifies the index at which buffer starts writing. Its default value is
0.
length: It specifies the number of bytes to write. Its default value is
buffer.length.
encoding: It specifies the encoding mechanism. Its default value is ‘utf-8’.
Example: Create a buffer.js file containing the following codes.
javascript
// Write JavaScript code here
cbuf = new Buffer(256);
bufferlen = cbuf.write("Learn Programming with GeeksforGeeks!!!");
console.log("No. of Octets in which string is written : "+ bufferlen);
Output:
Reading from Buffers: The buf.toString() method is used to read data from a node
buffer.
Syntax:
javascript
// Write JavaScript code here
rbuf = new Buffer(26);
var j;
console.log( rbuf.toString('ascii'));
Output:
Example 2: Read the data from Node.js buffer specifying the start and end point of
reading. Create a buffer.js file containing the following code.
javascript
// Write JavaScript code here
rbuf = new Buffer(26);
var j;
Output:
Node.js Console
Node.js console module is a global object that provides a simple debugging console
similar to JavaScript to display different levels of message. It is provided by web
browsers. The console module contains two components:
Console class: The console class methods are console.log(),
console.error() and console.warn() to display Node.js stream.
global console: It is used without calling require(‘console’).
Example of Console class: Make a file and save it as example_console_class.js with
the following code in the file.
// It requires the fs module
const fs = require('fs');
If you observe above example, we have created a simple object using Console class
with configurable output streams and we have created a Console class object by
using console.Console
Now, we will execute example_console_class.js script file in command prompt by
navigating to the folder where it exists like as shown below.
The above node.js example will create a log files (stdout & stderr) in the folder
where example_console_class.js file exists with required messages like as shown
below.
If you observe above code, we are trying to write a messages to node.js stream by
using global console object methods such as console.log(), console.error() and
console.warn(). Here, we are accessing global console object without importing it
using require directive.
Now, we will execute example_console_object.js file, for that open a command
prompt (cmd) and navigate to the folder that contains
a example_console_object.js file and write the command node
example_console_object.js and hit enter button like as shown below.
If you observe result, we are able to write a required messages to node.js stream by
using global console object.
Console Methods: Apart from above three methods (console.log(),
console.error(), console.warn()), few other methods also available in node.js
console object to write or print a messages in node.js stream.
console.count(): It is used to count the number of times a specific label
has been called.
console.clear(): It is used to clear the console history.
console.info(): It is used to write a messages on console and it is an alias
of console.log() method.
console.time(): It is used to get the starting time of an action.
console.timeEnd(): It is used to get the end time of specific action.
console.dir(): It use util.inspect() on object and prints the resulting string
to stdout.
NODE.JS DNS
DNS is a node module used to do name resolution facility which is provided by the
operating system as well as used to do an actual DNS lookup.
Advantage: No need for memorizing IP addresses – DNS servers provide a nifty
solution for converting domain or subdomain names to IP addresses.
Example 1: In this example, we will print the address of GeeksforGeeks on the
console.
javascript
Output:
address of geeksforgeeks.org is "52.25.109.230" family: IPv4
Example 2: In this example, we will print the address of the GeeksforGeeks.
javascript
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
Output:
Asynchronous read: GeeksforGeeks: A computer science portal
javascript
var fs = require("fs");
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
Output:
Synchronous read: GeeksforGeeks: A computer science portal
Open a File: The fs.open() method is used to create, read, or write a file. The
fs.readFile() method is only for reading the file and fs.writeFile() method is only for
writing to the file, whereas fs.open() method does several operations on a file. First, we
need to load the fs class which is a module to access the physical file system. Syntax:
fs.open(path, flags, mode, callback)
Parameters:
path: It holds the name of the file to read or the entire path if stored at other
locations.
flags: Flags indicate the behavior of the file to be opened. All possible values
are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+).
mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to
default as readwrite.
err: If any error occurs.
data: Contents of the file. It is called after the open operation is executed.
Example: Let us create a js file named main.js having the following code to open a
file input.txt for reading and writing.
javascript
var fs = require("fs");
Output:
opening file!
File open successfully
Reading a File: The fs.read() method is used to read the file specified by fd. This
method reads the entire file into the buffer. Syntax:
fs.read(fd, buffer, offset, length, position, callback)
Parameters:
fd: This is the file descriptor returned by fs.open() method.
buffer: This is the buffer that the data will be written to.
offset: This is the offset in the buffer to start writing at.
length: This is an integer specifying the number of bytes to read.
position: This is an integer specifying where to begin reading from in the
file. If the position is null, data will be read from the current file position.
callback: It is a callback function that is called after reading of the file. It
takes two parameters:
err: If any error occurs.
data: Contents of the file.
Example: Let us create a js file named main.js having the following code:
javascript
var fs = require("fs");
var buf = new Buffer(1024);
Output:
opening an existing file
File opened successfully!
reading the file
40 bytes read
GeeksforGeeks: A computer science portal
Writing to a File: This method will overwrite the file if the file already exists. The
fs.writeFile() method is used to asynchronously write the specified data to a file. By
default, the file would be replaced if it exists. The ‘options’ parameter can be used to
modify the functionality of the method. Syntax:
fs.writeFile(path, data, options, callback)
Parameters:
path: It is a string, Buffer, URL, or file description integer that denotes the
path of the file where it has to be written. Using a file descriptor will make it
behave similarly to fs.write() method.
data: It is a string, Buffer, TypedArray, or DataView that will be written to
the file.
options: It is a string or object that can be used to specify optional parameters
that will affect the output. It has three optional parameters:
encoding: It is a string value that specifies the encoding of the file.
The default value is ‘utf8’.
mode: It is an integer value that specifies the file mode. The
default value is 0o666.
flag: It is a string value that specifies the flag used while writing to
the file. The default value is ‘w’.
callback: It is the function that would be called when the method is executed.
err: It is an error that would be thrown if the operation fails.
Example: Let us create a js file named main.js having the following code:
javascript
var fs = require("fs");
Output:
writing into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Geeks For Geeks
Appending to a File: The fs.appendFile() method is used to synchronously append the
data to the file. Syntax:
fs.appendFile(filepath, data, options, callback);
or
fs.appendFileSync(filepath, data, options);
Parameters:
filepath: It is a String that specifies the file path.
data: It is mandatory and it contains the data that you append to the file.
options: It is an optional parameter that specifies the encoding/mode/flag.
Callback: Function is mandatory and is called when appending data to file is
completed.
Example 1: Let us create a js file named main.js having the following code:
javascript
var fs = require('fs');
// Callback function
function(err) {
if (err) throw err;
// If no error
console.log("Data is appended to file successfully.")
});
Output:
Data is appended to file successfully.
Example 1: For synchronously appending
javascript
var fs = require('fs');
Output:
Data is appended to file successfully.
Before Appending Data to input.txt file:
GeeksforGeeks: A computer science portal
After Appending Data to input.txt file:
GeeksforGeeks: A computer science portal
Learn Node.js
Closing the File: The fs.close() method is used to asynchronously close the given file
descriptor thereby clearing the file that is associated with it. This will allow the file
descriptor to be reused for other files. Calling fs.close() on a file descriptor while some
other operation is being performed on it may lead to undefined behavior. Syntax:
fs.close(fd, callback)
Parameters:
fd: It is an integer that denotes the file descriptor of the file for which to be
closed.
callback: It is a function that would be called when the method is executed.
err: It is an error that would be thrown if the method fails.
Example: Let us create a js file named main.js having the following code:
javascript
Output:
File closed successfully.
Delete a File: The fs.unlink() method is used to remove a file or symbolic link from the
filesystem. This function does not work on directories, therefore it is recommended to
use fs.rmdir() to remove a directory. Syntax:
fs.unlink(path, callback)
Parameters:
path: It is a string, Buffer or URL which represents the file or symbolic link
which has to be removed.
callback: It is a function that would be called when the method is executed.
err: It is an error that would be thrown if the method fails.
Example: Let us create a js file named main.js having the following code:
javascript
var fs = require("fs");
Output:
deleting an existing file
File deleted successfully!
4. Output:
5. The result is: 15
Importing multiple functions from local file: Filename: func.js
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
Filename: main.js
const f = require('./func');
console.log(f.add(4, 4));
console.log(f.subtract(8, 4));
We can also use the destructuring syntax to unpack the properties of the object returned
by require() function and store them in respective variables.
Output:
8
4
Other ways to export a module
Defining the functions inside module.exports object.
module.exports = {
add: function (x, y) {
return x + y;
},
Importing a module from a directory: Importing lib.js file inside the directory, by
prefixing lib.js with the directory name.
const lib = require('./mod/lib');
console.log(lib.add(6, 4));
console.log(lib.subtract(12, 4));
Example 1: In this example, we can create an HTTP server with the help
of http.createServer() method.
Filename: max.js
javascript
const http = require('http');
// Create a server
http.createServer((request, response) => {
Step to run this program: Run this max.js file using the below command:
node max.js
Output:
Console Output:
Browser Output:
Example 2: In this example, we will see to make requests via the HTTP
module http.request() method.
Filename: max.js
javascript
const http = require('http');
let options = {
host: 'www.geeksforgeeks.org',
path: '/courses',
method: 'GET'
};
Step to run this program: Run this max.js file using the below command:
node max.js
Output:
NODE.JS OS MODULE
OS is a node module used to provide information about the computer operating system.
Advantages:
It provides functions to interact with the operating system. It provides the hostname of
the operating system and returns the amount of free system memory in bytes.
Example 1:
javascript
// Include os module and create its object
const os = require('os');
Output:
Example 2:
javascript
// Include os module and create its object
const os = require('os');
Output:
NODE.JS URL MODULE
The url.hash is an inbuilt application programming interface of
class URL within url module which is used to get and set the fragment portion of the
URL.
Syntax:
url.hash
Return value: It gets and sets the fragment portion of the URL.
Below programs illustrate the use of url.hash Method:
Example 1:
Javascript
Output:
Before Change
https://example.org/foo#ram
After Change
https://example.org/foo#rahim
Example 2:
Javascript
Output:
#ram
NODE.JS V8 MODULE
The v8.cachedDataVersionTag() method is an inbuilt application programming
interface of the v8 module which is used to get the version tag derived from the v8
version.
Syntax:
v8.cachedDataVersionTag();
Parameters: This method does not have any parameters.
Return Value: This method returns the version tag from the v8 version, command-line
flags, and detected CPU features.
Example 1: The below example illustrates the use of the v8.cachedDataVersionTag()
method in Node.js.
index.js
javascript
// Accessing v8 module
const v8 = require('v8');
// Calling v8.cachedDataVersionTag()
tag = v8.cachedDataVersionTag();
console.log("cache data version tag is " + tag);
// Accessing v8 module
const v8 = require('v8');
// Calling v8.cachedDataVersionTag()
tagVersion = v8.cachedDataVersionTag();
return tagVersion;
}
// Function call
let result = getTagVersion();
NODE.JS VM MODULE
The Constructor: new vm.Script() method creates a new vm.Script object and
compiles the stated code but it does not run the code. Moreover, the
compiled vm.Script can run afterwards as many times as required. Here, the code is not
connected to any global object, rather it’s connected before each run, just for that
particular run.
Syntax:
Constructor: new vm.Script( code, options )
Parameters: This method accept two parameters as mentioned above and described
below.
code: It is the JavaScript code to compile.
options: It is optional parameter and it returns Object or string. If it returns a
string, then it defines the filename.
Below examples illustrate the use of Constructor: new vm.Script() in Node.js:
Example 1:
// Node.js program to demonstrate the
// Constructor: new vm.Script() method
// Creating context
const context = {
number: 2
};
// Contextifying object
vm.createContext(context);
// Displays output
console.log(context);
Output:
{ number: 4, Type: 'Int' }
Example 2:
// Node.js program to demonstrate the
// Constructor: new vm.Script() method
// Creating context
const context = {
value: 1.0
};
// Contextifying object
vm.createContext(context);
// Displays output
console.log(context);
Output:
{ value: 1.2, Type: 'Float' }