0% found this document useful (0 votes)
58 views50 pages

U4-01-Node JS

ead

Uploaded by

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

U4-01-Node JS

ead

Uploaded by

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

22ITC08

FULL STACK DEVELOPMENT

UNIT-IV

Node JS
Node JS - https://nodejs.org/en/
Node.js® is an open-source, cross-platform JavaScript runtime environment .
Node JS
 Node.js is an open-source and cross-platform runtime environment
built on Chrome’s V8 JavaScript engine for executing JavaScript code
outside of a browser.
 NodeJS is not a framework and it’s not a programming language.

To check your node version:

$ node --version / $ node -v

To run JS file:

$ node app.js
Node JS Modules
 In NodeJS, Modules are the blocks of encapsulated code that
communicates with an external application on the basis of their related
functionality.

Types of Modules in NodeJS:


1) Core/Built-in Modules
2) Local Modules
3) Third-party Modules
NodeJS Core Modules
 Built-in modules of node.js that are part of NodeJS and come with the
Node.js installation process are known as core modules.
 To load/include this module in our program, we use the require function.
const module = require('module_name')

Node.js = Runtime Environment + JavaScript Library

Node JS Documentation

https://nodejs.org/docs/latest-v17.x/api/
NodeJS Local Modules
 Local modules are created by us locally in our Node.js application.
These modules are included in our program in the same way as we
include the built in module.

Code for creating local modules and exporting:

Code for including local modules:


NodeJS Local Modules

execution.js mathcal.js
NodeJS Third Party Modules
 Modules that are available online and are installed using the npm are
called third party modules.
 Examples of third party modules are express, mongoose, Amazon Alexa
etc.
Export Module in Node.js

 The module.exports is a special object which is included in every

JavaScript file in the Node.js application by default.

 The module is a variable that represents the current module.

 The exports is an object that will be exposed as a module. So, whatever

you assign to module.exports will be exposed as a module.


Export Module in Node.js
Export Literals

As mentioned above, exports is an object. So it exposes whatever you


assigned to it as a module.
Export Module in Node.js
Export Object

The exports is an object. So, you can attach properties or methods to


it.
Export Module in Node.js
Export Object
 Use exports when you want to add properties to the export object.

 Use module.exports when you want to export a single object or function, or if


you need to completely replace the exports object.
Export Module in Node.js
 In the same way as above, you can expose an object with function. The
following example exposes an object with the log function as a
module.
Export Module in Node.js
 You can also attach an object to module.exports, as shown below.
Export Module in Node.js
Export Function

You can attach an anonymous function to exports object as shown below


Export Module in Node.js
Export Function as a Class

In JavaScript, a function can be treated like a class (ES5). The following


example exposes a function that can be used like a class.
Export Module in Node.js
Load Module from the Separate Folder
 Use the full path of a module file where you have exported it using
module.exports.
NPM - Node Package Manager
 NPM is the world's largest Software Registry. The registry contains
over 800,000 code packages.
 Node Package Manager (NPM) is a command line tool that installs,
updates or uninstalls Node.js packages in your application.
 Official website: https://www.npmjs.com

 NPM is included with Node.js installation. After you install Node.js,


verify NPM installation by writing the following command in terminal or
command prompt. C:\> npm –v 10.8.3
NPM - Node Package Manager

 If you have an older version of NPM then you can update it to the

latest version using the following command.

C:\> npm install npm –g

 To access NPM help, write npm help in the command prompt or

terminal window.

C:\> npm help


NPM - Node Package Manager
When we install a package using npm you can perform two types of
installation:
Local Installation
Use the following command to install any third party module in your local
Node.js project folder.
C:\>npm install <package name>
C:\MyNodeProj> npm install express
All the modules installed using NPM are installed
under node_modules folder. C:\MyNodeProj> npm install express --save
NPM - Node Package Manager
Global Installation
 NPM can also install packages globally so that all the node.js
application on that computer can import and use the installed packages.
 Global modules are installed in the standard system in root location in
system directory /usr/local/lib/node_modules project directory.
 To Print location on your system where all the global modules are
installed.
$ npm root –g
C:\Users\Admin\AppData\Roaming\npm\node_modules
Node JS
To List all the Global Packages in the system:

$ npm list -g

Update Package

C:\MyNodeProj> npm update <package name>

Uninstall Packages

C:\>npm uninstall <package name>


NodeJS Web Server
 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.
 IIS is a web server for ASP.NET web applications and Apache is a
web server for PHP or Java web applications.
 Node.js provides capabilities to create your own web server which
will handle HTTP requests asynchronously. You can use IIS or Apache to
run Node.js web application but it is recommended to use Node.js web
server.
NodeJS Web Server

 HTTP stands for Hyper Text Transfer Protocol

 require

We use the require directive to load Node JS modules.

 Create Server

The HTTP module use the createServer() method to create an HTTP

server.
NodeJS Web Server
HTTP Header If the response from the HTTP server is supposed to be
displayed as HTML, you should include an HTTP header with the correct
content type.
The first argument of the res.writeHead() method is the status
code, 200 means that all is OK, the second argument is an object
containing the response headers.
Port Number
HTTP server that listens to server ports and gives a response back
to the client.
NodeJS Web Server
NodeJS Web Server-Handle HTTP Request
NodeJS Web Server
NodeJS File System - fs
 Node.js includes fs module to access physical file system. The fs module is responsible for
all the asynchronous or synchronous file I/O operations.
 To include the File System module, use the require() method:

var fs = require('fs');
 Common use for the File System module:

1. Read files

2. Create files

3. Update files

4. Delete files

5. Rename files
NodeJS File System - Synchronous

 All the fs operations can be performed in a synchronous as well as in an

asynchronous approach depending on the user requirements.

 Synchronous methods: Synchronous functions block the execution of

the program until the file operation is performed. These functions are

also called blocking functions.

fs.readFileSync()
NodeJS File System - Asynchronous

 Asynchronous functions do not block the execution of the program

and each command is executed after the previous command even if the

previous command has not computed the result.

 The previous command runs in the background and loads the result once

it has finished processing.

fs.readFile(fileName [,options], callback)


Synchronous Vs. Asynchronous
NodeJS File System - fs
 Use fs.readFile() method to read the physical file asynchronously.

fs.readFile(fileName [,options], callback)

Parameter Description:

 filename: Full path and name of the file as a string.

 options: The options parameter can be an object or string which can include

encoding and flag. The default encoding is utf8 and default flag is "r".

 callback: A function with two parameters err and data. This will get called when

readFile operation completes.


NodeJS File System - fs
CBIT.html

index.js
NodeJS File System - fs
 Use fs.writeFile() method to write data to a file. If file already exists then it overwrites the
existing content otherwise it creates a new file and writes data into it.

fs.writeFile(filename, data[, options], callback)

Parameter Description:

 filename: Full path and name of the file as a string.

 Data: The content to be written in a file.

 options: The options parameter can be an object or string which can include encoding,
mode and flag. The default encoding is utf8 and default flag is "r".

 callback: A function with two parameters err and data. This will get called when write
operation completes.
NodeJS File System - fs
NodeJS File System - fs
 The fs.appendFile() method is used to synchronously append the data to the file.

fs.appendFile(filepath, data, options, callback);

fs.appendFileSync(filepath, data, options);

Parameters:

 filepath: It is a String that specifies the file path.

 data: It is mandatory and it contains the data that you append to the file.

 options: It is an optional parameter that specifies the encoding/mode/flag.

 Callback: Function is mandatory and is called when appending data to file is completed.
NodeJS File System - fs
NodeJS File System - fs
 The fs.open() method is used to create, read, or write a file.

fs.open(path, flags, mode, callback)

Parameters:

path: It holds the name of the file to read or the entire path if stored at other
locations.

flags: Flags indicate the behavior of the file to be opened.

mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite (Default).
NodeJS File System - fs
NodeJS File System - fs
Flag Description
r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs'
about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like 'w' but fails if path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it
exists).
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if path exists.
NodeJS File System - fs

 Delete a File: The fs.unlink() method is used to remove a file or

symbolic link from the file system.

 This function does not work on directories, therefore it is recommended

to use fs.rmdir() to remove a directory.

fs.unlink(path, callback);
NodeJS File System - fs
NodeJS Event Emitter class
 Every action on a computer is an event. Like when a connection is
made or a file is opened.
 Node.js 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.
const EventEmitter = require('events');

eventEmitter.addListener(event, listener)

eventEmitter.on(event, listener)
NodeJS Event Emitter class
NodeJS Event Emitter class
NodeJS Event Emitter class
NodeJS Event Emitter class
Common Patterns for EventEmitters
There are two common patterns that can be used to raise and bind an event using
EventEmitter class in Node.js.
Return EventEmitter from a function
In this pattern, function returns an EventEmitter object, which was used to emit
events inside a function. This EventEmitter object can be used to subscribe for the
events.
Extend the EventEmitter class
In this pattern, we can extend the constructor function from EventEmitter class to
emit the events.
EventEmitter class using util.inherits() method of utility module.
NodeJS Returning Event Emitter.
NodeJS Inheriting Events

You might also like