Node JS

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 16

Client-side scripting:-

1]Client-side refers to scripting languages executed on the client's web browser.


2]These scripts are typically written in languages like JavaScript,and they are
responsible for interactions directly within the browser environment.
3]Client-side scripting is commonly used for tasks such as validating form
input,creating dynamic web page content,and handling user interactions without
needing to communicate with the server.

Server-side scripting:-
1]Server-side scripting runs on the web server.
2]server-side scripting involves writing JavaScript code that runs on the server to
handle tasks such as processing form submissions,interacting with databases,and
generating dynamic web page content.

Angular JS:-
1]AngularJs is a JavaScript framework used for building client-side web
applications.
2]It provides features to create dynamic single-page applications(SPAs) that run in
the user's browser.
3]AngularJS helps to manage the structure of the application,handle user
interactions,and update the view in real-time without needing to reload the entire
page.
4]It was developed by google.
5]It is an open-source platform,where everyone can use and share it.

Node Js:-
1]Node js is a runtime environment that allows developers to execute JavaScript
code on the server-side.
2]Node js is commonly used for building web servers,APIs (Application Programming
Interfaces).
3]It enables developers to use JavaScript both on the client-side and server-
side,facilitating full-stack development.
4]It is open-source and cross-platform,running on various operating systems such as
Windows,macOS,and Linux.
5]Node js is efficient because it handles many connections at once without
waiting,using a model based on events and non-blocking input/output.

Javascript:-
1]Javascript is a programming language.
2]It is primarily used for creating dynamic and interactive content on websites.
3]It allows for handling user interactions such as clicks,input,and form
submissions.
4]JavaScript can manipulate the content of web pages in real-time without needing
to reload the entire page.
5]It is commonly used for tasks like animations,form validation,and fetching data
from servers.
6]JavaScript is executed by web browsers,making it client-side scripting language.

Frontend Development:-
1]Fontend Development Refers to the part of a web application or website that users
interact with directly in their web browsers.
2]Frontend development involves creating the user interface,designing
layouts,implementing client-side functionalities,and handling user interactions
using HTML,CSS,JS.
3]Frontend development focuses on improving user experience by designing user-
friendly layouts for websites.

Backend Development:-
1]Backend Development refers to the server-side of a web application where data
processing and storage occur.
2]Backend development involves creating the server,managing data,processing
requests from the client-side,and sending dynamic content to users browser.
3]Developers use server-side programming languages like Node.js, Python, Ruby, or
Java for backend development.
4]Backend developers work with databases like MySQL,MongoDB,PostgreSQL to store and
retrieve data efficiently.

Features of Node Js:-


1]Node js is a runtime environment that allows developers to execute JavaScript
code on the server-side.
2]Node js is commonly used for building web servers,APIs (Application Programming
Interfaces).
3]It enables developers to use JavaScript both on the client-side and server-
side,facilitating full-stack development.
4]It is open-source and cross-platform,running on various operating systems such as
Windows,macOS,and Linux.
5]Node js is efficient because it handles many connections at once without
waiting,using a model based on events and non-blocking input/output.

Applications of Node Js:-


1]Web Servers:
Node js is commonly used to create fast and scalable web servers.Its non-
blocking,event-driven architecture makes it well-suited for handling concurrent
connections efficiently.

2]API Development:
Node js is often used to build APIs (Application Programming Interfaces) due to its
ability to handle I/O operations asynchronously,making it efficient for serving
data to clients.

3]Real-time Applications:
Node js is for building real-time applications such as chat applications and online
gaming platforms due to its event-driven architecture which allows for handling
multiple connections simultaneously.

4]Command Line Tools:


Node js can be used to build command-line tools for automating tasks,processing
files,and managing dependencies,using its large collection of helpful packages from
npm.

Advantages of Node Js:-


1]Node js is a runtime environment that allows developers to execute JavaScript
code on the server-side.
2]Node js is commonly used for building web servers,APIs (Application Programming
Interfaces).
3]It enables developers to use JavaScript both on the client-side and server-
side,facilitating full-stack development.
4]It is open-source and cross-platform,running on various operating systems such as
Windows,macOS,and Linux.
5]Node js is efficient because it handles many connections at once without
waiting,using a model based on events and non-blocking input/output.

Traditional Web-Server Model:-


1]The traditional web server model in Node js involves handling each incoming
request in a sequential manner,where one request is processed at a time.
2]This model is synchronous,means while one request is being processed,the server
waits for it to complete before moving on to the next request.

Node Js Process Model:-

1]Node js process model operates on an event-driven architecture,where actions are


triggered by events rather than executing code in a linear sequence.
2]It runs in a single-threaded event loop,handling all incoming requests and events
on a single thread.
3]It uses non-blocking I/O operations,allowing it to execute other tasks while
waiting for I/O operations to complete.
4]It also uses asynchronous callbacks for I/O operations,ensuring that the program
does not wait for tasks to finish before moving on to the next one.
5]The event loop Node js process model,continuously checking for events and
executing corresponding callback functions.
6]Node js uses the libev library for its event loop,libev is a multi-platform
support library which focuses on asynchronous I/O.

Blocking Approach:-
1]In Blocking Approach,Tasks are executed sequentially.
2]In the blocking approach,tasks are completed one after the other,and each task
must finish before the next one can start.
3]Subsequent tasks wait for the current task to finish.
4]Blocking operations stop the program until they are done.
5]This can cause delays and make the program less efficient.
6]Examples are tasks like reading files synchronously or waiting for network
responses.

Non-Blocking Approach:-
1]In Non-Blocking Approcal,Tasks begin without needing to wait for others to
complete.
2]That Means Tasks are handled asynchronously.
3]It uses event loop to manage the task execution.
4]It provide Callback functions to handle tasks result or errors.
5]It Suitable for applications with high concurrency or I/O operations.

REPL:-

1]REPL stands for Read,Eval,Print,Loop it represents a runtime computing


environment.
2]Read :- REPL takes JavaScript code from the user through the terminal or command
prompt.
3]Eval :- It evaluates the input code as JavaScript,executing it within the Node
js environment.
4]Print :- After execution,REPL displays the result or output in the terminal for
the user to view.
5]Loop :- This process iterates continuously,enabling users to enter new
input,execute it,and view the results.

REPL Commands:-

1].help :- List of all commands.


2].break :- Exits from a multi-line expression.
3].clear :- Resets the REPL's context,clearing all defined variables and functions.
4].save filename :- Saves the current REPL session to a file.
5].load filename :- load a file content in the current REPL session.
6]ctrl + c :- Terminate the current command.
7]ctrl + c twice :- Terminate the Node REPL.
8]ctrl + d :- Terminate the Node REPL.
9]up/down keys :- see command history and modify previous commands.
10]tab keys :- List of current commands.

Variable :-
1]Variables in Node.js are containers used to store data values.
2]It can hold different types of data such as numbers,strings,objects,or functions.
3]To store the value we use "var" keyword.
4]Variables provide a way to manipulate and work with data within a
program,allowing developers to store and retrieve information as needed during
execution.

Underscore variable(_):-
1]It often used as a convention to represent the result of the last evaluated
expression in the REPL(Read-Eval-Print Loop)environment.
2]For Example:-

> 10 + 5
15
> _
15

Multi-line expression:-
1]A multiline expression refers to a block of code or input that spans multiple
lines.
2]For Example:-

> let sum = 0;


... for (let i=1;i<=10; i++)
... {
... sum=sum+i;
... }
... sum;

Web Server:-
1]A web server is a software application that interacts with web browsers by
processing HTTP requests and providing web content such as HTML pages,images,and
scripts,in response to those requests.
2]Web servers listen for incoming HTTP requests on a specific port,process these
requests,and generate appropriate responses based on the requested resources.
3]They communicate with clients using the Hypertext Transfer
Protocol(HTTP),facilitating the exchange of data between the server and the client
over the internet.
4]They implement various security measures such as authentication,encryption like
HTTPS,and access control to protect sensitive data and prevent unauthorized access
to resources.

Write steps to install node js through dashboard

1]Download Installer:-
Go to the official Node.js website: nodejs.org.
Click on the "Downloads" button.
Download the Windows Installer (.msi) for the LTS version (recommended for most
users).
2]Run Installer:-
Once the download is complete,locate the downloaded .msi file in your Downloads
folder.
Double-click on the installer file to run it.

3]Setup Wizard:-
The Node.js setup wizard will open.
Click "Next" to begin the installation process.

4]Agree to License Terms:-


Read and accept the license agreement.
Click "Next" to continue.

5]Choose Installation Location:-


Choose the destination folder where you want to install Node.js.
By default,it's recommended to keep the default location.
Click "Next" to proceed.

6]Select Components:-
Optionally,choose additional components you want to install(e.g., npm package
manager).
It's recommended to keep the default options selected.
Click "Next" to continue.

7]Start Installation:-
Click "Install" to begin the installation process.
The installer will now extract and install Node.js and its components on your
system.

8]Completing the Setup:-


Once the installation is complete, click "Finish" to exit the setup wizard.

9]Verification:-
To verify that Node.js and npm (Node Package Manager) are installed correctly,open
a command prompt or PowerShell window.
Type node -v and press Enter.This will display the installed version of Node.js.
Similarly, type npm -v and press Enter. This will display the installed version of
npm.

10]Complete installation:-
Node js is now installed on your Windows system, and you can start using it to
develop JavaScript applications.

Function:-
1]Function is a block of statements,which is used to perform specfic tasks.
2]Functions allows to break down a complex program into a smaller,more manageable
parts.
3]Functions can be reused multiple times within a program.

Defining Function:-
1]To define a function in Node.js:
Use the function keyword followed by the name of the function.
If the function takes parameters, list them inside parentheses.
Write the code block inside curly braces {} to specify what the function should do.
Optionally, use the return statement to specify the value the function should
return.
2]For Example:-

function add(a,b)
{
return a + b;
}
let sum = add(3, 5);
console.log(sum);

Function Expression(Anonymous Function):-


1]They involve defining a function by assigning it to a variable.
2]Function expressions do not require a function name and can be anonymous.
3]They are commonly used for creating functions dynamically or as callback
functions.
4]For Example:-

const f1=function(name)
{
return `Hello,${name}!`;
};

console.log(f1("Sujal Vora"));

Function Scope:-

Local Scope(variable):-
1]Variables declared inside the function cannot be accessed outside the function.
2]They are only visible and accessible within that function
3]Once the function is exited,the local variable is no longer available.
4]For Example:-

function f()
{
let n=20;
console.log(n);
}

f();

Global Scope(variable):-
1]Variables are declared outside of any function have global scope.
2]They are accessible throughout the entire program,including all functions.
3]For Example:-

let n=10;
function f()
{
console.log(n)
}

f();

Default Argument:-
1]Default Arguments allows you to provide default values for function parameters.
2]if a caller does not specify a value for a parameter,the default value is used.
3]For Example:-

function greet(name="World!")
{
console.log(`Hello,${name}!`);
}
greet();
greet("Sujal");

Buffer:-
1]A Buffer in Nodejs is a global object that allows you to work with binary data
directly.
2]Buffers provide a simple way to work with binary data,treating it like an array
of bytes.
3]Buffers are commonly utilized for tasks like file operations, network
communication,and data encoding/decoding.

How To Create Buffer:-

1]Buffer.from():-
[1]Creates a buffer from a string or an array of bytes.
[2]syntax:-
Buffer.from(object,encoding);

2]Buffer.alloc():-
[1]Creates a buffer with a specific size,optionally filled with a specified value.
[2]syntax:-
Buffer.alloc(size,fill,encoding);

3]Buffer.allocUnsafe():-
[1]Creates a buffer with a specific size without initializing the buffer's
contents.
[2]syntax:-
Buffer.allocUnsafe(size);

Writing To Buffers:-
1]Writing data to buffers in Node js involves using the write() method provided by
the Buffer class.
2]syntax:-
BufferName.write(string,offset,length,encoding);
3]For Example:-
const b=Buffer.alloc(10);
b.write('Hello World!','utf-8');
console.log(b.toString());

Reading From Buffers:-


1]Reading from buffers in Node js involves accessing the data stored in the buffer
and converting it to a usable format,such as a string or numerical value
2]syntax:-
BufferName.toString(encoding,start,end);
3]For Example:-
const b=Buffer.from('Hello,world!','utf-8');
const str=b.toString('utf-8',0,5);
console.log(str);

Concatenate Buffers:-
1]You can concatenate buffers using the Buffer.concat() method.
2]syntax:-
Buffer.concat(list,length);
3]For Example:-
const buf1=Buffer.from('Hello');
const buf2=Buffer.from('world!');
const concat1=Buffer.concat([buf1,buf2]);
const result=concat1.toString();
console.log(result);

Compare Buffers:-
1]You can compare buffers using the Buffer.compare() method.
2]syntax:-
Buffer.compare(buffer1,buffer2);
3]For Example:-
const buf1=Buffer.from('ABC');
const buf2=Buffer.from('ABCD');
const result=buf1.compare(buf2);
console.log(result);

Module:-
1]A module is a self-contained unit of code that groups together related functions
and data.
2]It promotes code organization by allowing developers to divide their code into
smaller manageable parts.
3]Modules can be either core modules,local modules or third-party modules.

[1]Core Modules:-
1]Core modules are pre-built modules that are part of the Node.js runtime
environment.
2]They provide essential functionality to Node.js applications without requiring
installation or additional setup.
3]Examples of core modules include fs for file system operations and http for
creating web servers.
4]They can be accessed using require() without specifying the path, as Node.js
knows where to find them automatically.
5]Here are some of few core modules are shown below:-
1)fs(File System):
The fs module provides functions for interacting with the file
system,allowing you to read from and write to files,create directories,and perform
other file-related operations.
2)http(HTTP):
The http module enables you to create HTTP servers and make HTTP requests.It
provides classes and methods for handling HTTP requests,responses,and server
configuration.
3)path:
The path module provides utilities for working with file and directory paths.
It offers functions for manipulating file paths,such as joining paths,resolving
relative paths,and extracting directory names and file extensions.

[2]Local Modules:-
1]Local modules encapsulate custom functionality specific to a Node js project or
application.
2]Local modules are usually created in their own files within the project
folder,helping to organize code into smaller,manageable parts.
3]Local modules export functionality using the module.exports or exports object,and
other parts of the project import them using require().
4]They facilitate code reusability by allowing developers to encapsulate and reuse
functionality across different parts of the project.

[3]Third-Party Module:-
1]These are modules developed by external parties or communities,not part of Node
js core or the local project.
2]They provide additional functionality beyond what is available in core modules or
local modules.
3]Third-party modules are typically published on package registries like npm (Node
Package Manager) for easy installation and usage.

module.exports:-
1]It is like a package you are sending out from your module.
2]Whatever you assign to module.exports becomes available to other modules that
require or import your module.
3]It is how you share functions,variables,or objects from your module with other
parts of your code.

NPM:-
1]NPM Stands for Node Package Manager.
2]It Manages and shares JavaScript code libraries.
3]It Helps developers easy to install,share,and manage dependencies for their Node
js projects or applications.
4]All npm are defined in files called package.json.
5]It was developed by Issac z. Schlueter in 2010.
6]It consists three different components:-
[1]Registry:The central database storing JavaScript packages.
[2]Command-Line Interface (CLI):The tool developers use to interact with NPM in
their terminal.
[3]Website: The online platform where developers can explore and discover
packages.

Need For NPM:-


1]Developers can easily find and download pieces of code(packages) made by
others.This saves them time and effort.
2]Developers can share their own code with others.This helps the community by
letting everyone build on each other's work.
3]NPM lets developers create shortcuts for doing common tasks,like testing or
deploying their code.This makes their work faster and easier.

Advantages of NPM:-
1]NPM simplifies the process of adding,updating,and managing external code packages
in a project,saving developers time and effort.
2]It facilitates the sharing and reuse of JavaScript code modules,promoting
efficiency by allowing developers to build on existing solutions.
3]NPM ensures consistency by managing different versions of packages,preventing
compatibility issues and providing stability in the development environment.
4]Developers benefit from a vast community of shared code modules,fostering
collaboration and accelerating the development cycle through access to a rich
ecosystem of tools and libraries.

Packages:-
1]In Nodejs,a package refers to a collection of code and resource files,typically
designed to perform a specific function or provide a set of functionalities.
2]It could be a library,tool,or any modular component that developers can use in
their projects.
3]The package.json file is a configuration file in Node.js projects.
4]It contains metadata about the project,such as its name,version,dependencies,and
various settings.

Install a package locally:-

1]To install a package locally in a Node js project or application,you can use the
following command in your terminal:
npm install <package-name>

Using The Installed package in your code:-

1]Once you've installed a package locally in your Node.js project, you can use it
in your code by requiring or importing it.
2]For Example:-
const packageName=require('<package-name>');
packageName.someFunction();

Uninstall a local package:-


1]To uninstall a package in Node.js, you can use the following command in your
terminal:
npm uninstall <package-name>

Manually Editing package.json:-


1]Open your package.json file in a text editor.
2]Find the "dependencies" section.
3]Add a new line with the package name and version,like this:
"dependencies":
{
"package-name":"version"
}
4]Save the file.Using npm Install Command:
5]Open your terminal in the project directory.
6]Run the following command,replacing <package-name> with the actual package name:
npm install <package-name> --save
7]This installs the package and automatically updates the package.json file with
the new dependency.

install Package Globally:-

1]To install packages globally in Node.js, you can use the following command in
your terminal or command prompt:
npm install -g <package-name>

Uninstall Global Pacakage:-

1]To uninstall a globally installed package in Node.js, you can use the following
command in your terminal or command prompt:
npm uninstall -g <package-name>

Updating Local Packages:-

1]To update local packages in your Node.js project, you can use the npm update
command.
2]This command will look for newer versions of the packages listed in your
package.json file and update them if newer versions are available.
3]It updates the packages within the scope of your specific project,not globally.
4]This means it only updates the packages listed in your project's package.json
file and installed in the node_modules directory of your project.
5]If you want to update a specific package to its latest version, you can use:
npm update <package-name>

Updating Global Package:-

1]To update a globally installed package in Node.js, you can use the following
command in your terminal or command prompt:
npm update -g <package-name>

Managing Third-Party Packages Using NPM:-

1]Use the npm install <package-name> command to install a third-party package


locally.
2]For global installations,use npm install -g <package-name>.
3]The installed packages and their versions are tracked in the package.json file.
4]The dependencies section lists the packages required for your project.
5]When starting a new project or cloning an existing one,use npm install to fetch
and install all dependencies listed in package.json.
6]Keep packages up-to-date using npm update for local packages or npm update -g
<package-name> for global ones.
7]Use npm uninstall <package-name> to remove a package locally.
8]For global removal,use npm uninstall -g <package-name>.
9]Regularly check for security updates using npm audit to ensure your packages are
secure.

Web Server:-

1]A web server is a software application that interacts with web browsers by
processing HTTP requests and providing web content such as HTML pages,images,and
scripts,in response to those requests.
2]Web servers listen for incoming HTTP requests on a specific port,process these
requests,and generate appropriate responses based on the requested resources.
3]They communicate with clients using the Hypertext Transfer
Protocol(HTTP),facilitating the exchange of data between the server and the client
over the internet.
4]They implement various security measures such as authentication,encryption like
HTTPS,and access control to protect sensitive data and prevent unauthorized access
to resources.

Static Web Server:-


1]Static Web serves pre-existing files directly to the browser without
modification.
2]It is Useful for delivering static content like HTML,CSS,and images.

Dynamic Web Server:-


1]Dynamic Web Server processes requests by generating or modifying content before
sending it to the browser.
2]It is suitable for applications with changing data or personalized content.
3]It Utilizes server-side logic to dynamically create web pages based on user input
or other factors.

Static Website:-
1]A static website consists of fixed,unchanging files delivered to users without
any server-side processing.
2]Its Content remains the same until manually updated,making it suitable for
simpler,information-centric web pages like company portfolios or blogs.

Advantages of Static Websites:


1]Static sites are generally faster to load since they serve fixed content without
server-side processing.
2]It is Easier and quicker to develop and deploy,especially for straightforward
content-based sites.
3]Static sites tend to have simpler architectures compared to dynamic sites, which
can result in a reduced likelihood of security issues due to their straightforward
nature.
Disadvantages of Static Websites:
1]It Lacks dynamic features and interactivity compared to dynamic websites.
2]Updating content may require manual modification of files,making it less
efficient for large or frequently changing websites.

Dynamic Website:-
1]A dynamic website generates content on the server side,allowing for real-time
customization based on user input,preferences,or data from databases.
2]It offers interactive features and is well-suited for applications where
information is frequently updated,such as social media platforms,e-commerce
sites,or web applications.

Advantages of Dynamic Websites:-


1]Dynamic sites offer interactive elements,enhancing user engagement and
experience.
2]Content can be updated dynamically,reflecting changes immediately without manual
intervention.
3]It Customized user experiences based on preferences or behavior are possible.

Disadvantages of Dynamic Websites:-


1]Building dynamic sites can be more complex and time-consuming.
2]Dynamic sites require server processing,which can lead to increased server load
and potentially slower response times.
3]The dynamic nature may introduce security challenges,such as vulnerabilities in
server-side scripts or databases.

HTTP Request Handling in Node js:

1]You create an HTTP server using Node.js's built-in http module.


2]The server listens for incoming requests on a specified port.
3]When a request is received,you handle it with a callback function,which gets
information about the request Like URL,method,headers.
4]After processing the request,you construct an HTTP response.You set the response
status code 200 for success,404 for not found).
5]You define response headers,like content type.
6]You send the actual response content Like HTML,JSON.
7]For Example:-
const server=http.createServer((req,res)=>
{
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello,World!');
});
const PORT=3000;
server.listen(PORT,()=>
{
console.log(Server listening on port ${PORT});
});

Request Handling:
HTTP in Node js lets you create a server that can handle incoming requests from
browsers or other clients.

Response Sending:
It enables you to send back responses to those requests,providing the requested
information or resources.

Status Codes:
HTTP supports status codes,like 200 for success or 404 for not found,to indicate
how the server processed a request.

Headers:
You can use headers to share additional information about the data being sent or
received,such as the content type or encoding.

Event-Driven:
Node js HTTP is event-driven,meaning you define what should happen when a request
occurs,and it responds accordingly.

Scalability:
It's designed for scalability,allowing you to handle many simultaneous connections
efficiently.

Creating a Web Server:-

const server=http.createServer((req,res)=>
{
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello,World!');
});
const PORT=3000;
server.listen(PORT,()=>
{
console.log(Server listening on port ${PORT});
});

GET:
1]This Method is Used for requesting data from a specified resource.
2]Typically used for retrieving information without altering the server state.

POST:
1]It Submits data to be processed to a specified resource.
2]It is Commonly used for creating or updating a resource on the server.

PUT:
1]It Updates a resource or creates a new resource if it does not exist.
2]The entire resource is replaced with the new data.

DELETE:
1]Deletes the specified resource.Used for removing a resource on the server.

HEAD:
1]It Requests the headers of the specified resource.Similar to GET but does not
return the actual data.
2]It is useful for checking resource existence or modifications.

File System:-
1]In Node js,the File System(fs) module is like a toolbox for dealing with files on
your computer.
2]It helps your program do things like reading what's in a file,writing new
information,creating or deleting files,checking what's in a folder,and finding out
details about a file,such as its size or when it was last changed.
3]It is like your program's way of managing and interacting with files and
folders,just like you do on your computer.

Reading a file synchronously:-


1]Reading a file synchronously in Node js involves using the fs(File
System)module's synchronous version of the readFile function.
2]For Example:

const fs=require('fs');
const filePath='path/to/your/file.txt';
try
{
const data=fs.readFileSync(filePath,'utf8');
console.log('File content:',data);
}
catch(err)
{
console.error('Error reading the file synchronously:',err);
}

Reading a file asynchronously:-


1]Reading a file asynchronously in Node js involves using the fs(File System)
module's readFile function.
2]For Example:-
const fs=require('fs');
const filePath='path/to/your/file.txt';
fs.readFile(filePath,'utf8',(err,data)=>
{
if(err)
{
console.error('Error reading the file asynchronously:',err);
return;
}
console.log('File content:',data);
});

Synchronously Writing data to a file:-

const fs=require('fs');
const filePath='path/to/your/file.txt';
const data='Hello,world!';
try
{
fs.writeFileSync(filePath,data,'utf8');
console.log('File written synchronously!');
}
catch(err)
{
console.error('Error writing file synchronously:',err);
}

Asynchronously Writing data to a file:-

const fs=require('fs');
const filePath='path/to/your/file.txt';
const data='Hello,world!';
fs.writeFile(filePath,data,'utf8',(err)=>
{
if(err)
{
console.error('Error writing file asynchronously:',err);
return;
}
console.log('File written asynchronously!');
});

Open a file:-
1]In Node js,you can open a file using the fs(File System) module.
2]For Example:-
const fs=require('fs');
const filePath='path/to/your/file.txt';
fs.open(filePath,'r',(err)=>
{
if(err)
{
console.error('Error opening the file:', err);
return;
}
console.log('File opened successfully!');
});

Delete a file:-

1]In Node js,you can delete a file using the fs(File System) module.
2]For Example:-
const fs=require('fs');
const filePath='path/to/your/file.txt';
fs.unlink(filePath,(err)=>
{
if(err)
{
console.error('Error deleting the file:',err);
return;
}
console.log('File deleted successfully!');
});

Truncate a file:-

1]In Node js,you can truncate a file using the fs(File System) module.
2]Truncating a file means reducing its size to a specified length.
3]For Eaxmple:-
const fs=require('fs');
const filePath='path/to/your/file.txt';
const newSize=1024;
fs.truncate(filePath,newSize,(err)=>
{
if(err)
{
console.error('Error truncating the file:',err);
return;
}
console.log('File truncated successfully!');
});

Append a file:-
1]In Node js, you can append data to a file using the fs(File System) module.
2]For Example:-
const fs=require('fs');
const filePath='path/to/your/file.txt';
const newData='This will be appended to the file.';
fs.appendFile(filePath,newData,'utf8',(err)=>
{
if(err)
{
console.error('Error appending to the file:',err);
return;
}
console.log('Data appended to the file successfully!');
});

Error and Exception Handling:-

1]Errors Handling in Node js are like warning signs that appear when something
unexpected occurs in your code.
2]Exception handling is like having a backup plan in case those warning signs pop
up,so your entire program doesn't crash
3]Think of a try block as a safe zone for risky actions,and a catch block as the
backup plan that kicks in if something goes wrong.
4]For Example:-
function divide(a,b)
{
if(b==0)
{
throw new Error("Cannot divide by zero!");
}
return a/b;
}

function Division(a,b)
{
try
{
const result=divide(a,b);
console.log("Result of division:",result);
}
catch(error)
{
console.error("An error occurred:",error.message);
}
}

console.log("Test 1:");
Division(10,2);

console.log("Test 2:");
Division(8,0);

You might also like