Module II
Module II
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
🞇 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