KEMBAR78
Node - Js Part4 | PDF | Computer File | Java Script
0% found this document useful (0 votes)
8 views11 pages

Node - Js Part4

Node.Js Workshop Powerpoint Presentation

Uploaded by

arunasekaran
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)
8 views11 pages

Node - Js Part4

Node.Js Workshop Powerpoint Presentation

Uploaded by

arunasekaran
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/ 11

Asynchronous

Programming
● Asynchronous Programming is a paradigm used in Node.js development, allowing us to

perform concurrent tasks without blocking other operations.


● Callbacks are widely used to handle these operations asynchronously. These can sometimes

lead to complex nested code raising the challenge called Callback Hell.
● A callback is a function that's passed as a parameter to another method/function and is

executed when the event happens. It can be thought of as an event handler for a performed
action. Such as on button click on UI.
Blocking Example (Sync):

const fs = require('fs');
const data = fs.readFileSync('file.txt'); // Blocks here
console.log(data.toString());

Non-blocking Example (Async):


fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
Working with Express
1. Routing in Express

Handles different HTTP methods (GET, POST, PUT, DELETE)


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

app.post('/users', (req, res) => {...});

2. Middleware

Functions that execute before route handlers.


app.use(express.json()); // built-in middleware for parsing JSON

3. Modular Routing

Use express.Router() for clean code organization:


const router = express.Router();

router.get('/posts', (req, res) => {...});


Introduction to Asynchronous File
System
The File System module (fs) provides an API to communicate and perform
operations on the file system. It allows operations like reading, writing,
updating files and deleting files & directories.It allows the functionalities of file
I/O with the use of wrappers modeled on or around standard POSIX
functions.POSIX - Portable Operating System Interface.These file operations can
be synchronous or asynchronous depending on the requirements of your
application.
To define this module in our Node.js applications we make use of the line:
const fs = require('fs');

1. fs.readFile() – Read a File

Definition:
Reads the entire contents of a file asynchronously. It doesn't block
the execution thread.

Syntax:
Introduction to Asynchronous File System
2. fs.writeFile() – Write to a File

Definition:
Creates a new file or overwrites an existing file with the
provided content, asynchronously.

Syntax:
3. fs.open() – Open a File
fs.writeFile(path, data, options, callback);
Definition:
Opens a file for reading, writing, or both. Returns a file descriptor (a
low-level reference to the file).

Syntax:
4. fs.unlink() – Delete a File
fs.open(path, flags, mode, callback);
Definition:
Deletes a file asynchronously from the file
system.

Syntax:
Introduction to Asynchronous File System

5. Writing a File Asynchronously – Full Breakdown

Writing to a file asynchronously we will create a new folder


and for this course’s purpose we will name is ‘File System
Operations’.
In this folder we will create a file ‘main.js’ in which we will
write data to a new file.

Our aim is to write a program that creates a new file as well as


writes to it asynchronously.
New folder containing only our js file:
main.js:

const fs = require('fs'); //Defining the filesystem module to be


used further
const asyncWriteExample = 'Data is written to this file in
asynchronous mode using callbacks'; //Data we want to write
to the file.
fs.writeFile('./testasyncWriteExample.txt',
asyncWriteExample, errObj => {
if (errObj) {
console.error(errObj); //Error Handling
} else {
console.log("File write operation was successful.");
}
});
Now we see a new file has been created
inWe
ourrun
folder
thisand
codeitsusing
contents:
command prompt
File 'testasyncWriteExample.txt'

Other I/O Operations

1. fs.appendFile() - Used to append data to a file.


2. fs.createReadStream() or fs.createWriteStream() – For reading from or
writing to files using streams.
3. fs.watch() – To watch for changes in a file or directory using
eventTypes.
4. fs.copyFile() – To copy a file from one location to another.
5. fs.rename() – To move or rename a file.
6. fs.readdir(), fs.mkdir() or fs.mkdirSync() & fs.rmdir() or fs.rmdirSync()
– To get lists of files in a director, create or delete a directory respectively.
7. fs.stat(), fs.fstat(), or fs.lstat() - To retrieve file/directory metadata, like
size, modified times, and permissions.
8. It is important to note that a lot of the fs methods are coupled with
promise-based counterparts from the fs/promises module, which allow
Introduction to JS ES6
ES6 (ECMAScript 6), officially known as ECMAScript 2015, is a major
update to JavaScript that introduced many powerful and modern
features, making code cleaner, easier to manage, and more
maintainable.
Some features that ES6 brought to JavaScript are:
• Modules – ES6 brought about support for modules, allowing developers to
import & export functions/methods, and objects from one module to another.

1. Export: This allows to export functions, objects, or variables from required


modules.
2. Import: This allows to import the exported entities from the required modules.
3.Promises – ES6 gave us a way to handle asynchronous operations more
efficiently than callbacks.
4.Classes - Classes are used to create objects with the help of a constructor
5.Arrow Functions - It allowed a shorter syntax for writing function definitions as
you no longer required the keywords ‘function’, ’return’ or the curly braces. const
multiply = (a, b) => a * b;
6.Template Literals – Made it easier to create strings, especially when embedding
variables or expressions is required. Backticks (') are used for
this.
const a = "JohnDoe";
const b = 'Student ${a}';
Nodemailer Module
● The Nodemailer module is a Node.js Module that can be made
use of for sending emails as it makes it easy to use the various
A mechanisms required by the application.
transport
● It is a module that allows sending emails from your server, be
I
it communicating with users or notifications of any application
related update.
Nodemailer – Sending Emails in Node.js
🔹 Step 1: Install Nodemailer
npm install nodemailer
🔹 Step 2: Import Module
const nodemailer = require('nodemailer');
🔹 Step 3: Create Transporter
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_app_password'
}
});
🔹 Step 4: Define Mail Options
const mailOptions = {
from: 'your_email@gmail.com',
to: 'recipient@example.com',
subject: 'Test Email',
text: 'Hello from Nodemailer!'
};
🔹 Step 5: Send Email
transporter.sendMail(mailOptions, (error, info) => {
if (error) return console.log(error);
console.log('Email sent:', info.response);
});

You might also like