0% found this document useful (0 votes)
56 views32 pages

WDF Unit Ii Notes

Uploaded by

keerthikt10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views32 pages

WDF Unit Ii Notes

Uploaded by

keerthikt10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

JAL1502 - WEB DEVELOPMENT FRAMEWORK

UNIT II - NODE JS
Understanding Node JS - Installing Node.js - Working with Node packages - Creating a simple Node.js
application - Handling Data I/O - Using the Buffer Module to Buffer Data - Implementing HTTP services in
Node.js - Processing URLs - Processing Query Strings and Form Parameters - Understanding Request,
Response, and Server Objects.
2.1. Understanding the Node.js:
 Node.js was developed in 2009 by Ryan Dahl as an answer to the frustration caused by
concurrency issues, especially when dealing with web services. Google had just come out with
the V8 JavaScript engine for the Chrome web browser, which was highly optimized for web
traffic. Dahl created Node.js on top of V8 as a server-side environment that matched the client-
side environment in the browser.
 The result is an extremely scalable server-side environment that allows developers to more
easily bridge the gap between client and server. The fact that Node.js is written in JavaScript
allows developers to easily navigate back and forth between client and server code and even
reuse code between the two environments.
 Node.js has a great ecosystem with new extensions being written all the time. The Node.js
environment is clean and easy to install, configure, and deploy. Literally in only an hour or two
you can have a Node.js webserver up and running.
 Node.js is an open-source server-side runtime environment built on Chrome’s V8 JavaScript
engine.
 It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime
environment for building highly scalable server-side applications using JavaScript.
 Who Uses Node.js?
Node.js quickly gained popularity among a wide variety of companies. These companies
use Node.js first and foremost for scalability but also for ease of maintenance and faster
development. The following are just a few of the companies using the Node.js technology:
■ Yahoo!
■ LinkedIn
■ eBay
■ New York Times
■ Dow Jones
■ Microsoft
 What Is Node.js Used For?
Node.js can be used for a wide variety of purposes. Because it is based on V8 and has highly
optimized code to handle HTTP traffic, the most common use is as a webserver. However,
Node.js can also be used for a variety of other web services such as:
■ Web services APIs such as REST
■ Real-time multiplayer games
■ Backend web services such as cross-domain, server-side requests
■ Web-based applications
■ Multiclient communication such as IM
 What Does Node.js Come With?
Node.js comes with many built-in modules available right out of the box.
■ Assertion testing: Allows you to test functionality within your code.
■ Buffer: Enables interaction with TCP streams and file system operations.
■ C/C++ add-ons: Allows for C or C++ code to be used just like any other Node.js module.
■ Child processes: Allows you to create child processes.
■ Cluster: Enables the use of multicore systems.
■ Command line options: Gives you Node.js commands to use from a terminal.
■ Console: Gives the user a debugging console.
■ Crypto: Allows for the creation of custom encryption.
■ Debugger: Allows debugging of a Node.js file.
■ DNS: Allows connections to DNS servers.
■ Errors: Allows for the handling of errors.
■ Events: Enables the handling of asynchronous events.
■ File system: Allows for file I/O with both synchronous and asynchronous methods.
■ Globals: Makes frequently used modules available without having to include them first.
■ HTTP: Enables support for many HTTP features.
■ HTTPS: Enables HTTP over the TLS/SSL.
■ Modules: Provides the module loading system for Node.js.
■ Net: Allows the creation of servers and clients.
■ OS: Allows access to the operating system that Node.js is running on.
■ Path: Enables access to file and directory paths.
■ Process: Provides information and allows control over the current Node.js process.
■ Query strings: Allows for parsing and formatting URL queries.
■ Readline: Enables an interface to read from a data stream.
■ REPL: Allows developers to create a command shell.
■ Stream: Provides an API to build objects with the stream interface.
■ String decoder: Provides an API to decode buffer objects into strings.
■ Timers: Allows for scheduling functions to be called in the future.
■ TLS/SSL: Implements TLS and SSL protocols.
■ URL: Enables URL resolution and parsing.
■ Utilities: Provides support for various apps and modules.
■ V8: Exposes APIs for the Node.js version of V8.
■ VM: Allows for a V8 virtual machine to run and compile code.
■ ZLIB: Enables compression using Gzip and Deflate/Inflate.

 The main features of Node.js are:


1. Event Driven Architecture
2. Non-Blocking I/O Model
3. Asynchronous by Default

 Node.js can be used to build different types of applications such as command line application,
web application, real-time chat application, REST API server, chat rooms, web streaming
options, for collection of data, data processing, browser games, high-speed applications, the
databases that are expected to be scalable/expandable eventually. Application program
interfaces applied on the databases, queueing applications like message queues, etc.

 Key elements of Node.js:

 Requests – Based on the specific tasks users need to perform in a web application, the requests
can either be blocking (complex) or non-blocking (simple).
 Node.js server – It accepts user requests, processes them, and returns the results to the
corresponding users.
 Event queue – It stores the incoming requests and passes them sequentially to the Event Pool.
 Event loop – After receiving the client requests from the event queue, it sends responses to
corresponding clients.
 Thread pool – It contains the threads available for performing those operations necessary to
process requests.
 External resources – The external resources are used for blocking client requests and can be
used for computation, data storage, and more.

2.2. Installing Node.js


The following tools/SDK are required for developing a Node.js application on any platform.
1. Node.js
2. Node Package Manager (NPM)
3. IDE (Integrated Development Environment) or Text Editor
 NPM (Node Package Manager) is included in Node.js installation since Node.js version
0.6.0, so there is no need to install it separately.
 Installing node.js :
To easily install Node.js, download an installer from the Node.js website at http://nodejs.org.
The Node.js installer installs the necessary files on your PC to get Node.js up and running. No
additional configuration is necessary to start creating Node.js applications.
 Looking at the Node.js Install Location :
The install location contains a couple of executable files and a node_modules folder. The node
executable file starts the Node.js JavaScript VM. The following list describes the executables in
the Node.js install location:
■ node: This file starts a Node.js JavaScript VM. If you pass in a JavaScript file location,
Node.js executes that script. If no target JavaScript file is specified, then a script prompt is
shown which allows to execute JavaScript code directly from the console.
■ npm: This command is used to manage the Node.js packages.
■ node_modules: This folder contains the installed Node.js packages. These packages act as
libraries that extend the capabilities of Node.js.
 Verify Node.js Executables:
1. Open a console prompt and execute the following command to bring up a Node.js VM:
node -v
2. Next, at the Node.js prompt execute the following to write "Hello World" to the screen.
>console.log("Hello World");
"Hello World" will be shown in the output to the console screen. Now exit the console using
Ctrl+C in Windows or Cmd+C on a Mac.
3. Next, verify that the npm command is working by executing the following command in the
OS console prompt:
npm version
Displayed output will be similar to the following:
{ npm: '3.10.5',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.5.0',
openssl: '1.0.2h',
uv: '1.9.1',
v8: '5.1.281.81',
zlib: '1.2.8'}
 Selecting a Node.js IDE:
Configure any Integrated Development Environment (IDE) to generate your Node.js web
applications. For example, Eclipse has some great Node.js plugins, and the WebStorm IDE by
IntelliJ has some good features for Node.js built in. If unsure of where to start use Visual
Studio Code for the built-in TypeScript functionality. All we need is a decent text editor.
Almost all the code will be .js, .json, .html, and .css. So pick the editor in which feel the most
comfortable writing those types of files.
Install Node.js on Windows:
The first step in using Node.js is the installation of the Node.js libraries on the client system. Below are
the steps to download and install Node.js in Windows:
Step 1: Download the Installer
 Download the Windows Installer from Node.js official website (nodejs.org). It will
automatically detect OS and display the download as per your Operating System.
 For example, it will display the following download link for 64 bit Windows OS.
 Download the installer for windows by clicking on LTS (Long-term Support) or Current
version button.
Step 2 : Installing Node.js and NPM:

After choosing the path, double click to install .msi binary files to initiate the installation
process. Then give access to run the application.

Clicking on the Next button, a custom page setup page will be opened. Choose npm package
manager, not the default of Node.js runtime. This way, Node and NPM can be installed
simultaneously.
 143MB of space is required to install Node.js and npm features.
 The following features will be installed by default:
 Node.js runtime
 Npm package manager
 Online documentation shortcuts
 Add to Path
Click the Install button to start Installing node.js on Windows
Step 3 : Check Nodejs and NPM Version

 Go to command prompt, type "node -v" command to confirm node installation


 To confirm NPM installation, type “npm -v" command

Installing Nodejs and NPM on Mac:


Step 1 : Download the .pkg Installer

 Click on the “ macOS Installer ” option to download the .pkg installer. Make sure you
download it to your desired location.
 Go to Node.js official website. -> https://nodejs.org/en
 Click the “Download” button on the Homepage.
 Download the recommended LTS(Long-Term Support) version for MacOS on the download
page.

Step 2 : Run Node.js Installer


 After the download has completed, execute the downloaded .pkg file by double-clicking on it.
 Setup Wizard will guide us. During the installation, we can accept the default settings.

 After the installation has completed, finalize it by clicking on a button such as “Finish”,
“Close” or “Complete Installation”.
Step 3: Verify Node.js installation

 To validate that Node.js installation is successful, open a terminal and run the command.
Check the installed Node.js version.
 Run the "node -v" command in your terminal to confirm node installation.
Step 4: Update your NPM Version
 $ sudo npm install npm -g // global
2.3. Working with Node packages
1. NODE PACKAGE MANAGER:
 The NPM -Node Package Manager is the default package manager for Node.js
 Basically, NodeJs is a JavaScript runtime environment, allowing developers to develop the
scalable application in a given time.
 NPM allows developers to easily install, share, and manage libraries and tools needed for their
JavaScript applications.
 NPM allows open-source web developers to share and borrow packages for app development.
 It works as a command-line utility for the application for installing packages in the project,
dependency management, and even version management.
 It is a dependency and module manager for the ecosystem, similar to other managers such as
composer in PHP or pip in Python.
 Node Package Manager provides two main functionalities:
 It provides online repositories for node.js packages/modules which are searchable on
search.nodejs.org
 It also provides command line utility to install Node.js packages, do version management
and dependency management of Node.js packages.
//Components of NPM:
 Website: Packages can be found from the official NPM website for the project. Also, create and
set up profiles to manage and access all types of packages.
 Command Line Interface (CLI): To Interface with NPM packages and repositories, the CLI
runs from your computer's terminal.
 Registry: It has a huge database of JavaScript projects and meta-data. Thus it allows to use
any supported NPM registry. Also, it is possible to utilise someone else's registry as per their
terms of use.
 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.
 To check NPM Version
npm -v
 To update the NPM Version
npm update npm@latest-g
As npm is a global package, -g flag is used to update it globally.
 To access NPM help, write npm help in the command prompt or terminal window
npm help
2.WORKING WITH NODE PACKAGES:
 A Node Packaged Module is a packaged library that can easily be shared, reused, and installed
in different projects. Many different modules are available for a variety of purposes.
For example, the Mongoose module provides an ODM (Operational Data Model) for
MongoDB, Express extends Node’s HTTP capabilities, and so on.
 Node.js modules are created by various third-party organizations to provide the needed features
that Node.js lacks out of the box. This community of contributors is active in adding and
updating modules.
 Node Packaged Modules include a package.json file that defines the packages. The package.json
file includes informational metadata, such as the name, version author, and contributors, as well
as control metadata, such as dependencies and other requirements that the Node Package
Manager uses when performing actions such as installation and publishing.
Understanding the Node Package Registry
 The Node modules have a managed location called the Node Package Registry where packages
are registered. This allows to publish own packages in a location where others can use them as
well as download packages that others have created.
 The Node Package Registry is located at https://npmjs.com. From this location ,can view
the newest and most popular modules as well as search for specific packages, as shown in below
👇

 Using the Node Package Manager


 The Node Package Manager have already seen is a command-line utility. It allows to find,
install, remove, publish, and do everything else related to Node Package Modules.
 The Node Package Manager provides the link between the Node Package Registry and
your development environment.
 The simplest way to explain the Node Package Manager is to list some of the command-line
options and what they do.

Option Description Example

search Finds module packages in the npm search express


repository
install Installs a package either using a npm install
package.json file, from the repository,
npm install express
or a local location
npm install [email protected]
npm install ../tModule.tgz
install -g Installs a package globally npm install express -g
remove Removes a module npm remove express

pack Packages the module defined by the npm pack


package.json file into a .tgz file
view Displays module details npm view express
publish Publishes the module defined by a npm publish
package.json file to the registry
unpublish Unpublishes a module you have npm unpublish myModule
published
owner Allows you to add, remove, and list npm add bdayley myModule
owners of a package in the repository npm rm bdayley myModule
npm ls myModule

 Searching for Node Package Modules


 Search for modules in the Node Package Registry directly from the command prompt using the
npm search <search_string> command.
 For example, the following command searches for modules related to openssl and displays the
results as shown in below
npm search openssl
 Installing Node Packaged Modules
 To use a Node module in applications, it must first be installed where Node can find it.
 To install a Node module, use the npm install <module_name> command. This downloads the
Node module to your development environment and places it into the node_modules folder
where the install command is run. For example, the following command installs the express
module:
npm install express
 The output of the npm install command displays the dependency hierarchy installed with
the module. For example, the following code block shows part of the output from installing
the express module.
C:\express\example
`-- [email protected]
+-- [email protected]
| +-- [email protected]
| | `-- [email protected]
| `-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
| `-- [email protected] ...

 The dependency hierarchy is listed; some of the methods Express requires are cookie-
signature, range-parser, debug, fresh, cookie, and send modules. Each of these was
downloaded during the install. Notice that the version of each dependency module is listed.
 Node.js has to be able to handle dependency conflicts. For example, the express module
requires cookie 0.3.1, but another module may require cookie 0.3.0. To handle this
situation, a separate copy for the cookie module is placed in each module’s folder under
another node_modules folder.
 To illustrate how modules are stored in a hierarchy, consider the following example of how
express looks on disk. Notice that the cookie and send modules are located under the
express module hierarchy, and that since the send module requires mime it is located under
the send hierarchy:
./
./node_modules
./node_modules/express
./node_modules/express/node_modules/cookie
./node_modules/express/node_modules/send
./node_modules/express/node_modules/send/node_modules/mime

 Install packages locally


npm install <package_name>
Example: The following command will install ExpressJS into MyNodeProj folder.
npm install express
All the modules installed using NPM are installed under node_modules folder. The above
command will create ExpressJS folder under node_modules folder in the root folder of your
project and install Express.js there.
 Install package globally
NPM can also install packages globally so that all the node.js application on that computer can
import and use the installed packages, NPM installs global packages into
/<User>/local/lib/node_modules folder.
Apply -g in the install command to install package globally.
Example: The following command will install ExpressJS globally.
npm install -g express
 Update Package
To update the package installed locally in your Node.js project, navigate the command prompt
or terminal window path to the project folder and write the following update command.
npm update <package name>
Example: The following command will update the existing ExpressJS module to the latest
version.
npm update express
 Uninstall Packages
npm uninstall <package name>
Example: The following command will uninstall ExpressJS from the application
npm uninstall express
USING PACKAGE.JSON
 Node uses a file called package.json
 A package is a folder tree described by a package.json file.
 The package consists of the folder containing the package.json file and all subfolders until the
next folder containing another package.json file, or a folder named node_modules.
 A package.json is a JSON file located in the root of a JS project that holds relevant metadata
for the project and manages a project's dependencies, scripts, version,etc.
 Module in Node.js is a simple or complex functionality organized in single or multiple
JavaScript files which can be reused throughout the Node.js application
 Each module in Node.js has its own context, so it cannot interfere with other modules or
pollute global scope. Also, each module can be placed in a seperate .js file under a separate
folder.
 The main purpose of this file is to centralize all project dependencies so that the application
can work properly.
 Node.js modules are a type of package that can be published to npm.
 Node modules must include a package.json file in their root directory. The package.json file is
a simple JSON text file that defines the module including dependencies. The package.json.file
can contain a number of different directives to tell the Node Package Manager how to handle
the module.
 The following is an example of a package.json file with a name, version, description, and
dependencies:
{
"name": "my_module",
"version": "0.1.0",
"description": "a simple node.js module",
"dependencies" : {
"express" : "latest"
}
}
 The only required directives in the package.json file are name and version. The rest depend
on what we want to include. Most common directives are listed below:
Directive Description Example
name Unique name of package "name": "camelot"
preferGlobal Indicates this module prefers to be "preferGlobal": true
installed globally.
version Version of the module "version": 0.0.1

author Author of the project "author": "arthur@???.com"

contributors Additional contributors to the "contributors": [ { "name": "gwen",


module. "email": "gwen@???.com"}]
description Textual description of module. "description": "a silly place"

bin Binary to be installed globally with "bin: { "excalibur": "./bin/excalibur"}


project.
scripts Specifies parameters that execute "scripts" { "start": "node
console apps when launching node ./bin/ excalibur", "test": "echo testing"}
main Specifies the main entry point for the "main": "./bin/excalibur"
app. This can be a binary or a .js file.
repository Specifies the repository type and "repository": { "type":
location of the package. "git", "location": "http://???.com/c.git"}
keywords Specifies keywords that show up in "keywords": [ "swallow", "unladen" ]
the npm search.
dependencies Modules and versions this module "dependencies": {
depends on. You can use the * and x "express": "latest", "connect": "2.x.x,
wildcards. "cookies": "*" }
engines Version of node this package works "engines": {
with. "node": ">=6.5"}

 A great way to use package.json files is to automatically download and install the dependencies
for your Node.js app. Create a package.json file in the root of your project code and add the
necessary dependencies to it. For example, the following package.json requires the express
module as a dependency.
{ "name":
"my_module",
"version": "0.1.0",
"dependencies" : {
"express" : "latest"
}
}
 Then you run the following command from root of your package, and the express module is
automatically installed.
npm install
 No module is specified in the npm install because npm looks for a package.json file by
default.To add the additional modules, add those to the dependencies directive and then run
npm install again.
//CREATE A PACKAGE.JSON FILE
 Create a package.json file to store useful metadata about the project and help to manage the
project's dependent Node.js modules.
 This is a JSON (JavaScript Object Notation) file which is a standard format used for sharing,
based on JavaScript objects and consisting of data stored as key.value pairs.
 A package.json file can be created in two ways:
1. Using npm init: Running this command, system expects user to fill the vital information
required. It provides users with default values which are editable by the user
npm init
This will open a CLI prompt that will ask you a few questions to help fill in your new
package.json file.
This utility will walk you through creating a package.json file.
It only covers the most common items and tries to guess sensible defaults.
See 'npm help init' for definitive documentation on these fields and exactly what they do.
Use 'npm install <pkg> 'afterwards to install a package and save it as a dependency in the
package.json file.
Press ^C at any time to quit.
package name:

 It will ask information like the name of your project, version, description, entry point, test
command, git repository, keywords, author, and license.
 Hit center to accept the default value or you can type in your own value if you want to
change it.
 Once you finish with the questions, you'll be prompted to save the file.
 package.json will be generated when npm init is run to initialise a JavaScript/ Node.js
project, with these basic metadata provided by developers:
 name: Name represents the names of the project. The name must be:
 one word
 lower case
 not start with an ''_" or '.'

 version: The version denotes the current version of the modules. It must follow the
semantic versioning guidelines, e.g., 1.0.0
 description: The description provides more information about the project.
 • Engines: The engine property i is an object used to specify the library versions
required for the application to run.
 license: the project's license
 Scripts: Scripts are key-value pairs used to perform a series of tasks such as building,
testing, etc. %
 Main: Main is the entry point of the application and should refer to main page of your
app.
 Homepage: Homepage is used to specify the landing page of the app.
Example: package.json file-1
{
"name":"',
"version": "1.0.0",
"description":"",
"main": "index.js",
"scripts": {
"Test": "echo "Error: no test specified\" &&exit 1"
}
"author":"',
"license": "ISC"
Installing all dependencies
 To install any dependencies type npm install in the root of the project, and it will automatically
alter the package.json file to include the dependencies, or we ca manually edit the file yourself,
then run npm install to install the dependencies.
npm install
 Dependencies: It denotes the list of modules and packages required for the application to
function. It is added to the dependency list when installed.
 dev Dependencies: are modules that are not required to run the application but are needed in
the development phase.
Controlling where the package gets installed:
 To install a package and simultaneously save it in package.json file (in case using Node.js), add
-save flag. The-save flag is default in npm install command so it is equal so npm install
package_name command.
 Examples:
npm install express_save
By-save flag one can control where the packages are to be installed.
 -save-prod: Using this packages will appear in Dependencies which is also by
default.
 -save-dev: Using this packages will get appear in dev Dependencies and only be
used in the development mode
Examples:
npm install node-color-save-dev
Example package.json file 2: This is an example that contains all of the properties of
json file{
"name": "packnge.json-educative",
"version": "1.0.0",
"description": "Master file of packnge.json",
"private": true,
"main": "index.js",
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"repository": {
"type": "git",
"url": "https://github.com/Educative/package.json-educative.git"
},
"keywords": [
"node",
"package.json",
"javascript",
"npm"
],
"author": "Sahara",
"license": "Standard",
"homepage": "https://github.com/Educative/packagejson-educative#readme",
"engines": {
"npm": "6.10.4",
"node": "10.14.3"
},
"dependencies": {},
"devDependencies": {}
}
2.4. Creating a simple Node.js application

 Creating a Node.js Packaged Module


 To create a Node.js Packaged Module, create the functionality in JavaScript, define
 the package using a package.json file, and then either publish it to the registry or package it for
local use.
 The following steps explains the process of building a Node.js Packaged Module using an
example called censorify. The censorify module accepts text and then replaces certain words
with asterisks:
1. Create a project folder named .../censorify. This is the root of the package.
2. Inside that folder, create a file named censortext.js.
3. Add the code from censortext.js. Most of the code is just basic JavaScript; however, note
that lines 18–20 export the functions censor(), addCensoredWord(), and
getCensoredWords(). The exports.censor is required for Node.js applications using this
module to have access to the censor() function as well as the other two.
 censortext.js: Implementing a simple censor function and exporting it for other modules using
the package
01 var censoredWords = ["sad", "bad", "mad"];
02 var customCensoredWords = [];
03 function censor(inStr) {
04 for (idx in censoredWords) {
05 inStr = inStr.replace(censoredWords[idx], "****");
06 }
07 for (idx in customCensoredWords) {
08 inStr = inStr.replace(customCensoredWords[idx], "****");
09 }
10 return inStr;
11 }
12 function addCensoredWord(word){
13 customCensoredWords.push(word);
14 }
15 function getCensoredWords(){
16 return censoredWords.concat(customCensoredWords);
17 }
18 exports.censor = censor;
19 exports.addCensoredWord = addCensoredWord;
20 exports.getCensoredWords = getCensoredWords;
4. Once the module code is completed, create a package.json file that is used to generate the Node.js
Packaged Module. Create a package.json file in the./censorify folder. Then add contents specifically,
add the name, version, and main directives as a minimum. The main directive needs to be the name of
the main JavaScript module that will be loaded, in this case censortext. Note that the .js is not
required, Node.js automatically searches for the .js extension.
package.json: Defining the Node.js module
01 {
02 "author": "Brendan Dayley",
03 "name": "censorify",
04 "version": "0.1.1",
05 "description": "Censors words out of text",
06 "main": "censortext",
07 "dependencies": {},
08 "engines": {
09 "node": "*"
10 }
11 }
5. Create a file named README.md in the .../censorify folder and put whatever read
me instructions you want in this file.
6. Navigate to the .../censorify folder in a console window and run the npm pack
command to build a local package module.
7. The npm pack command creates a censorify-0.1.1.tgz file in the .../censorify
folder. This is the first Node.js Packaged Module.
//Creating the simple node.js application in two ways:
1. Console based
2. Web based
1. Creating a simple hello world node.js application using console based method:
Use the Node.js console module to print output on your system console. Create a JavaScript file
nodejs_hello_console.js using the below content.
console.log('Hello World');
Execute the script using the node:
$ node nodejs_hello_console.js
[output] Hello World!
2. Creating a simple hello world node.js application using web based method:
root@recadmin:~;
root@recadmin:~; node nodejs_hello_console.js
Hello World!
root@recadmin:~;
root@recadmin:~;
A Node.js web application is built with 3 parts:
 Import module to create web server
 Create a web server
 Read client requests and send response back to client
Below is the sample application uses http module. http module creates a web server similar
to Apache or Nginx web servers.
Create a server with specified host and port.
Use 0.0.0.0 host address means it will listen on all interfaces attached to the system.
Create a JavaScript file nodejs_hello_web.js and add the following content:
const http = require('http');
const host = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!');
});
server.listen(port, host, () => {
console.log('Web server running at http://%s:%s', host, port);
});
Execute the script using node. It will start a web server on specified port and host:
node nodejs_hello_web.js
[Output] Web server running at http://0.0.0.0:3000
For example, above script started a web server on port 3000.
Visit the server on a defined port in the web browser.It will show the result as:
Hello World!
Publishing a Node.js Packaged Module to the NPM Registry
In the previous section you created a local Node.js Packaged Module using the npm packcommand.
You can also publish that same module to the NPM repository at http://npmjs.com/.When modules
are published to the NPM registry, they are accessible to everyone using the NPM manager utility
discussed earlier. This allows you to distribute your modules and applications to others more easily.
The following steps describe the process of publishing the module to the NPM registry. These steps
assume that you have completed steps 1 through 5 from the previous section:
1. Create a public repository to contain the code for the module. Then push the contents of the
.../censorify folder up to that location. The following is an example of a Github repository URL:
https://github.com/username/projectname/directoryName/ch03/censorify
2. Create an account at https://npmjs.org/signup.
3. Use the npm adduser command from a console prompt to add the user you created to the
environment.
4. Type in the username, password, and email that you used to create the account in step 2.
5. Modify the package.json file to include the new repository information and any keywords that you
want made available in the registry search as shown in lines 7–14 in Listing 3.3.
Listing 3.3 package.json: Defining the Node.js module that includes the repository and
keywords information
01 {
02 "author": "Brad Dayley",
03 "name": "censorify",
04 "version": "0.1.1",
05 "description": "Censors words out of text",
06 "main": "censortext",
07 "repository": {
08 "type": "git",
09 //"url": "Enter your github url"
10 },
11 "keywords": [
12 "censor",
13 "words"
14 ],
15 "dependencies": {},
16 "engines": {
17 "node": "*"
18 }
19 }
6. Publish the module using the following command from the .../censor folder in the console:
npm publish
Once the package has been published you can search for it on the NPM registry and use the
npm install command to install it into your environment.
To remove a package from the registry make sure that you have added a user with rights to the
module to the environment using npm adduser and then execute the following command:
npm unpublish <project name>
For example, the following command unpublishes the censorify module:
npm unpublish censorify
In some instances you cannot unpublish the module without using the --force option. This
option forces the removal and deletion of the module from the registry. For example:
npm unpublish censorify --force
2.5. Handling Data I/O:
1.Introduction to Data Flow in Web Applications:
 Modern web applications and services are constantly handling large volumes of data. This data
flow is continuous and integral to the functioning of these systems.
 The types of data these applications handle can vary. It includes:
Text: Simple string data (e.g., user input, logs).
JSON strings: Structured data in JSON format, commonly used for APIs.
Binary buffers: Raw binary data, often used for files or media.
Data streams: Continuous flows of data, such as video feeds or real-time updates.
2.Node.js Support for Data I/O
 Node.js provides various built-in tools and features specifically designed to handle the input
and output (I/O) of data between different systems. This includes reading, writing, and
processing different types of data effectively.
3.Importance of Understanding Node.js Mechanisms

 To build robust and performant web applications with Node.js, developers must understand
these data-handling mechanisms. This knowledge ensures that applications can process data
efficiently, making them more responsive and scalable.
 Manipulating JSON data: How to work with JSON strings, converting them to objects and vice
versa.
 Managing binary data buffers: Handling raw binary data efficiently using Node.js buffers.
 Implementing readable and writable streams: Creating streams for continuous data flow,
which is crucial for handling large datasets or real-time data.
 Compressing and decompressing data: Techniques to reduce data size for storage or
transmission and to restore it to its original form.
1. Introduction to JSON : JSON is widely used in Node.js applications to represent and exchange
data. It’s a standard format for data interchange, particularly in web applications and APIs.
2. JSON Serialization and Deserialization : JSON allows you to convert JavaScript objects into a
string format using JSON.stringify() for transmission or storage. Similarly, you can convert
the string back into an object using JSON.parse().
Serialization is the process of converting objects into a format suitable for storage or
transmission. JSON is used for serializing and deserializing data to facilitate communication
between different parts of a system (e.g., between a web client and server or between services).
3. Advantages of JSON Over XML:
 "JSON is much more efficient and takes up fewer characters." : JSON syntax is more
concise compared to XML. For example, JSON uses fewer characters for the same data
representation, reducing the amount of data transmitted.
 "Serializing/deserializing JSON is faster than XML because it’s simpler syntax." : JSON’s
simpler syntax means that operations to convert data to and from JSON format are
generally faster than those for XML.
 "JSON is easier to read from a developer’s perspective because it is similar to JavaScript
syntax." : JSON’s syntax closely resembles JavaScript object notation, making it easier for
developers familiar with JavaScript to read and write JSON data.
4. When to Use XML
 XML may be preferred in cases where:
1. Complex Objects: XML can represent more complex structures and metadata that
JSON might not handle as well.
2. Existing Infrastructure: You might continue using XML if your system already
relies on XML-based transformations (e.g., XSLT) or has extensive XML-based
processes in place.
1. JSON to JavaScript Object Conversion:
 A JSON string represents the JavaScript object in string form. The string syntax is similar
to code, making it easy to understand
 the JSON.parse(string) method to convert a string that is properly formatted with JSON
into a JavaScript object.
1. Example of Converting JSON to a JavaScript Object
The example demonstrates how to define accountStr as a JSON string and convert it into a
JavaScript object using JSON.parse(). Once converted, the properties of the object can be
accessed using JavaScript's dot notation.
var accountStr = '{"name":"Jedi", "members":["Yoda","Obi Wan"], "number":34512,
"location": "A galaxy far, far away"}';
var accountObj = JSON.parse(accountStr);
console.log(accountObj.name);
console.log(accountObj.members);
 Step 1: accountStr is a JSON string that represents an object with properties: name,
members, number, and location.
 Step 2: accountObj = JSON.parse(accountStr); converts the JSON string accountStr into a
JavaScript object accountObj.
 Step 3: console.log(accountObj.name); prints the value of the name property of
accountObj, which is "Jedi".
 Step 4: console.log(accountObj.members); prints the members array, which contains
"Yoda" and "Obi Wan".
OUTPUT:
Jedi
[ 'Yoda', 'Obi Wan' ]
 The first console.log(accountObj.name); outputs "Jedi", which is the value associated
with the name property in the object.
 The second console.log(accountObj.members); outputs ['Yoda', 'Obi Wan'], the array
stored in the members property, listing the members as an array of strings.
2. Converting JavaScript Objects to JSON
 Node allows to convert a JavaScript object into a properly formatted JSON string. Thus the
string form can be stored in a file or database, sent across an HTTP connection, or written to
a stream/buffer. Use the JSON.stringify(text) method to parse JSON text and generate a
JavaScript object:
 For example, the following code defines a JavaScript object that includes string, numeric,
and array properties. Using JSON.stringify(), it is all converted to a JSON string:
var accountObj = {
name: "Baggins",
number: 10645,
members: ["Frodo, Bilbo"],
location: "Shire"
};
var accountStr = JSON.stringify(accountObj);
console.log(accountStr);
1. Defining a JavaScript Object:
var accountObj = {
name: "Baggins",
number: 10645,
members: ["Frodo, Bilbo"],
location: "Shire"
};
 accountObj is a JavaScript object.
 It has four properties:
 name: A string value "Baggins".
 number: A numeric value 10645.
 members: An array containing a single string "Frodo, Bilbo".
 location: A string value "Shire".
2. Converting the Object to a JSON String:
var accountStr = JSON.stringify(accountObj);
 JSON.stringify(accountObj) converts the JavaScript object accountObj into a
JSON string.
 The resulting JSON string, stored in accountStr, is a text-based representation of
the object.
3. Logging the JSON String to the Console:
console.log(accountStr);
The console.log() function is used to print the JSON string to the console.
 The preceding code outputs the following:
{"name":"Baggins","number":10645,"members":["Frodo, Bilbo"],"location":"Shire"}

2.6. Using the Buffer Module to Buffer Data

 While JavaScript is Unicode friendly, it is not good at managing binary data. However, binary
data is useful when implementing some web applications and services. For example:
1. Transferring compressed files
2. Generating dynamic images
3. Sending serialized binary data
 Understanding Buffered Data
Buffered data is made up of a series of octets in big endian or little endian format. That means
they take up considerably less space than textual data. Therefore, Node.js provides the Buffer
module that gives the functionality to create, read, write, and manipulate binary data in a
buffer structure. The Buffer module is global, so do not need to use the require() statement to
access it.
Buffered data is stored in a structure similar to that of an array but is stored outside the
normal V8 heap in raw memory allocations. Therefore a Buffer cannot be resized.
When converting buffers to and from strings, need to specify the explicit encoding method to
be used.
Methods of encoding between strings and binary buffers:
METHOD DESCRIPTION
utf8 Multi-byte encoded Unicode characters
used as the standard in most documents
and webpages.
utf16le Little endian encoded Unicode
characters of 2 or 4 bytes.
ucs2 Same as utf16le.
base64 Base64 string encoding.
Hex Encode each byte as two hexadecimal
characters.

Big Endian and Little Endian


Endianess refers to the order in which bytes are stored in computer memory. It determines how a
sequence of bytes representing a multi-byte value (like an integer) is stored and interpreted in
memory.Big Endian vs. Little EndianBig Endian:Definition: In big endian format, the most
significant byte (the "big end") is stored at the smallest memory address. This means the highest
order byte (the one with the largest value) comes first.
Example: For a 4-byte word 0x0A 0x0B 0x0C 0x0D, the bytes would be stored in memory as:
Address | Data
-----------------
0x00 | 0x0A (most significant byte)
0x01 | 0x0B
0x02 | 0x0C
0x03 | 0x0D (least significant byte)
Little Endian:Definition: In little endian format, the least significant byte (the "little end") is stored at
the smallest memory address. This means the lowest order byte (the one with the smallest value)
comes first.
Example: For the same 4-byte word 0x0A 0x0B 0x0C 0x0D, the bytes would be stored in memory as:
Address | Data
-----------------
0x00 | 0x0D (least significant byte)
0x01 | 0x0C
0x02 | 0x0B
0x03 | 0x0A (most significant byte)
1. Creating Buffers
Buffer objects are actually raw memory allocations; therefore, their size must be determined
when they are created.
methods for creating Buffer objects :
new Buffer(sizeInBytes)
new Buffer(octetArray)
new Buffer(string, [encoding])
2. Writing to Buffers
The size of a Buffer object can't be extended after it has been created, but you can write data to
any location in the buffer.
Methods of writing from Buffer objects:
Methods Description
buffer.write(string, [offset], Writes length number of bytes from the string starting at the
[length][encoding]) offset index inside the buffer using encoding.
buffer[offset] = value Replaces the data at index offset with the value specified.
writeInt8(value, offset, Writes the value to every byte in the buffer starting at the
[noAssert]) offset index and ending with the end index.
writeInt8(value, offset, There is a wide range of methods for Buffer objects to write
[noAssert]) integers, unsigned integers, doubles, and floats of various sizes
writeInt16LE(value, offset, using little endian or big endian. value specifies the value to
[noAssert]) writeInt16BE(value, write, offset specifies the index to write to, and noAssert
offset, [noAssert]) specifies whether to skip validation of the value and offset.
noAssert should be left at the default false unless you are
absolutely certain of correctness.

3. Reading from Buffers


There are several methods for reading from buffers. The simplest is to use the toString()
method to convert all or part of a buffer to a string. However, you can also access specific
indexes in the buffer directly or by using read(). Also Node.js provides a StringDecoder object
that has a write(buffer) method that decodes and writes buffered data using the specified
encoding.
Methods of reading from Buffer objects
Methods Description
buffer.toString([encoding], Returns a string containing the decoded characters specified
[start], [end]) by encoding from the start index to the end index of the
buffer. If start or end is not specified, then toString() uses the
beginning or end of the buffer.
stringDecoder.write(buffer) Returns a decoded string version of the buffer.
buffer[offset] Returns the octet value in the buffer at the specified offset.
readInt8(offset, [noAssert]) There is a wide range of methods for Buffer objects to read
readInt16LE(offset, integers, unsigned integers, doubles, and floats of various sizes
[noAssert]) readInt16BE(offset, using little endian or big endian. These functions accept the
[noAssert]) … offset to read from an optional noAssert Boolean value that
specifies whether to skip validation of the offset. noAssert
should be left at the default false unless you are absolutely
certain of correctness.

4. Determining Buffer Length


The length of a buffer can be determined by calling.length on the Buffer object especially
when creating a buffer dynamically from a string. To determine the byte length that a string
takes up in a buffer cannot use the .length property. Instead have to use
Buffer.byteLength(string, [encoding]).
5. Copying Buffers
Node.js provides the copy(targetBuffer, [targetStart],
[sourceStart], [sourceIndex]) method on Buffer objects. The targetBuffer
parameter is another Buffer object, and targetStart, sourceStart, and sourceEnd are
indexes inside the source and target buffers.
Note:
To copy string data from one buffer to the next, make sure that both buffers use the same
encoding or you may get unexpected results when decoding the resulting buffer.
6. Slicing Buffers
Another important aspect of working with buffers is the ability to divide them into slices. A
slice is a section of a buffer between a starting index and an ending index. Slicing a buffer
allows to manipulate a specific chunk.
Slices are created using the slice([start], [end]) method, which returns a Buffer object
that points to start index of the original buffer and has a length of end – start. Keep in
mind that a slice is different from a copy. While Editing a copy, the original does not change.
However, if you edit a slice, the original does change
7. Concatenating Buffers
You can also concatenate two or more Buffer objects together to form a new buffer. The
concat(list, [totalLength]) method accepts an array of Buffer objects as the first parameter,
and totalLength defines the maximum bytes in the buffer as an optional second argument. The
Buffer objects are concatenated in the order they appear in the list, and a new Buffer object is
returned containing the contents of the original buffers up to totalLength bytes.
Wherever totalLength parameter is not provided, concat() figures it out. However, it
has to iterate through the list, so providing a totalLength value is faster.

2.7. Implementing HTTP services in Node.js


 One of the most important aspects of Node.js is the ability to quickly implement HTTP and
HTTPS servers and services. Node.js provides the http and https modules out of the box, and
they provide the basic framework to do most everything need from an HTTP and HTTPS
standpoint. In fact, it is not difficult to implement a full webserver using just the http module
but the http module is pretty low level. It doesn’t provide calls to handle routing, cookies,
caching, and so on.
 The http module is used for implementing backend web services for applications to use. That is
where the http module becomes an invaluable tool.
 The basic HTTP servers provide an interface for communications behind firewall and then
basic HTTP clients that interact with those services.
2.8. Processing URLs
 The Uniform Resource Locator (URL) acts as an address label for the HTTP server to handle
requests from the client. It provides all the information needed to get the request to the correct
server on a specific port and access the proper data.
 The URL can be broken down into several different components, each providing a basic piece
of information for the webserver on how to route and handle the HTTP request from the
client.
Properties of the URL object
1. href - This is the full URL string that was originally parsed.
2. protocol -The request protocol lowercased.
3. host The full host portion of the URL including port information lowercased.
4. auth - The authentication information portion of a URL.
5. hostname The hostname portion of the host lowercased.
6. port The port number portion of the host.
7. pathname - The path portion of the URL including the initial slash if present.
8. search -The query string portion of the URL including the leading question mark.
9. path - The full path including the pathname and search.
10. query - This is either the parameter portion of the query string or a parsed object containing
the query string parameters and values if the parseQueryString is set to true.
11. hash The hash portion of the URL including the pound sign (#).
 Understanding the URL Object
 Node.js provides the url module that provides functionality to convert the URL string into a
URL object to use the URL information more effectively.
 To create a URL object from the URL string, pass the URL string as the first parameter to the
following method:
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
 The url.parse() method takes the URL string as the first parameter. The parseQueryString
parameter is a Boolean that when true also parses the query string portion of the URL into an
object literal. The default is false. The slashesDenoteHost is also a Boolean that when true
parses a URL with the format of //host/path to {host: 'host', pathname: '/path'} instead of
{pathname: '//host/path'}. The default is false
Resolving the URL Components
 The url module resolves URL components in the same manner as a browser would. This
allows you to manipulate the URL strings on the server side to make adjustments in the
URL.
 For example, you might want to change the URL location before processing the request
because a resource has moved or changed parameters.
 To resolve a URL to a new location use the following syntax:
url.resolve(from, to)
 The from parameter specifies the original base URL string. The to parameter specifies the
new location where you want the URL to resolve.
2.9. Processing Query Strings and Form Parameters
 HTTP requests often include query strings in the URL or parameter data in the body for form
submissions. The query string can be obtained from the URL object.
 The query string and form parameters are just basic key-value pairs. convert the string into a
JavaScript object using the parse() method from the querystring module to actually consume
these values in Node.js webserver.
querystring.parse(str, [sep], [eq], [options])
The str parameter is the query or parameter string. The sep parameter allows you to specify
the separator character used. The default separator character is &. The eq parameter allows
you to specify the assignment character to use when parsing. The default is =. The options
parameter is an object with the property maxKeys that allows to limit the number of keys the
resulting object can contain. The default is 1000. If you specify 0, there is no limit.
2.10. Understanding Request, Response, and Server Objects
 The request and response object povide the information and much of the functionality that
comes into and out of the HTTP clients and servers.
1. The http.ClientRequest Object :
The ClientRequest object is created internally when you call http.request() when building
the HTTP client. This object represents the request while it is in progress to the server. You
use the ClientRequest object to initiate, monitor, and handle the response from the server.
The ClientRequest implements a Writable stream, so it provides all the functionality of a
Writable stream object. For example, you can use the write() method to write to it as well
as pipe a Readable stream into it.
To implement a ClientRequest object, you use a call to http.request() using the following
syntax:
http.request(options, callback)
2. The http.ServerResponse Object
The ServerResponse object is created by the HTTP server internally when a request event
is received. It is passed to the request event handler as the second argument. ServerRequest
object is used to formulate and send a response to the client.
3. The http.IncomingMessage Object
The IncomingMessage object is created either by the HTTP server or the HTTP client. On
the server side, the client request is represented by an IncomingMessage object, and on the
client side the server response is represented by an IncomingMessage object. The
IncomingMessage object can be used for both because the functionality is basically the
same.
The IncomingMessage implements a Readable stream, allowing you to read the client
request or server response as a streaming source. This means that the readable and data
events can be listened to and used to read data from the stream.
4. The http.Server Object
The Node.js HTTP Server object provides the fundamental framework to implement HTTP
servers. It provides an underlying socket that listens on a port and handles receiving
requests and then sends responses out to client connections. While the server is listening,
the Node.js application will not end.
To start the HTTP server, first create a Server object using the createServer() method.
which returns the Server object. The optional requestListener parameter is a callback that
is executed when the request event is triggered.
The callback should accept two parameters. The first is an IncomingMessage object
representing the client request, and the second is a ServerResponse object to formulate and
send the response:
http.createServer([requestListener])
After created the Server object, begin listening on it by calling the listen() method on the
Server object:
listen(port, [hostname], [backlog], [callback])

QUESTIONS TO REVIEW:
1. What are module and what are some of the built-in modules provided by Node.js? Provide a brief
description of at least five built-in modules?
1. In Node.js, a module is a reusable piece of code that can be imported into other files in your
application.
2. It helps organize and structure your code into manageable, logical parts.There are two main
types of modules in Node.js:
1. Core Modules : are built into Node.js.
2. Local Modules : These are custom modules we create .
List of built in Modules:
Node.js comes with many built-in modules available right out of the box.
■ Assertion testing: Allows you to test functionality within your code.
■ Buffer: Enables interaction with TCP streams and file system operations.
■ C/C++ add-ons: Allows for C or C++ code to be used just like any other Node.js module.
■ Child processes: Allows you to create child processes.
■ Cluster: Enables the use of multicore systems.
■ Command line options: Gives you Node.js commands to use from a terminal.
■ Console: Gives the user a debugging console.
■ Crypto: Allows for the creation of custom encryption.
■ Debugger: Allows debugging of a Node.js file.
■ DNS: Allows connections to DNS servers.
■ Errors: Allows for the handling of errors.
■ Events: Enables the handling of asynchronous events.
■ File system: Allows for file I/O with both synchronous and asynchronous methods.
■ Globals: Makes frequently used modules available without having to include them first.
■ HTTP: Enables support for many HTTP features.
■ HTTPS: Enables HTTP over the TLS/SSL.
■ Modules: Provides the module loading system for Node.js.
■ Net: Allows the creation of servers and clients.
■ OS: Allows access to the operating system that Node.js is running on.
■ Path: Enables access to file and directory paths.
■ Process: Provides information and allows control over the current Node.js process.
■ Query strings: Allows for parsing and formatting URL queries.
■ Readline: Enables an interface to read from a data stream.
■ REPL: Allows developers to create a command shell.
■ Stream: Provides an API to build objects with the stream interface.
■ String decoder: Provides an API to decode buffer objects into strings.
■ Timers: Allows for scheduling functions to be called in the future.
■ TLS/SSL: Implements TLS and SSL protocols.
■ URL: Enables URL resolution and parsing.
■ Utilities: Provides support for various apps and modules.
■ V8: Exposes APIs for the Node.js version of V8.
■ VM: Allows for a V8 virtual machine to run and compile code.
■ ZLIB: Enables compression using Gzip and Deflate/Inflate.
1. fs (File System) :
Purpose: To work with the file system (e.g., reading, writing, deleting files).
Common Functions:
1. fs.readFile(): Asynchronously reads the contents of a file.
2. fs.writeFile(): Asynchronously writes data to a file.
3. fs.appendFile(): Asynchronously appends data to a file.
4. fs.unlink(): Asynchronously deletes a file.
2. http:
Purpose: To create and manage HTTP servers and handle HTTP requests and responses.
Common Functions:
http.createServer(): Creates an HTTP server.
server.listen(): Binds and listens for connections on a specified port.
3. path:
Purpose: To work with file and directory paths in a cross-platform way.
Common Functions:
path.join(): Joins multiple path segments into a single path.
path.resolve(): Resolves a sequence of paths into an absolute path.
path.basename(): Returns the last portion of a path.
path.extname(): Returns the extension of the path.
4. url:
Purpose: To parse and format URL strings.
Common Functions:
url.parse(): Parses a URL string into its components.
url.format(): Formats a URL object into a URL string.
5. stream:
Purpose: To work with streams, which are data-handling methods that allow for efficient
processing of large amounts of data.
Common Types:
Readable: Streams from which data can be read.
Writable: Streams to which data can be written.
Duplex: Streams that are both readable and writable.
Transform: Streams that can modify or transform the data as it is written and read.
2. Describe the step-by-step process of setting up Node.js on your computer and creating a simple
Node.js application. Include the necessary commands and code snippets for reference.
1. Installing node.js on your computer:
Installing Node.js on your system depends on the operating system you're using. Below are step-by-
step instructions for installing Node.js on different platforms:
1. Windows
Option 1: Using the Node.js Installer
i. Download the Installer: Go to the official Node.js website.
Download the LTS (Long Term Support) version for Windows (recommended for most users).
ii. Run the Installer:
Double-click the downloaded .msi file.
Follow the installation prompts. It's recommended to install the default settings, which include
installing npm (Node Package Manager) alongside Node.js.
iii. Verify the Installation:

 Open Command Prompt.


 Run the following commands to check if Node.js and npm were installed correctly:
node -v
npm -v
2.Creating a simple Node.js application is a great way to get started with server-side JavaScript.
Step 1: Install node js and follow the installation instructions.This should print the version numbers of
Node.js and npm.
Step 2: Set Up the Project:
i. Create a Project Directory:

 Open your terminal or command prompt.


 Create a directory for your project:
mkdir my-node-app
cd my-node-app
ii. Initialize a Node.js Project:
 Run the following command to create a package.json file, which will manage your project
dependencies:
npm init -y
This creates a package.json file with default settings.
Step 3: Create the Application
1. Install Express.js (Optional but common):
 Express.js is a popular framework for building web applications in Node.js.
 Install Express.js:
npm install express
2. Create the Main Application File:
Create a file named app.js in your project directory:
touch app.js
Open app.js in your favorite code editor and add the following code:
const express = require('express');
const app = express();
// Define a route
app.get('/', (req, res) => {
res.send('Hello, World!');
});

// Start the server


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 4: Run the Application:
1.Start the Server:
In your terminal, run the following command to start your Node.js application:
node app.js
You will see a message like Server is running on port 3000.
Access the Application:
Open a web browser and go to http://localhost:3000.You will see the message "Hello, World!"
displayed on the page.
Step 5: Enhance the Application (Optional)Add More Routes:You can add more routes to handle
different endpoints. For example:
app.get('/about', (req, res) => {
res.send('This is the about page');
});
2. Use Middleware:
Express allows you to use middleware functions to handle requests. For example, adding a logger:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
3.Handle JSON Data:
If you want to handle JSON data in your routes:
app.use(express.json());
app.post('/data', (req, res) => {
console.log(req.body);
res.send('Data received');
});
Step 6: Stop the Server
To stop the server, go to your terminal and press Ctrl + C.

You might also like