0% found this document useful (0 votes)
25 views

Node Js

Node.js is a free, open-source, cross-platform JavaScript runtime environment that allows developers to create servers and web applications. It is built on Chrome's V8 engine, supports asynchronous programming with non-blocking I/O, and has a rich ecosystem of modules available through npm. The document also covers installation, key features, core modules, data types, and various functionalities like file system operations and event handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Node Js

Node.js is a free, open-source, cross-platform JavaScript runtime environment that allows developers to create servers and web applications. It is built on Chrome's V8 engine, supports asynchronous programming with non-blocking I/O, and has a rich ecosystem of modules available through npm. The document also covers installation, key features, core modules, data types, and various functionalities like file system operations and event handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Node.

js
Node.js® is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.

Node.js is an
1 open source 2
Node.js is free
server
environment

Node.js runs on Node.js uses


various platforms JavaScript on
4 3
(Windows, Linux, the server
Unix, Mac OS X,
etc.)
What is NodeJS
• JavaScript Runtime: Node.js is an open-source, cross-platform
runtime environment for executing JavaScript code outside of a
browser.
• NodeJS: is a JS in a different environment means Running JS on the
Server or any computer.
• Built on Chrome’s V8 Engine: It runs on the V8 engine, which
compiles JS directly to native machine code, enhancing performance.
• V8 is written in C++ for speed.
• V8 + Backend Features = NodeJS
Installation of Node JS on Windows
Downloading the Node.js ‘.msi’ installer the first step
Step 1: Download the NodeJS to install Node.js on Windows is to download the
installer. Visit the official Node.js website i.e)
https://nodejs.org/en/download/

Step 1: Download the NodeJS


Installation of Node JS on Windows
Step 2: Download the
NodeJS
Key features of Node.js

• Non-blocking I/O: Node.js is asynchronous, enabling efficient handling of

concurrent requests.

• Event-driven architecture: Developers can create event-driven applications

using callbacks and event emitters.

• Extensive module ecosystem: npm (Node Package Manager) provides access

to thousands of reusable packages.


Core Modules

Node.js includes several core modules for essential functionality. Some commonly used ones ar

• fs (File System): Read/write files and directories.

• http: Create HTTP servers and clients.

• path: Manipulate file paths.

• events: Implement custom event handling.


Data type in
Node.js
Datatypes in Node.js Loose Typing: Node.js supports loose
Node.js contains various types of data types
typing, which means you don’t need
similar to JavaScript.
to specify what type of information
•Boolean
will be stored in a variable in
•Undefined
advance. We use the var and let
•Null
keywords in Node.js declare any type
•String

•Number of variable. Examples are given

below:
Example Loose
Type
// Variable store number data type
let a = 35;
console.log(typeof a);
Output
// Variable store string data type number
a = “United College";
string
console.log(typeof a);
boolean
// Variable store Boolean data type
a = true; undefined
console.log(typeof a);
// Variable store undefined (no value) data type
a = undefined;
console.log(typeof a);
Object and
Function
Node.js objects are the same as let company = {
Name: “United College”,
JavaScript objects i.e. the objects
Address: “Prayagraj”,
are similar to variables and it Contact: "+9335833415",

contains many values which are Email: “[email protected]


};
written as name: value pairs.
// Display the object information
Name and value are separated by console.log("Information of variable company:",
company); // Display the type of variable
a colon and every pair is
console.log("Type of variable company:", typeof
separated by a comma. company);
How to run first program in Node.js

Step Step
 1
Create a Folder
Such as WT
2 file java
Create
script file such as 
Index.js
index.js


Step Step

D:\WT>

3
Go to Command 4
D:\WT>node
Prompt index.js
Application
Of Node.Js

Console Web Base


Base Node Node
Application Application
User input in run time
REPL
The full form of REPL is “Read Eval Print Loop”. It is an interactive console (similar
to the windows command prompt) for node.js where we can write node.js commands
and the system will provide its corresponding output.
In this REPL terminal of Nodejs, you can perform various mathematical operations.
The repl terminal is also known as a node shell.
Nodejs REPL Environment:
The Repl terminal comes automatically with the node.js installation. So if you have
installed node.js then you can use this terminal.
The four parts of Repl are as follows:
1) Read: It takes the user input, parses it into javascript, and then stores it in
memory.
2) Eval: It evaluates the parsed javascript.
3) Print: The result of the evaluation is shown as an output.
4) Loop: It again starts reading. To break out of this loop you have to press ctrl+c
Starting REPL Terminal:
• Open a terminal or command prompt.
• Type Node
• Press enter

To quit from the prompt, press ctrl+c twice.


Examples of REPL:
1. Mathematical operation:
You can see that the repl terminal is able to solve simple
mathematics.
2. Using libraries:
We can also use the node modules in the repl terminal. In the
below image you can see that we have used the Math module of
node to perform some mathematical operations.
3. Variables:
We can store the values in a variable to use it again.
There are two ways to store variables
1) directly assigning to a variable Eg: a=20.Or
2) Var a=20.
4. MultiLine expressions and Loops:
We can write multiline code in the repl terminal and then execute it in the repl
terminal.
All the loops that are present in javascript can also be used in the repl
terminal.
5. The Underscore Variable:
This variable holds the value of the last performed operation.
Stopping/Exiting the REPL terminal:
To quit the terminal press ctrl+c twice
REPL Commands:
Below is a list of most popular commands for repl terminal
1) Using ctrl+c once: It terminates the current command.
2) Using ctrl+c twice: It quits the repl terminal.
3) Using ctrl+d: It quits the repl terminal.
4) up/down key: Shows previously used commands.
5) Tab key: View current commands
6) .help: Gives a list of all commands that it supports
7) .clear: To exit from the multiline expression.
8) .break: For exiting from multiline command
9) .save “filename”: To save the current repl as a file.
10) .load “filename”: Load a file into repl terminal
Node.js File System Module
• The Node.js file system module allows you to work with the file
system on your computer.
• To include the File System module, use the require() method:
• var fs = require('fs');
• Common use for the File System module:
• Read files
• Create files
• Update files
• Delete files
• Rename files
In Node.js, callbacks are a fundamental
part of handling asynchronous
operations, including when using the
Node Package Manager (NPM) or
working with packages that involve
asynchronous behavior.
What are Callbacks?
A callback is a function passed as an argument to
another function, which is then invoked after the
completion of a task. This allows Node.js to perform
non-blocking I/O operations.
How Callbacks Work in NPM
When you install packages or use certain functions from those packages, you often encounter
asynchronous operations. Here’s how callbacks typically come into play:
1.Installation of Packages: When you use commands like npm install, the package manager
runs various scripts that may use callbacks internally to handle tasks like downloading,
extracting, and installing the packages.
2.Using Packages: Many Node.js packages use callbacks to handle results from asynchronous
operations. For example, when reading a file using the fs module:
Node JS fs.readFile() Method
• In Node, the fs (File System) module provides a collection of methods
for interacting with the file system. Among these
methods, fs.readFile() stands out as a fundamental tool for reading data
from files asynchronously. This article will delve into the fs.readFile()
method, exploring its syntax, parameters, usage, and error handling.
• NodeJS readfile method
• The readfile method is used to asynchronously read the data from a file.
It is a method of node js file system module. Asynchronously reading file
content enables the non-blocking operation in Node.
• Syntax:
• fs.readFile( file_path, encoding, callback_function )
• Parameters:
• The method accepts three parameters as mentioned above and
described below:
• file_path: It holds the file’s name to read or the entire path if stored
at another location.
• encoding: It holds the encoding of the file. Its default value is ‘utf8’.
• callback_function: A callback function is called after reading the file.
It takes two parameters:
• err: If any error occurred.
• data: Contents of the file.
const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {


if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});

In this example:
• fs.readFile is asynchronous.
• The last parameter is a callback function that will
be called once the file read operation completes.
Node fs.mkdir() Method
• The fs.mkdir() method in Node.js is used to create a directory
asynchronously.
• Syntax
• fs.mkdir(path, mode, callback)
• Parameters: This method accepts three parameters as mentioned above
and described below:
• path: This parameter holds the path of the directory that has to be created.
• mode: This parameter holds the recursive boolean value. The mode option
is used to set the directory permission, by default it is 0777.
• callback: This parameter holds the callback function that contains an error.
The recursive option if set to true will not give an error message if the
directory to be created already exists.
Node.js fs.rmdir() Method

• The fs.rmdir() method is used to delete a directory at the given path.


It can also be used recursively to remove nested directories.
• Syntax:
• fs.rmdir( path, options, callback )
Node.js HTTP Module

• Node.js has a built-in module called HTTP, which allows Node.js to


transfer data over the Hyper Text Transfer Protocol (HTTP).
• To include the HTTP module, use the require() method:
• var http = require('http');
Node.js as a Web Server
• 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:
• var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

The function passed into the http.createServer() method, will be executed


when someone tries to access the computer on port 8080.
Node.js OS

• The os module in Node.js provides operating system-related utility


methods and properties. It helps retrieve system information such as
CPU details, memory usage, and network interfaces, enabling you to
write system-aware applications.
• It provides functions to interact with the operating system. It provides
the hostname of the operating system and returns the amount of free
system memory in bytes.
• os.arch(): Returns the CPU architecture of the operating system (e.g., ‘x64’,
‘arm’).
• os.cpus(): Provides an array of objects describing each CPU/core installed.
• os.freemem(): Returns the amount of free system memory in bytes.
• os.homedir(): Returns the path to the current user’s home directory.
• os.hostname(): Returns the hostname of the operating system.
• os.networkInterfaces(): Returns a list of network interfaces and their
details.
• os.platform(): Returns the operating system platform (e.g., ‘linux’,
‘darwin’).
• os.release(): Returns the operating system release.
• os.totalmem(): Returns the total amount of system memory in bytes.
• os.uptime(): Returns the system uptime in seconds.
Node.js path.basename()
Method
• The path.basename() method is used to get the filename portion of a path
to the file. The trailing directory separators are ignored when using this
method.
• Syntax:
• path.basename( path, extension )
• Parameters: This method accepts two parameters as mentioned above and
described below:
• path: It is the file path that would be used to extract the filename.
• extension: It is an optional file extension that would be removed from the
returned string.
• Return Value: It returns a string with the filename portion of the path. It
throws an error if the path or the extension parameters are not string values.
Node.js path.dirname() Method

• The path.dirname() method is used to get the directory name of the given
path. It ignores the respective platform’s trailing directory separators.
• Syntax:
• path.dirname( path )
• Parameters: This function accepts one parameter as mentioned above and
described below:
• path: It is the file path that would be used to extract the directory name. It
throws a TypeError if this parameter is not a string value.
• Return Value: It returns a string with the directory of the path.
• Below programs illustrate the path.dirname() method in Node.js:
Node.js path.extname() Method

• The path.extname() method is used to get the extension portion of a


file path. The extension string returned from the last occurrence of a
period (.) in the path to the end of the path string. If there are no
periods in the file path, then an empty string is returned.
• Syntax:
• path.extname( path )
• Parameters: This method accepts single parameter path which holds
the file path that would be used to extract the extension.
• Return Value: It returns a string with the extension portion of the
path. It throws a TypeError if this parameter is not a string value.
Node.js path.parse() Method
• The path.parse() method is used to return an object whose
properties represent the given path. This method returns the
following properties:
• root (root name)
• dir (directory name)
• base (filename with extension)
• ext (only extension)
• name (only filename)
• The values of these properties may be different for every platform. It
ignores the platform’s trailing directory separators during parsing.
Events
Node.js Events

• Every action on a computer is an event. Like when a connection is


made or a file is opened.
• Node.js 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 events.EventEmitter();
In Node.js, "events" typically refers to "EventEmitter" events, which are a fundamental part of
the event-driven architecture in Node.js. The EventEmitter class allows you to create and
handle events, enabling you to build asynchronous applications easily.
Key Concepts:
1.EventEmitter Class:
•It's part of the events module.
•You can create an instance of EventEmitter and use it to emit events and listen for them.
2.Emitting Events:
•You can trigger an event using the .emit() method.
3.Listening to Events:
•Use the .on() method to register a callback function that gets called whenever the event is
emitted.
How to Use
Const EventEmitter=require(“events”)
const EventEmitter = require('events');
Or
// Create an instance of EventEmitter
Import EventEmitter from ‘events’ //es6
const myEmitter = new EventEmitter();
// Register a listener for the 'event' event
myEmitter.on('event', () => {
console.log('An event occurred!');
});
// Emit the 'event' event
myEmitter.emit('event');
Express Js Freamwork
Express.js is a minimal and flexible web application

framework for Node.js that provides a robust set of

features for building web and mobile applications.


Web Application

Creating Web-based Node Application

A web-based Node application consists of the following three important

components:

• Import required module

• Create server

• Read Request and return response


1. Core Features
• Routing: Express allows you to define routes to handle different HTTP
methods and URLs. You can create modular routes, making it easy to
manage and organize your application.
• Middleware: Middleware functions can process requests, modify the
request and response objects, end requests, and call the next middleware
function in the stack. This provides great flexibility in how you handle
requests.
• Static Files: You can easily serve static files, such as images, CSS, and
JavaScript, using the built-in middleware.
2. Setting Up an Express Application

Install Express:

npm install express

Create an Application:
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {


res.send('Hello, World!');
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
3. Middleware Usage
4. Error Handling
You can use middleware for various purposes,
such as logging, authentication, or parsing Express has a built-in error handling
mechanism. You can define custom error-
request bodies. For example, to use the
handling middleware
body-parser middleware:

app.use((err, req, res, next) => {


const bodyParser = require('body-parser');
console.error(err.stack);
app.use(bodyParser.json());
res.status(500).send('Something broke!');
app.use(bodyParser.urlencoded({ extended: true }));
});
5. Connecting to Databases
Express can easily integrate with databases such as MongoDB, PostgreSQL, or MySQL. Using an
ORM like Mongoose or Sequelize simplifies database interactions.

6. Best Practices
• Organize Your Code: Structure your app using separate files for routes, controllers, and
middleware to maintain readability.
• Use Environment Variables: Manage configuration settings using environment variables with
libraries like dotenv.
• Error Handling: Implement comprehensive error handling to improve user experience and
facilitate debugging.
Restful API
REpresentational State Transfer (REST) is an architectural style that defines a set of
constraints to be used for creating web services. REST API is a way of accessing web services
in a simple and flexible way without having any processing.

REST technology is generally preferred to the more robust Simple Object Access Protocol
(SOAP) technology because REST uses less bandwidth, simple and flexible making it more
suitable for internet usage. It’s used to fetch or give some information from a web service.
All communication done via REST API uses only HTTP request.
Key Principles of REST
4.Use of Standard HTTP Methods:
1.Statelessness: •GET: Retrieve resource(s).
•Each request from a client to the server must contain
•POST: Create a new resource.
all the information needed to understand and process •PUT: Update an existing resource.
the request. The server does not store client context. •DELETE: Remove a resource.
2.Client-Server Architecture:
5.Representations:
•The client and server are separate, allowing for
•Resources can have multiple
independent development and scaling. Clients
representations (e.g., JSON, XML).
interact with the API without knowing the server's
JSON is commonly used in RESTful
internal workings.
APIs for data interchange.
3.Resource Identification:
6.Stateless Communication:
•Resources (data entities) are identified by URIs
•Each request is independent, with no
(Uniform Resource Identifiers). For example, /users
session state stored on the server.
might represent a collection of user resources.

You might also like