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

Module II

Modules 2

Uploaded by

Firoza
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module II

Modules 2

Uploaded by

Firoza
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

NODE.

JS
MODULES,
EVENTS &
FUNCTIONS
Detailed Contents
NODE.JS MODULES
🞇 Consider to be the same as JavaScript libraries. A
set function you want to include in your
application.
🞇 Node.js has a set of built-in modules which you
use without any further installation.
Module
🞇 File System
🞇 OS
🞇 Path
🞇 Http
🞇 Event
File System MODULE
🞇 Want to use file system module -
Hence we require to add file module in our project.
OS Module
🞇 To find out architecture of our computer architecture
arch()
🞇 To get free memory space us
os.freemem()
STANDARD CALLBACK
PATTERN
🞇 Callback is an asynchronous equivalent for a function. A
callback function is called at the completion of a given task.
Node makes heavy use of callbacks. All the APIs of Node are
written in such a way that they support callbacks.
🞇 For example, a function to read a file may start reading file and
return the control to the execution environment immediately so
that the next instruction can be executed. Once file I/O is
complete, it will call the callback function while passing the
callback function, the content of the file as a parameter. So there
is no blocking or wait for File I/O. This makes Node.js highly
scalable, as it can process a high number of requests without
waiting for any function to return results.
🞇 BLOCKING CODE EXAMPLE
🞇 NON BLOCKING CODE EXAMPLE
🞇 These two examples explain the concept of blocking and non-blocking
calls.
1) The first example shows that the program blocks until it reads the
file and then only it proceeds to end the program.
2) The second example shows that the program does not wait for file
reading and proceeds to print "Program Ended" and at the same time,
the program without blocking continues reading the file

🞇 Thus, a blocking program executes very much in sequence. From the


programming point of view, it is easier to implement the logic but non-
blocking programs do not execute in sequence. In case a program needs
to use any data to be processed, it should be kept within the same block
to make it sequential execution.
EVENT EMITTER PATTERN
🞇 The standard callback pattern — whereby you pass a callback function as an
argument of the function you are executing — works well when you want
the client to be notified when a function completes.
🞇 But if several events take place during execution, or if they happen several
times, this style doesn’t work as well. For instance, if you are interested in
being notified every time, the standard callback pattern is not very helpful.
This is when the event emitter pattern can help.
🞇 You can use a standard interface to clearly separate the event emitter and the
event listener. When you use an event emitter pattern, two or more objects
are involved — the event emitter and one or more event listeners.
🞇 An event emitter is an object that — as the name says — emits events. An
event listener is a part of the code that binds to the event emitter and listens
for certain types of events.
EVENT TYPE (after)
🞇 Notice that emitted events always have a type, which is represented by a
string. In this example we have the “data” and “end” event types. These are
arbitrary strings dictated by the event emitter.
🞇 We cannot infer programmatically what types of events a given event
emitter emits: The event emitter API provides no such introspection
mechanism. The API you are using should document which event types it is
emitting.
🞇 The event emitter will invoke the listener once a relevant event occurs, and
it will pass in any relevant data. In the previous http.request example, the
“data” event callback function received the data object as its first and sole
argument, whereas the “end” event didn’t receive any. These are also
arbitrary arguments that are part of the specific API contract
THE EVENT EMITTER API
🞇 Any object that implements the event emitter pattern
➤ .addListener and .on — To add an event listener to an
event type
➤ .once — To attach an event listener to a given event
type that will be called at most once
➤ .removeEventListener — To remove a specific event
listener of a given event
➤ .removeAllEventListeners — To remove all event
listeners of a given event type
Method and Description
EVENT
🞇 Every action on a computer is an event. Like when a connection is made or a file is opened.
🞇 Objects in Node.js can fire events, like the readStream object fires events when opening and closing a
file
EVENT MODULE
🞇 Node.js has a built-in module, called "Events", where we can create-, fire-, and listen
for our 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();
EVENTEMITTER OBJECT
🞇 (Creation of own event)
🞇 We can assign event handlers to our own events with the EventEmitter
object.
🞇 In the example below we have created a function that will be executed when
a "scream" event is fired.
🞇 To fire an event, use the emit() method.
COMMON PATTERNS FOR EVENT EMITTERS

There are two common patterns that can be used to


raise and bind an event using EventEmitter class in
Node.js.

1. Return EventEmitter from a function


2. Extend the EventEmitter class
1) Return EventEmitter from a function
🞇 In this pattern, a constructor 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.
Consider the following example
🞇 In the above LoopProcessor() function, first we create an object of
EventEmitter class and then use it to emit 'BeforeProcess' and
'AfterProcess' events. Finally, we return an object of EventEmitter
from the function. So now, we can use the return value of
LoopProcessor function to bind these events using on() or
addListener() function.
2) Extend EventEmitter Class
🞇 In this pattern, we can extend the constructor function from
EventEmitter class to emit the events
🞇 In the above example, we have extended LoopProcessor
constructor function with EventEmitter class using
util.inherits() method of utility module. So,we can use
EventEmitter's methods with LoopProcessor object to handle
its own events.
🞇 In this way, you can use EventEmitter class to raise and
handle custom events in Node.js
DIFFERENCE BETWEEN
EVENTS AND CALLBACKS
🞇 Events and Callbacks look similar but the differences lies in
the fact that callback functions are called when an
asynchronous function returns its result
🞇 Where as event handling works on the observer pattern.
Whenever an event gets fired, its listener function starts
executing. Node.js has multiple in-built events available
through events module and EventEmitter class which is used
to bind events and event listeners
DEFER EXECUTION OF A
FUNCTION
Syntax-setTimeout(callbackfunction,period)
Task-
🞇 Print Hello after 5sec
🞇 Print Hello after 7 sec
🞇 Use only one function
CANCEL THE EXECUTION OF A
FUNCTION
Task--
🞇 Cancel function execution in another
function.
SCHEDULE/CANCEL REPETITIVE
EXECUTION OF FUNCTION
🞇 If we want to print same line of code after define time interval
🞇 Syntax-setInterval(callbackfunction,period)
Task
🞇 Read a file in every 1000ms
🞇 Read a file after 2000ms.
USING PROCESS.NEXTTICK TO DEFER
THE EXECUTION
OF A FUNCTION UNTIL THE NEXT EVENT
LOOP ITERATION
🞇 setTimeout(callback, 0)
🞇 By using process.nextTick(callback) instead of
setTimeout(callback, 0), your callback runs
immediately after all the events in the event queue
have been processed.
🞇 Ex. process.nextTick(function() {
my_expensive_computation_function();
});
BLOCK EVENT LOOP
🞇 Node and JavaScript runtimes in general are single-
threaded event loops. On each loop, the runtime
processes the next event in queue by calling the
associated callback function.
🞇 When that event is done, the event loop fetches and
processes the next event; this pattern continues until the
queue is empty.
🞇 If one of these callbacks takes a long time, the event
loop won’t process pending events in the meantime.
🞇 This can lead to a slow application or service.
🞇 In this case, the nextTick2 and timeout functions will never have the chance to
run no matter how long we wait because the event loop is blocked by an
infinite cycle inside the first nextTick function.
🞇 Even the scheduled timeout function that was supposed to run after one second
does not run.
🞇 When using setTimeout, the callback function goes into a scheduling queue,
which, in this case, doesn’t even get to be dispatched.
🞇 This is an extreme case, but we can see how running a processor-intensive task
may block or slow down our event loop .
ESCAPE EVENT LOOP
🞇 By using process.nextTick, we can now defer the
execution of a non-crucial task to the next tick,
freeing the event loop to execute other pending
events.

You might also like