Node Js
Lecture 11
What is Node.js?
A free and open-source, cross-platform
JavaScript runtime environment
JavaScript can be used on the Server.
A single language for both frontend and
backend.
Build end-to-end JavaScript
applications.
Several major companies such as LinkedIn,
Netflix, and PayPal, have all migrated from
one background technology to node js.
Run Time Environment for Run
JS Code
JavaScript Engine: Node.js uses the V8
JavaScript engine (from Google Chrome) to
interpret and run JavaScript code.
JS Engines
Node.js handles a file request:
Receive Request:
Sends a request (indx.html or image) to Node.js server.
Process Request Using Asynchronous I/O
Node.js receives the request and, rather than blocking other
operations while waiting for the file to be read, it sends a call
to the filesystem to retrieve the file asynchronously.
Callback Handling
Once the file operation is complete, the fs module sends the
file data to a callback function, allowing Node.js to continue
processing other requests while waiting for the file data.
Send Response to Client:
If there’s no error, it sends the file content back as the response to the
client.
Node JS Architecture
Node JS Architecture
Node JS Architecture
Example
A user types a message and sends it to the
server.
When the server receives the message, it
processes and forwards it to the intended
recipient immediately without waiting for any
other operation.
Using a non-blocking database function, Node.js
initiates the message logging but does not wait
for the database operation to complete.
The sender and recipient both get the message
instantly, as Node.js does not pause for database
logging to finish.
What Can Node.js Do?
Node.js can generate dynamic page
content
Node.js can create, open, read, write,
delete, and close files on the server
Node.js can collect form data
Node.js can add, delete, modify data
in your database
What Can you Build with Node
JS?
Traditional Websites
Backend Services like APIs
Real-time applications
Streaming Services
CLI (Command Line Interface) Tools
Multiplayer Applications
Node JS allowed you to Build complex and
powerful applications
Tool Requirements
1. Node. Js: is the runtime environment that
allows you to run JavaScript on the server
2. npm (Node Package Manager): Included
with Node.js: npm comes bundled with Node.js
and is used to manage libraries and
dependencies. It allows you to install packages,
share your own packages, and manage project
dependencies.
3. Text Editor or IDE: Choose a text editor or
Integrated Development Environment (IDE) that
supports JavaScript and Node.js development.
(VS Code, Sublime, Atom etc)
Tool Requirements
4. Terminal or Command Prompt:
Essential: You'll need access to a
terminal or command prompt to run
Node.js commands.
(Command Prompt, PowerShell, or Windows
Terminal)
Download Node. JS
1. Click Here to Downlo
ad
2.Install Node.Js
3.Now go to Start and
type Node.JS
Start a project
Go to VS.
Create a Folder.
Go to View and Open the Terminal.
Now write node –v. It will show the
version of Node.js. In case of an error,
your Node.js installation might not have
been successful.
Cltr + D to clear Command
How to Execute JavaScript
Code with Node
Node REPL:It is a programming language
environment (basically a console window)
that takes a single expression as user input
and returns the result to the console after
execution.
Read
Evaluate
Print
Loop
How to Execute JavaScript
Code with Node
Variable in Node REPL
Loop in Node REPL
Execute Code in JavaScript File in Command Line
Create a new File with the convention
App.js, Main.js, or Index.js
Now got to file and write code:
Modules
Node.js utilizes a modular architecture,
allowing code to be organized into reusable
units.
These modules can be categorized into
three types:
Local Module,
Built-in Module,
and Third-party.
Local Modules:
These are custom modules created by the
developer for a specific application.
They reside within the application's
directory and are typically used to organize
and reuse code within the project.
Local modules are imported using relative
paths in the require() function.
Local Modules cont..
Modules that we create and use in our applications.
Each file is a module that is isolated by default
To load a module into another file, use require function
CommonJS (//saba.js file)
CommonJS is a standard that states how a module
should be structured and shared.
Node.Js adopted CommonJS when it started and is what
you will see in the code bases
Built in or Core Modules
these are provided by Node.js itself and
offer essential functionalities such as :
File system operations (fs),
HTTP requests (http),
And path manipulation (path).
Built-in modules do not require installation
and are imported using their name in the
require() function.
Path
Useful for handling and transforming file paths
Provide utilities for working with directories and
file paths such as joining paths, getting file
extent
Path.join
Path.parse
Third Party Module
These are modules developed by the
community and made available through
the Node Package Manager (npm).
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(“Node”)
Common use for the File System module:
• Read files
• Create files
• Update files
• Delete files
• Rename files
Write Files-Synchronous
const fs = require('fs');
//Takes 3 arguments, third one is optional
fs.writeFileSync('write.txt', 'Write the
file‘,’utf-8’);
console.log("File write done");
Write.txt File was created on run time.
Write Files-Asynchronous
const fs = require('fs’);
//take 4 arguments, one is optional
fs.writeFile('writeAs.txt','This is Asynchronous File',function(err){
if (err)
{ console.log("Error Occurred");}
else
{ console.log("File Successfully Created") }
});
console.log("After file write");
Synchronous(fs.writeFileS
ync)
Blocking: The fs.writeFileSync function is
synchronous, meaning it blocks the
execution of the program until the file write
operation is complete. The code will wait for
the file to be written before moving on to
the next line of code.
No callback: Since it is synchronous, it
doesn’t need a callback. Any errors will be
thrown and need to be handled using
try/catch
Asynchronous(fs.writeFile)
Non-blocking: The fs.writeFile function is
asynchronous and doesn't block the
execution of the program. This means that
other code can continue executing while the
file is being written.
Callback-based: It requires a callback
function to handle any potential errors or
success when the operation is complete.
Read File-Synchronous
fs.readFileSync('writeAs.txt');
console.log("et data = The date of file
is",data);
Data will show buffer values so convert it into a
string
console.log("The date of file
is:",data.toString());
Read File-Asynchronous
fs.readFile('writeAs.txt',function(err,data){
if (err)
{console.log("Error has Occured",err);
return;}
else{console.log("The date of file
is:",data.toString());}
});
Delete File-Synchronous
try
{
fs.unlinkSync('write.txt');
}
catch(error){
console.log('error',error)
}
Delete File - Asynchronous
const fs = require('fs');
fs.unlink('writeAs.txt',function(err){
if(err)
{
console.log("error occured", err);
}
else
{console.log("Deleted");}
}
);
Rename File
const fs = require('fs');
if(fs.existsSync("New.txt"))
{
fs.renameSync('New.txt','write.txt');
console.log("Changed Successfully");
}
else{"File not found";}
HTTP Module
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type':
'text/html' });
res.write('Welcome to this page!');
res.end();
}).listen(3000);
Explanation
require() is a function in Node.js used to import
modules or libraries into your script. It allows you
to use built-in or third-party modules in your code.
The function http.createServer() method will be
executed when someone tries to access the
computer on port 3000.
The res.writeHead() method is the status code
where 200 means it is OK, while the second
argument is an object where you specify
additional response headers. Here, { 'Content-
Type': 'text/html' } tells the browser that the
content being sent is HTML.
Example NodeJS with HTML
Example NodeJS with HTML
Reference
https://nodejs.org/docs/latest-v16.x/api/
fs.html#fsreadfilepath-options-callback