NODE JS
[Link] is an open-source and cross-platform runtime environment for
executing JavaScript code outside a browser. You need to remember
that NodeJS is not a framework, and it’s not a programming
language. [Link] is mostly used in server-side programming.
Creating Web Servers Using NodeJS: To access web pages of any web
application, you need a web server. The web server will handle all the http
requests for the web application e.g IIS is a web server for [Link] web
applications and Apache is a web server for PHP or Java web applications.
[Link] provides capabilities to create your own web server which will handle
HTTP requests asynchronously. You can use IIS or Apache to run [Link] web
application but it is recommended to use [Link] web server. [Link] makes it
easy to create a simple web server that processes incoming requests
asynchronously. There are mainly two ways as follows. Using Built-in HTTP
module, Using Express Module
Using Built-in HTTP module
HTTP and HTTPS, these two inbuilt modules are used to create a simple
server. The HTTPS module provides the feature of the encryption of
communication with the help of the secure layer feature of this module.
Whereas the HTTP module doesn’t provide the encryption of the data.
Building a simple [Link] web server with the http module by using
[Link](), which listens for requests, sends responses, and is ideal for
understanding core server functionality. The following example is a simple
[Link] web server contained in [Link] file.
In the below example, we import the http module using require() function. The
http module is a core module of [Link], so no need to install it using NPM. The
next step is to call createServer() method of http and specify callback function
with request and response parameter. Finally, call listen() method of server
object which was returned from createServer() method with port number, to
start listening to incoming requests on port 5000. You can specify any unused
port here. Run the above web server by writing node [Link] command in
command prompt or terminal window and it will display message as shown
below.
C:\>node [Link]
[Link] web server at port 5000 is running..
This is how you create a [Link] web server using simple steps. Now, let's see
how to handle HTTP request and send response in [Link] web server.
Output: Now open your browser and go to [Link] you will see
the following output:
NodeJS is a powerful runtime environment that allows developers to build
scalable and high-performance applications, especially for I/O-bound
operations. One of the most common uses of NodeJS is to create HTTP servers.
What is HTTP?
HTTP (Hypertext Transfer Protocol) is a protocol used for transferring data
across the web. It's the foundation of any data exchange on the Web and it
allows browsers and servers to communicate. HTTP servers handle incoming
requests from clients (typically web browsers), process them, and send back
appropriate responses.
In NodeJS, the built-in http module makes it easy to create an HTTP server that
can handle these requests.
Steps to Create a NodeJS Server
To create a simple HTTP server in NodeJS, follow these steps:
Step 1: Initialize the Project
Begin by initializing your project using npm, which will create a [Link]
file to manage your project's dependencies and configurations.
npm init -y
Step 2: Import the HTTP Module
NodeJS includes a built-in HTTP module that allows you to create an HTTP
server. It allows [Link] to transfer data over the Hyper Text Transfer Protocol
(HTTP). To include the HTTP module, use the require() method:
var/const http = require('http');
Step 3: Create a Server
Use the [Link]() method to create an HTTP server. This method
accepts a callback function that handles incoming requests and sends responses.
Or The HTTP module can create an HTTP server that listens to server ports and
gives a response back to the client.
Use the createServer() method to create an HTTP server:
const server = [Link]((request, response) => {
// Request handling logic
});
Step 4: Handle Requests
Within the server, set the response header and body to define how the server
responds to incoming requests. And create server object as below
const server = [Link]((request, response) => {
[Link](200, { 'Content-Type': 'text/plain' });
[Link]('Hello, World!\n');
});
Example: After implementing the above steps, we will effectively establish the
NodeJS server
• Loading the http Module: The http module is required to create an
HTTP server.
• Creating the Server: The createServer method is used to create the
server, which takes a callback function that handles incoming requests
and sends responses.
• Setting Response Headers and Body: The writeHead method sets the
HTTP status code and headers, while the end method sends the response
body.
• Starting the Server: The listen method starts the server on the specified
port and IP address, and a callback function logs a message when the
server is running.
Terminal Output: When you start the server, you'll see:
Web Browser Output: When you access [Link] in your web
browser, the server responds with
Now a simple HTTP server is created. You can enhance it to handle more
complex use cases like CRUD operations etc.
Handling Requests And Responses in [Link]
[Link] is a powerful JavaScript runtime for building server-side applications. It
provides an efficient way to handle HTTP requests and responses using the
built-in http module or frameworks like [Link].
The [Link]() method includes request and response parameters which
is supplied by [Link]. The request object can be used to get information about
the current HTTP request e.g., url, request header, and data. The response object
can be used to send a response for a current HTTP request.
The following example demonstrates handling HTTP request and response in
[Link].
Understanding HTTP Requests and Responses
An HTTP request is sent by a client (browser or API) to a server, and the server
processes it to return an HTTP response. The response contains a status code,
headers, and body content.
HTTP Methods
• GET: Retrieves data without modifying it, ensuring the same result for
multiple requests.
• POST: Sends data to create a resource, potentially resulting in duplicates
if repeated.
• PUT: Fully updates an existing resource, replacing all its current data.
• DELETE: Removes a resource from the server, ensuring consistent
results across requests.
HTTP Response Components
• Status Code: Represents the outcome of the request (e.g., 200 OK, 404
Not Found, 500 Server Error).
• Headers: Provide metadata about the response, such as content type and
caching.
• Body: Contains the actual data sent back to the client, in formats like
JSON, HTML, or plain text.
Handling Requests and Responses with HTTP Module
[Link] has a built-in http module to create an HTTP server and handle
requests.
Creating a Simple HTTP Server
Creates an HTTP server that listens for requests and responds with a message.
Handling GET and POST Requests
Defines different behaviors for GET and POST requests.
NODE JS Module
A set of functions you want to include in your application. [Link] has a set of
built-in modules which you can use without any further installation. To include
a module, use the require() function with the name of the module:
var http = require('http');
Now your application has access to the HTTP module, and is able to create a
server:
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]('Hello World!');
}).listen(8080);
You can create your own modules, and easily include them in your applications.
The following example creates a module that returns a date and time object:
[Link] = function () {
return Date();
};
Use the exports keyword to make properties and methods available outside the
module file.
Now you can include and use the module in any of your [Link] files.
Example
Use the module "myfirstmodule" in a [Link] file:
var http = require('http');
var dt = require('./myfirstmodule');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]("The date and time are currently: " + [Link]());
[Link]();
}).listen(8080);
Notice that we use ./ to locate the module, that means that the module is located
in the same folder as the [Link] file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
C:\Users\Your Name>node demo_module.js
If you have followed the same steps on your computer, you will see the same
result as the example: [Link]
In NodeJS, modules play an important role in organizing, structuring, and
reusing code efficiently. A module is a self-contained block of code that can
be exported and imported into different parts of an application. This modular
approach helps developers manage large projects, making them
more scalable and maintainable.
What are Modules in NodeJS?
A NodeJS module is a separate file containing code that can be imported and
reused in other parts of the application. It helps break down large applications
into smaller, manageable sections, each focused on a specific functionality. By
using modules, developers can keep code organized, reusable, and
maintainable.
Modules can contain
• Variables
• Functions
• Classes
• Objects
Types of Modules in NodeJS
NodeJS provides two primary module systems
1. ES6 Modules (ECMAScript Modules – ESM)
ES6 Modules offer a modern and standardized way to
structure NodeJS applications. Unlike CommonJS, ESM uses import/export
instead of require/[Link].
How ES6 Modules Work?
• Uses import to import modules.
• Uses export to export functions, objects, or variables.
• Modules are loaded asynchronously, allowing better performance.
• Requires “type”: “module” in [Link].
Use Cases of ES6 Modules
1. Default Export and Import
The default export allows a module to export a single function, object, or class
as its main functionality. When importing, the name can be customized,
making it more flexible than named exports.
2. Named Exports with Aliases
Named exports allow multiple functions, objects, or variables to be exported
from a single module. Unlike default exports, named exports must be imported
using the exact name they were exported with, unless an alias is provided during
import.
2. CommonJS Modules (CJS)
CommonJS is the default module system used in NodeJS. It enables code
modularity by allowing developers to export and import functions, objects, or
variables using [Link] and require().
How CommonJS Works in NodeJS?
• Uses require() to import modules.
• Uses [Link] to export functions, objects, or variables.
• Modules are loaded synchronously, meaning execution waits until the
module is fully loaded.
• It is default in NodeJS, but not natively supported in browsers.
• Each module runs in its own scope, preventing variable conflicts.
Why Use Modules in NodeJS?
Using modules provides several benefits, including:
• Separation of Concerns: Keeps code modular and well-structured.
• Reusability: Code can be reused across multiple files or projects.
• Encapsulation: Avoids global scope pollution by keeping variables local.
• Maintainability: Smaller, independent modules make debugging easier.
• Performance Optimization: Cached modules improve execution speed.
Benefits of Using Modules in NodeJS
• Encapsulation: Modules help keep the code modular, encapsulating
functionalities within distinct files. This ensures that each module only
exposes what is necessary, preventing unnecessary access to internal
details.
• Reusability: Modules can be reused across different parts of your
application or even in different applications, reducing code duplication
and improving maintainability.
• Maintainability: By breaking down the code into smaller, focused
modules, it’s easier to manage, update, and debug applications as they
grow in complexity.
• Modularity and Separation of Concerns: Each module is responsible
for a specific functionality or task. This approach supports clean code
architecture by separating concerns and making the application easier to
understand.
Conclusion
NodeJS modules provide a powerful way to organize and structure
applications. CommonJS (require/[Link]) remains the default,
while ES6 Modules (import/export) offer modern, efficient alternatives.
Understanding these module systems helps in building scalable, maintainable,
and high-performance NodeJS applications.
[Link] NPM
NPM is a package manager for [Link] packages, or modules. NPM (Node
Package Manager) is a package manager for NodeJS modules. It helps
developers manage project dependencies, scripts, and third-party libraries. By
installing NodeJS on your system, NPM is automatically installed, and ready to
use. Node Package Manager (NPM) is a command line tool that installs,
updates or uninstalls [Link] packages in your application. It is also an online
repository for open-source [Link] packages. The node community around the
world creates useful modules and publishes them as packages in this
repository. It has now become a popular package manager for other open-
source JavaScript frameworks like AngularJS, jQuery, Gulp, Bower etc.
• It is primarily used to manage packages or modules—these are pre-built
pieces of code that extend the functionality of your NodeJS application.
• The NPM registry hosts millions of free packages that you can download
and use in your project.
• NPM is installed automatically when you install NodeJS, so you don’t
need to set it up manually.
Package in NodeJs
A package in NodeJS is a reusable module of code that adds functionality to
your application. It can be anything from a small utility function to a full-
featured library.
• Packages can be installed from the NPM registry.
• They are stored in the node_modules folder in your project.
• You can easily install, update, or remove packages with NPM commands.
[Link] hosts thousands of free packages to download and use.
The NPM program is installed on your computer when you install [Link]. A
package in [Link] contains all the files you need for a module. Modules are
JavaScript libraries you can include in your project.
Downloading a package is very easy. Open the command line interface and tell
NPM to download the package you want.
For example to download a package called "upper-case":
Download "upper-case" command is:
C:\Users\Your Name>npm install upper-case
Now you have downloaded and installed your first package!
NPM creates a folder named "node_modules", where the package will be
placed. All packages you install in the future will be placed in this folder.
My project now has a folder structure like this:
C:\Users\My Name\node_modules\upper-case
To access NPM help, write npm help in the command prompt or terminal
window.
C:\> npm help
NPM performs the operation in two modes: global and local. In the global
mode, NPM performs operations which affect all the [Link] applications on
the computer whereas in the local mode, NPM performs operations for the
particular local directory which affects an application in that directory only.
Use --save at the end of the install command to add dependency entry into
[Link] of your application.
For example, the following command will install ExpressJS in your application
and also adds dependency entry into the [Link].
C:\MyNodeProj> npm install express –save
Update Package
To update the package installed locally in your [Link] project, navigate the
command prompt or terminal window path to the project folder and write the
following update command.
C:\MyNodeProj> npm update <package name>
The following command will update the existing ExpressJS module to the latest
version.
C:\MyNodeProj> npm update express
Uninstall Packages
Use the following command to remove a local package from your project.
C:\>npm uninstall <package name>
The following command will uninstall ExpressJS from the application.
C:\MyNodeProj> npm uninstall express
How to Use NPM with NodeJS?
To start using NPM in your project, follow these simple steps
Step 1: Install NodeJS and NPM
First, you need to install NodeJS. NPM is bundled with the NodeJS installation.
You can follow our article to Install the Node and NPM- How to install Node on
your system
Step 2: Verify the Installation
After installation, verify NodeJS and NPM are installed by running the following
commands in your terminal:
node -v
npm -v
These commands will show the installed versions of NodeJS and NPM.
Step 3: Initialize a New NodeJS Project
In the terminal, navigate to your project directory and run:
npm init -y
This will create a [Link] file, which stores metadata about your project,
including dependencies and scripts.
Step 4: Install Packages with NPM
To install a package, use the following command
npm install <package-name>
For example, to install the [Link] framework
npm install express
This will add express to the node_modules folder and automatically update the
[Link] file with the installed package information.
Step 5: Install Packages Globally
To install packages that you want to use across multiple projects, use the -g
flag:
npm install -g <package-name>
Step 6: Run Scripts
You can also define custom scripts in the [Link] file under the “scripts”
section. For example:
{
"scripts": {
"start": "node [Link]"
}
}
Then, run the script with
npm start
[Link] EVENTS
[Link] is perfect for event-driven applications. Every action on a computer is
an event. Like when a connection is made or a file is opened. Objects in [Link]
can fire events, like the readStream object fires events when opening and
closing a file:
Events Module
[Link] has a built-in module, called "Events", where you can create-, fire-, and
listen for- your own events.
To include the built-in Events module use the require() method. In addition, all
event properties and methods are an instance of an EventEmitter object. To be
able to access these properties and methods, create an EventEmitter object:
var events = require('events');
var eventEmitter = new [Link]();
The EventEmitter Object
You can assign event handlers to your own events with the EventEmitter object.
In the example below we have created a function that will be executed when a
"scream" event is fired. To fire an event, use the emit() method.
Example
var events = require('events');
var eventEmitter = new [Link]();
//Create an event handler:
var myEventHandler = function () {
[Link]('I hear a scream!');
}
//Assign the event handler to an event:
[Link]('scream', myEventHandler);
//Fire the 'scream' event:
[Link]('scream');
[Link] allows us to create and handle custom events easily by using events
module. Event module includes EventEmitter class which can be used to raise
and handle custom events. The following example demonstrates EventEmitter
class for raising and handling a custom event.
In the above example, we first import the 'events' module and then create an
object of EventEmitter class. We then specify event handler function using on()
function. The on() method requires name of the event to handle and callback
function which is called when an event is raised.
The emit() function raises the specified event. First parameter is name of the
event as a string and then arguments. An event can be emitted with zero or
more arguments. You can specify any name for a custom event in the emit()
function.
NODE JS CONSOLE
The [Link] console module provides a way to interact with the command line,
similar to the JavaScript console in web browsers. It offers a
global console object, accessible without requiring it, and a Console class for
more customized instances. The console module is essential for debugging and
logging in [Link] applications. It enables developers to print messages to the
terminal, making it easier to monitor application behavior, track issues, and
display runtime information.
Console in [Link]
The console module in [Link] is a built-in utility that provides access to the
standard output and error streams, offering various methods for printing
information, debugging, and logging messages.
It 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’).
Using the Global console Object
The global console object provides methods for outputting information to the
command line, with the most commonly used being [Link]().
[Link]('Hello, world!'); // Outputs: Hello, world!
Other methods include:
• [Link](): For error messages.
• [Link](): For warning messages.
• [Link](): For informational messages.
• [Link](): For debug messages (often not shown by default).
• [Link](): Displays an object's properties.
• [Link]() and [Link](): Measure execution time.
• [Link](): Displays a stack trace.
• [Link](): Logs an error message if the assertion is false.
Creating a Custom Console Instance
The Console class allows creating instances that write to specific streams, useful
for directing output to files or other destinations.
const fs = require('node:fs');
const myConsole = new [Link]([Link]('./[Link]'),
[Link]('./[Link]'));
[Link]('This will be written to [Link]');
[Link]('This will be written to [Link]');
Features
• Offers various methods for different types of logging and debugging
needs.
• Simple API for developers to quickly output messages and track
application behavior.
• Built-in methods to measure execution time and display performance
metrics.
• [Link]() and [Link]() provide formatted and interactive data
views.
Example: Make a file and save it as example_console_class.js with the
following code in the file.
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].
Example of Global Console Object: Create a file and save it as
example_console_object.js with the following code in the file.
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.
NODE JS Process Model and Advantages
[Link] is a powerful, open-source, and cross-platform JavaScript runtime
environment built on Chrome's V8 engine. NodeJS is a runtime environment for
executing JavaScript outside the browser, built on the V8 JavaScript engine. It
enables server-side development, supports asynchronous, event-driven
programming, and efficiently handles scalable network applications.
• NodeJS is single-threaded, utilizing an event loop to handle multiple
tasks concurrently.
• It is asynchronous and non-blocking, meaning operations do not wait
for execution to complete.
• The V8 engine compiles JavaScript to machine code,
making NodeJS fast and efficient.
• It allows you to run JavaScript code outside the browser, making it ideal
for building scalable server-side and networking applications.
• JavaScript was earlier mainly used for frontend development. With Node
JS (Introduced in 2009), JavaScript became a backend language as well.
• Non-blocking, event-driven architecture for high performance.
• Supports the creation of REST APIs, real-time applications,
and microservices.
• Comes with a rich library of modules through npm (Node Package
Manager).
Why Learn [Link]
• Enables the use of JavaScript for both frontend and backend
development.
• Supports building real-time applications like chat apps and gaming
servers.
• Provides high scalability for I/O-heavy applications.
• Backed by a vibrant community and extensive library support.
Key Features of NodeJS
• Server-Side JavaScript: NodeJS allows JavaScript to run outside the
browser, enabling backend development.
• Asynchronous & Non-Blocking: Uses an event-driven architecture to
handle multiple requests without waiting, improving performance.
• Single-Threaded Event Loop: Efficiently manages concurrent tasks
using a single thread, avoiding thread overhead.
• Fast Execution: Powered by the V8 JavaScript Engine, NodeJS compiles
code directly to machine code for faster execution.
• Scalable & Lightweight: Ideal for building microservices and handling
high-traffic applications efficiently.
• Rich NPM Ecosystem: Access to thousands of open-source libraries
through Node Package Manager (NPM) for faster development.
How NodeJS Works?
NodeJS is a runtime environment that allows JavaScript to run outside
the browser. It is asynchronous, event-driven, and built on the V8 JavaScript
engine, making it ideal for scalable network applications.
NodeJS operates on a single thread but efficiently handles multiple concurrent
requests using an event loop.
• Client Sends a Request: The request can be for data retrieval, file
access, or database queries.
• NodeJS Places the Request in the Event Loop: If the request is non-
blocking (e.g., database fetch), it is sent to a worker thread without
blocking execution.
• Asynchronous Operations Continue in Background: While waiting for
a response, NodeJS processes other tasks.
• Callback Execution: Once the operation completes, the callback
function executes, and the response is sent back to the client.
Where to Use NodeJS?
NodeJS is best suited for applications that require high performance, scalability,
and real-time processing. Below are some common use cases:
• Web APIs and Backend Services : Ideal for building RESTful APIs and
GraphQL APIs. It also Used in backend services for mobile apps and web
applications.
• Real-Time Applications: Chat applications (e.g., WhatsApp, Slack).
Live streaming services (e.g., Netflix, Twitch).
• Microservices Architecture: It helps in developing scalable and
independent services. It also used in cloud-based applications.
• IoT (Internet of Things) Applications: Handles real-time data streaming
from IoT devices. It is suitable for smart home automation and sensor-
based systems.
• Serverless Computing: Works well with AWS Lambda, Azure
Functions, and Google Cloud Functions. Runs lightweight serverless
functions efficiently.
• Single-Page Applications (SPAs): It used in React, Angular,
and [Link] applications. It manages API requests efficiently in the
backend.
• Data-Intensive Applications: It used for big data processing and real-
time analytics. It works well with NoSQL databases
like MongoDB and Firebase.
Applications of NodeJS
Web Development: NodeJS powers backend services for web applications,
handling HTTP requests and managing APIs efficiently.
• Real-Time Applications: Used in chat applications, online gaming, and
live streaming services due to its event-driven, non-blocking
architecture.
• Server-Side Applications: Enables full-stack JavaScript development,
handling database operations, authentication, and server logic.
• Microservices Architecture: Helps build scalable, independent
microservices for modern web applications.
• API Development: Ideal for creating RESTful and GraphQL APIs that
interact with databases and client applications.
• IoT Applications: NodeJS efficiently handles real-time data processing
for IoT devices like sensors and smart home systems.
Limitations of NodeJS
Security Risks – Being open-source and widely used, NodeJS applications are
prone to security vulnerabilities like Cross-Site Scripting (XSS) and SQL
Injection if not handled properly.
• Single-Threaded Limitations: While the event loop manages
concurrency efficiently, CPU-intensive tasks can block the thread,
affecting performance.
• Performance Issues with Heavy Computation: NodeJS is not ideal for
CPU-bound tasks like machine learning or video processing, as it lacks
multi-threading for heavy computations.
• Callback Hell: Older asynchronous code heavily relied on nested
callbacks, making it difficult to read and maintain,
though Promises and Async/Await help mitigate this.
• Weak Type Checking: Since NodeJS runs JavaScript, dynamic typing
can lead to runtime errors and unpredictable behavior without strict type
enforcement.
NodeJS is a powerful runtime environment that extends JavaScript beyond
the browser, enabling fast, scalable, and non-blocking server-side
applications. With its event-driven architecture, V8 engine, and rich NPM
ecosystem, it is widely used for web development, APIs, real-time
applications, and microservices. While it excels in handling I/O-intensive
tasks, it may not be ideal for CPU-heavy computations.
NODE JS Process Model
Traditional Web Server Model
In the traditional web server model, each request is handled by a dedicated
thread from the thread pool. If no thread is available in the thread pool at any
point of time then the request waits till the next available thread. Dedicated
thread executes a particular request and does not return to thread pool until it
completes the execution and returns a response.
[Link] Process Model
[Link] processes user requests differently when compared to a traditional web
server model. [Link] runs in a single process and the application code runs in a
single thread and thereby needs less resources than other platforms. All the user
requests to your web application will be handled by a single thread and all the
I/O work or long running job is performed asynchronously for a particular
request. So, this single thread doesn't have to wait for the request to complete
and is free to handle the next request. When asynchronous I/O work completes
then it processes the request further and sends the response.
An event loop is constantly watching for the events to be raised for an
asynchronous job and executing callback function when the job completes.
Internally, [Link] uses libev for the event loop which in turn uses internal C++
thread pool to provide asynchronous I/O.
The following figure illustrates asynchronous web server model using [Link].
[Link] process model increases the performance and scalability with a few
caveats. [Link] is not fit for an application which performs CPU-intensive
operations like image processing or other heavy computation work because it
takes time to process a request and thereby blocks the single thread.
Install [Link]
In this section, you will learn about the tools required and steps to setup
development environment to develop a [Link] application.
[Link] development environment can be setup in Windows, Mac, Linux and
Solaris. The following tools/SDK are required for developing a [Link]
application on any platform.
1. [Link]
2. Node Package Manager (NPM)
3. IDE (Integrated Development Environment) or TextEditor
NPM (Node Package Manager) is included in [Link] installation since Node
version 0.6.0., so there is no need to install it separately.
Install [Link] on Windows
Visit [Link] official web site [Link] It will automatically detect OS
and display download link as per your Operating System. For example, it will
display following download link for 64 bit Windows OS.
Download the installer for windows by clicking on LTS or Current version
button. Here, we will install the latest version LTS for windows that has long
time support. However, you can also install the Current version which will have
the latest features. After you download the MSI, double-click on it to start the
installation.
Click Next to read and accept the License Agreement and then click Install. It
will install [Link] quickly on your computer. Finally, click finish to complete
the installation.
Verify Installation
Once you install [Link] on your computer, you can verify it by opening the
command prompt and typing node -v. If [Link] is installed successfully then it
will display the version of the [Link] installed on your machine
[Link] Console/REPL
[Link] comes with virtual environment called REPL ( Node shell). REPL
stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple
[Link]/JavaScript code. NodeJS REPL (Read-Eval-Print Loop) is an interactive
shell that allows you to execute JavaScript code line-by-line and see immediate
results. This tool is extremely useful for quick testing, debugging, and learning,
providing a sandbox where you can experiment with JavaScript code in a
NodeJS environment.
In this article, we’ll explore what the NodeJS REPL is, how it works, its key
features, and how you can use it effectively for testing and debugging.
What is REPL?
REPL is like a JavaScript playground in your terminal. If you type the code,
REPL runs it, shows you the result, and then waits for your next command. It’s
a loop:
• READ: You type some JavaScript code into the terminal, and REPL
reads what you typed.
• EVAL: REPL runs (evaluates) your code.
• PRINT: REPL shows you the result of your code.
• LOOP: REPL goes back to step 1, waiting for you to type more code.
This loop continues until you quit REPL.
Getting Started with REPL
To start working with the REPL environment of NodeJS, follow one of these
two methods:
Starting REPL in the Terminal or Command Prompt
• Open your terminal (for UNIX/Linux) or Command Prompt (for
Windows).
• Type node and press ‘Enter’ to start the REPL.
node
To launch the REPL (Node shell), open command prompt (in Windows) and
type node as shown above. It will change the prompt to > in Windows. Various
operations can be performed on the REPL. Below are some of the examples to
get familiar with the REPL [Link] can now test pretty much any
[Link]/JavaScript expression in REPL. 10 + 20 will display 30 immediately in
new line.
Key Features of NodeJS REPL
Executing JavaScript Code
The REPL is a full-featured JavaScript environment, meaning you can run any
valid JavaScript code inside it.
Example:
> const x = 10;> const y = 20;> x + y30
• You can declare variables, create functions, and run any code that would
work in a regular JavaScript runtime.
Multi-Line Input
In case of complex logic (like loops or functions), the REPL supports multi-line
input. When you enter a block of code, the REPL will continue reading input
until the block is complete.
Example:
> function add(a, b) {... return a + b;... }> add(5, 10)15
• Here, the REPL waits for you to complete the function block before
evaluating the code.
Underscore (_) Variable
The REPL provides a special variable _ (underscore) that stores the result of the
last evaluated expression.
Example:
> 3 + 36> _ * 212
• In this case, the result of 3 + 3 is stored in _, which is then used in the
next line to calculate 12.
Built-in REPL Commands
NodeJS REPL provides several built-in commands (REPL commands always
start with a dot .).
• .help: Displays a list of all available REPL commands.
• .break: Breaks out of multi-line input or clears the current input.
• .clear: Resets the REPL context by clearing all declared variables.
• .exit: Exits the REPL session.
Arithmetical operations in REPL
Arithmetical operations in REPL
Operations using libraries of NODE
Math library methods gfg
• Note: using ‘math’ shows error as the library is referenced as ‘Math’ in
NODE and not ‘math’.
Using variables in REPL
The keyword var is used to assign values to variables.
Using Variables in REPL
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.
Best Practices for NodeJs REPL
• Use REPL for Quick Testing: Utilize the REPL to test small code
snippets or experiment with new features without creating a separate file.
• Leverage Built-in Modules: Access and test NodeJS built-in modules
directly in the REPL to understand their functionality and behavior.
• Save and Load Code with .save and .load: Continue your REPL
sessions by saving code to a file and loading it back later for continued
work or testing.
• Use for Prototyping and Debugging: Quickly test small code snippets
or debug specific functionality by running them interactively in the
REPL.