0% found this document useful (0 votes)
57 views14 pages

FALLSEM2020-21 CSE3002 ETH VL2020210106412 Reference Material I 29-Oct-2020 NodeJS Intro

Node.js modules allow code reuse and organization. The require() function is used to include Node.js built-in and custom modules. Built-in modules provide access to operating system functionality like HTTP servers, file systems, and more. Objects in Node.js can emit events using the EventEmitter class. Callbacks allow asynchronous code to be executed after an asynchronous operation completes.

Uploaded by

asmit gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views14 pages

FALLSEM2020-21 CSE3002 ETH VL2020210106412 Reference Material I 29-Oct-2020 NodeJS Intro

Node.js modules allow code reuse and organization. The require() function is used to include Node.js built-in and custom modules. Built-in modules provide access to operating system functionality like HTTP servers, file systems, and more. Objects in Node.js can emit events using the EventEmitter class. Callbacks allow asynchronous code to be executed after an asynchronous operation completes.

Uploaded by

asmit gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Node.

js
Events and Call backs
Node.js Modules
• A set of functions you want to include in your application.

• Node.js has a set of built-in modules which you can use without any further
installation.

• Include Modules
• To include a module, use the require() function with the name of the
module:

• var http = require('http');


Node.js Built-in Modules
Module Description
assert Provides a set of assertion tests
buffer To handle binary data
child_process To run a child process
cluster To split a single Node process into multiple processes
crypto To handle OpenSSL cryptographic functions
dgram Provides implementation of UDP datagram sockets
dns To do DNS lookups and name resolution functions
domain Deprecated. To handle unhandled errors
events To handle events
fs To handle the file system
http To make Node.js act as an HTTP server
https To make Node.js act as an HTTPS server.
net To create servers and clients
os Provides information about the operation system
path To handle file paths
punycode Deprecated. A character encoding scheme
querystring To handle URL query strings
readline To handle readable streams one line at the time

stream To handle streaming data


string_decoder To decode buffer objects into strings
timers To execute a function after a given number of milliseconds

tls To implement TLS and SSL protocols


tty Provides classes used by a text terminal
url To parse URL strings
util To access utility functions
v8 To access information about V8 (the JavaScript engine)

vm To compile JavaScript code in a virtual machine

zlib To compress or decompress files


Create Your Own Modules
Create a module that returns the current date and time: myfirstmodule.js

exports.myDateTime = function ()
{
return Date();
};

Use the exports keyword to make properties and methods available


outside the module file.
var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

To include a module,
use the require() function with the name of the module:

Now your application has access to the HTTP module, and is able to create a
server:
Include Your Own Module
var http = require('http');
var dt = require('./myfirstmodule');

http.createServer(function (req, res)


{
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Events in Node.js
Objects in Node.js can fire events, like the readStream object fires
events when opening and closing a file:

var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
Events Module
• 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();
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.

var events = require('events');


var eventEmitter = new events.EventEmitter();

//Create an event handler:


var myEventHandler = function () {
console.log('I hear a scream!');
}

//Assign the event handler to an event:


eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:


eventEmitter.emit('scream');
Listeners
emitter.addListener(event, listener)
var emitter = require('events').EventEmitter;
var em = new emitter();
//Subscribe FirstEvent
em.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');

First parameter is name of the event as a string and then arguments.


EventEmitter Methods Description
Adds a listener to the end of the listeners array for the specified event. No
emitter.addListener(event, listener)
checks are made to see if the listener has already been added.
Adds a listener to the end of the listeners array for the specified event. No
emitter.on(event, listener) checks are made to see if the listener has already been added. It can also be
called as an alias of emitter.addListener()
Adds a one time listener for the event. This listener is invoked only the next time
emitter.once(event, listener)
the event is fired, after which it is removed.
Removes a listener from the listener array for the specified event. Caution:
emitter.removeListener(event, listener)
changes array indices in the listener array behind the listener.
emitter.removeAllListeners([event]) Removes all listeners, or those of the specified event.
By default EventEmitters will print a warning if more than 10 listeners are added
emitter.setMaxListeners(n)
for a particular event.
Returns the current maximum listener value for the emitter which is either set
emitter.getMaxListeners()
by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.

emitter.listeners(event) Returns a copy of the array of listeners for the specified event.

emitter.emit(event[, arg1][, arg2][, ...]) Raise the specified events with the supplied arguments.

emitter.listenerCount(type) Returns the number of listeners listening to the type of event.


What are callbacks?
• A callback function is a function that is passed to another function as
a parameter, and the callback function is called (executed) inside the
second function.
• Callbacks functions execute asynchronously
var fs = require('fs'); function mycontent() {
var fcontent ; console.log(fcontent);
function readingfile(callback){ }
fs.readFile("readme.txt", "utf8", readingfile(mycontent);
function(err, content) { Console.log('Reading files....');
fcontent=content;
if (err) mycontent() function can get passed in
{ an argument that will become the
return console.error(err.stack); callback variable inside the readingfile()
function. After file reading is completed
} through readFile() the callback variable (
callback(content); callback()) will be invocked. Only
}) function can be invoked
};

You might also like