0% found this document useful (0 votes)
93 views81 pages

FSD Node - Js Module 4

Uploaded by

aboutrajababu1
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)
93 views81 pages

FSD Node - Js Module 4

Uploaded by

aboutrajababu1
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/ 81

Full Stack Development

Presentation Material

Department of Computer Science & Engineering

Course Code: Semester: III

Course Title: FSD Year: II

Faculty Name:

Department of Computer Science &


Course Name & Course Code 1
Engineering
(MODULE 4)

Node JS

Introduction to NodeJS, Set up Dev Environment, Node JS


Modules, Node Package Manager, File System, Events, Database
connectivity using MongoDB
Introduction to NODE JS

• Node JS is an open-source and cross platform JavaScript runtime


environment. It is used for developing server-side and networking
applications. Node JS runs single threaded, non-blocking, asynchronous
programming. Node JS files must be initiated on the server. And the files
of Node JS will have an extension “.js”
Set up dev environment
• Node JS environment can be setup in windows, Mac, Linux. It requires the
following tools/SDK (Software Development Kit) :
• Node JS
• Node Package Manager (NPM)
• IDE (Integrated Development Environment) or Text Editor
Node.js Module

• Module in Node.js is a simple or complex functionality organized in


single or multiple JavaScript files which can be reused throughout
the Node.js application.
• Each module can be placed in a separate .js file under a separate
folder. Node.js implements commons modules standard .
Node.js Module Types
• Node.js includes three types of modules:
• Core Modules
• Local Modules
• Third Party Modules
*Node.js Core Modules

• The core modules include bare minimum functionalities of Node.js. These


core modules are compiled into its binary distribution and load
automatically when Node.js process starts. However, you need to import
the core module first in order to use it in your application.
Core Module Description

http module includes classes, methods and events to create


http
Node.js http server.

url url module includes methods for URL resolution and parsing.

querystring Querystring module includes to deal with query string.

Path Path module includes methods to deal with file paths

Util Util module includes utility functions useful for programmers

fs module includes classes ,methods and events to work with file


Fs
I/O
Loading Core Modules
• To use Node.js core, you first need to import it using require ()
function.
• var module =require (‘module_name’);
• Specify the module name in the require() function. The require()
function will return an object, function, property or any other
JavaScript type, depending on what the specified module returns.
Node.js HTTP Module
• Node.js has a built-in module called HTTP, which allows Node.js to transfer data
over the Hyper Text Transfer Protocol (HTTP).To include the HTTP module, use
the require() method:
Example1: demonstrate how to use Node.js http module to create a web server.
var http = require('http');
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);
Here require() function returns an object because http module returns its
functionality as an object, then use its properties and methods using dot notation
e.g. http. createServer().In this way,Node.js core modules can be loaded and used
in application.


Example 1:

// include http module in the file


var http = require('http');
// create a server
http.createServer(function (req, res) {
// http header
// 200 - is the OK message
// to respond with html content, 'Content-Type' should be 'text/html'
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Node.js says hello!'); //write a response to the client
res.end(); //end the response
}).listen(9000); //the server object listens on port 9000
The Built-in URL Module

The URL module splits up a web address into readable parts.

To include the URL module, use the require() method:

var url = require('url');

Parse an address with the url.parse() method, and it will return a URL object with each part of the
address as properties:
example:Split a web address into readable parts:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?
year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month:


'february' }
console.log(qdata.month); //returns 'february'
//let parsed_queryString = querystring.parse(q.query);
//console.log("This is parsed Query String :",parsed_queryString);
querystring

// Import the querystring module


const querystring = require("querystring");

// defining the query string as per default parameters of the parse


function
var str = "username=educative_user&password=a1b2c3";

// calling the parse function with default parameters


console.log("Parsed Object: ",querystring.parse(str))
output
Parsed Object: [Object: null prototype]
{ username: 'educative_user', password:
'a1b2c3' }
Util
• The util module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. The Util
module provides access to some utility functions.To access it:
const util = require('util');
Util Properties and Methods

Method Description
debuglog() Writes debug messages to the error object

deprecate() Marks the specified function as deprecated

format() Formats the specified string, using the specified arguments

inherits() Inherits methods from one function into another

inspect() Inspects the specified object and returns the object as a string
// Node.js util.format() demo Example

// Importing the util module


const util = require('util');

function fun1() {
var val1 = util.format('%s:%s:%s', 'tutorialsPoint');

var val2 = util.format('%s:%s','a', 'b', 'c', 'd');

var val3 = util.format(10, 20, 30);

var val4 = util.format('%% : %s : %d');

var val5 = util.format('%% : %s', 786);

console.log(val1, '\n', val2, '\n',


val3, '\n', val4, '\n', val5);
}

// Function call
util.isArray(object) #
Returns true if the given "object" is an Array. false otherwise.

var util = require('util');


util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false
Path -core module
var path = require('path');
//Create a path object:
var obj = { dir: 'C:\\Users\\Refsnes', base:
'demo_path.js' }
//Format the path object into a path string:
var p = path.format(obj);
console.log(p);
output
*Node.js File System Module:fs

• The Node.js file system module allows us to work with the file system on
your computer.To include the File System module, use
the require() method:
var fs = require('fs');
• To handle file operations like creating, reading, deleting, etc., Node.js
provides an inbuilt module called FS (File System).
• Common use for File System module
• Read Files
• Write Files
• Append Files
• Close Files
• Delete Files
Open a File:
The fs.open() method is used to create, read, or write a filefs.open() method
does several operations on a file. First, we need to load the fs class which is a
module to access the physical file system.
Syntax: fs.open(path, flags, mode, callback)

Parameters:
• path: It holds the name of the file to read or the entire path if stored at other
locations.
• flags: Flags indicate the behavior of the file to be opened. All possible values
are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+).
• mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default
as readwrite.
• callback:It is a callback function that is called after reading a file. It takes two
parameters:
• err: If any error occurs.
• data: Contents of the file. It is called after the open operation is executed.
Read Files

• The fs.readFile() method is used to read files on computer.


• Assume we have the following HTML file (located in the same
folder as Node.js):
• Demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
• Create a Node.js file that reads the HTML file, and return the content:
• Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
• Save the code above in a file called "demo_readfile.js", and initiate the
file:
• Initiate demo_readfile.js:
C:\Users\Your Name>node demo_readfile.js
Create Files

• The File System module has methods for creating new files:
1. fs.appendFile()
2. fs.open()
3. fs.writeFile()

1. The fs.appendFile() method appends specified content to a file. If the


file does not exist, the file will be created:
• Example(Create a new file using the appendFile() method)
• var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
2. The fs.open() method takes a "flag" as the second argument, if the
flag is "w" for "writing", the specified file is opened for writing. If
the file does not exist, an empty file is created:

• Example(Create a new, empty file using the open() method)


• var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
3. The fs.writeFile() method replaces the specified file and content if it
exists. If the file does not exist, a new file, containing the specified
content, will be created:

• Example(Create a new file using the writeFile() method)


• var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Update Files

• The File System module has methods for updating files:


• fs.appendFile()
• fs.writeFile()

• The fs.appendFile() method appends the specified content at the end


of the specified file:
• Example(Append "This is my text." to the end of the file
"mynewfile1.txt“)
• var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
if (err) throw err;
console.log('Updated!');
});
• The fs.writeFile() method replaces the specified file and content:
• Example(Replace the content of the file "mynewfile3.txt")
• var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
• Output:
Delete Files

• To delete a file with the File System module, use


the fs.unlink() method.

• Example(Delete "mynewfile2.txt")
• var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Rename Files

• To rename a file with the File System module, use


the fs.rename() method.

• Example(Rename "mynewfile1.txt" to "myrenamedfile.txt”)

• var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
Node.js Local Module

• Local modules are modules created locally in your Node.js


application. These modules include different functionalities of your
application in separate files and folders.

• In Node.js, module should be placed in a separate JavaScript file.


So, create a Log.js file and write the following code in it.

• In the next logging module example, we have created an object with


three functions - info(), warning() and error(). At the end, we have
assigned this object to module.exports. The module.exports in the
above example exposes a log object as a module.
Writing Simple Module
log.js:
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log

module.exports or exports is used to expose a function, object or variable as a module


in Node.js.
Here log is a object: that is having key value pair
Loading Local Module

• To use local modules in your application, you need to load it using


require() function in the same way as core module. However, you need to
specify the path of JavaScript file of the module.
• The following example demonstrates how to use the previous logging
module contained in Log.js.
• app.js
var myLogModule = require('./Log.js');
myLogModule.info('Node.js started');
• Here app.js is using log module . Logging module is contained in Log.js
file in the root folder. So, we have specified the path './Log.js' in the
require() function. The '.' denotes a root folder.
• The require() function returns a log object.
• An object can be attached to module.exports , as shown below.
data.js
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
App.js
var person = require('./data.js');
console.log(person.firstName + ' ' + person.lastName);
Output:
C:\> node app.js
James Bond
Cont.. Export Module in Node.js
• The module.exports is a special object which is included in every JavaScript file
in the Node.js application by default. The module is a variable that represents the
current module, and exports is an object that will be exposed as a module. So,
whatever you assign to module.exports will be exposed as a module.
Export Literals
• exports is an object. So it exposes whatever you assigned to it as a module. For
example, if you assign a string literal then it will expose that string literal as a
module.
• The following example exposes simple string message as a module in Message.js.

Message.js //file name

module.exports = 'Hello world';//write this content in the file Message.js


• Now we can Import the message module and use it as shown below
• app.js //file name
var msg = require('./Messages.js');
console.log(msg);
• Output
C:\> node app.js
Hello World

• Note: You must specify ./ as a path of root folder to import a local


module. However, you do not need to specify the path to import
Node.js core modules or NPM modules in the require() function.
Export Object:
• The exports is an object. So, you can attach properties or methods to it. The
following example exposes an object with a string property in Message.js file.
Message.js
exports.SimpleMessage = 'Hello world';
//or

module.exports.SimpleMessage = 'Hello world';


• In the above example, property SimpleMessage is attached to the exports
object. Now, we can import and use this module, as shown below.
App.js
var msg = require('./Messages.js');
console.log(msg.SimpleMessage);
• The require() function in App.js will return an
object { SimpleMessage : 'Hello World'} and assign it to the msg
variable. So, now you can use msg.SimpleMessage.

• Run the above example by writing node app.js in the command


prompt and see the output as shown below.

• C:\> node app.js


Hello World
Log Function As A Module
Log.js
module.exports.log = function (msg) {
console.log(msg);
};
The above module expose an object {log:function(msg){console.log(msg);}}
We can use the above module as shown below
App.js
var msg = require('./Log.js');
msg.log('Hello World');
Output
C:\> node app.js
Hello World
● File System:Synchronously
Asynchronously

• The Node.js file system module allows you to work with the file system
on your computer. All the File Interactions can be done using two ways
– Synchronously
– Asynchronously
Asynchronously:
• To read files fs module has open function.
• open function takes three parameters
• Filename String
• Flag ‘w’ to write and ‘r’ to read
• Callback function
• The specified file is opened for read or write if the file does not exist an
empty file is created.
• Syntax: fs.open(‘filename’, ‘r/w’, function(err, data) {});
Read files Asynchronously:
• To read files fs module has readFile function.
• readFile function takes two parameters
– Filename String
– Callback function
• The specified name of the file is read once it’s done call back
function is called
• Syntax:
fs.readFile(‘filename’, function(err, data) {});
fs.readFile( filename, encoding, callback_function)

● filename: It holds the path to the file which has to be read.


● encoding: It holds the encoding of the file. If no option is specified, then the raw
buffer is returned, Default value is ‘utf8’.
● callback_function: It is a function that gets called after reading the file and
contains two parameters err and data. If any error is encountered then it gets
stored in err else content of the file is stored in data.

Return Value: It returns the content of a file.


*Write files Asynchronously:
• To update files fs module has writeFile function.
• It takes three parameters
– Filename String
– Content to be written
– Callback function
• The specified file is written and then the call back function is called.
• Syntax:
fs.writeFile (‘filename’, ‘Datum’, function(err, data) {});
Delete File Asynchronously:
• To delete files fs module has unlink function.
•Both function takes two parameters
–Filename String
–Callback function
•The specified file is deleted and then the call back function is
called.
•Syntax:
fs.unlink (‘filename’, function(err, data) {});
* 1.Program to Write the content to a
file(Asynchronously)
const fs = require('fs')
const content = 'Some content!'
fs.writeFile('/Users/joe/test.txt', content, err => {
if (err) {
console.error(err)
return
}
})
Synchronously
Read Files Synchronously:
•To read files fs module has readFileSync function.
•readFileSync function takes two parameters
–Filename String
–Encoding
•The specified name of the file is read once it’s done the data in
the file is returned.
•Syntax:
fs.readFileSync(‘filename’,’utf-8’);
Write Files Synchronously:
•To write files fs module has writeFileSync function.
•writeFileSync function takes two parameters
–Filename String
–Data
•Data is written into the specified file. Once its done it continues
execution.
•Syntax:
fs.writeFileSync(‘filename’,data);
Delete Files Synchronously:
•To write files fs module has unlinkSync function.
•unlinkSync function takes one parameter
•Path
•The file specified by the path gets deleted.
•Syntax:
fs.unlinkSync(path);
Writing to a file(synchronously):
const fs =require('fs')
const content ='Some content!‘
try{
const data = fs.writeFileSync('/Users/joe/test.txt',content)
//file written successfully
}
catch(err)
{
console.error(err)
}
Node.js Third Party Modules
● Node 3rd party modules is a module or package which is developed and manitained by 3rd
parties.
● Millions of 3rd party node modules/packages which are freely available on NPM Registry.
● You can install node 3rd party modules/packages and use them to add functionality to your
projects.
● Node 3rd party modules can be installed using NPM (Node Package Manager).

Install and Use Node 3rd Party Modules:

Node 3rd party modules can be installed using node package manager (npm).
Install Module
npm install module_name

OR

npm i module_name

//some examples
npm i express
npm i mongoose
npm i axios

//multiple modules at once


npm i express mongoose axios
Events” module provided by Node.js

Events” module provided by Node.js, which consists of the “EventEmitter” class that enables us to implement event-
driven programming

How do Events work in Node.js?


Node.js events follow the below concepts:

1. Since Node.js applications are event-driven, the events are triggered on its associated event handler.

2. An event handler is nothing but a callback function called when an event is triggered.

3. The main loop listens to the event triggers and then calls the corresponding event handler.
The EventEmitter class calls all the events synchronously in the order that they were registered. It ensures the proper
sequencing of events and helps us avoid logic errors. When in need, we can switch to asynchronous
One of the methods which fire an event is known as emit() that belongs to the EventEmitter class. The
emit() method has the first argument as the name of the event and the next arguments are used to pass
data

The on() method listens to the event that is emitted and executes it.
Events in Node.js
•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:
Example
•var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () { //fires the event ‘open’
console.log('The file is open');
});
Output
C:\Users\My Name>node demo_events_open.js
The file is open
fs.createReadStream(path, options)

Parameters:

● path: It holds the path to the file which has to be read. It could be the string, URL of the
buffer.
● options: It is an optional parameter. We can pass a string or object to it.
● Return Value: It returns the object of ReadObject Stream.

Example: In this example, We are reading file name by createReadStream.on method.


Events in Node.js
Events Module
•Node.js has a built-in module, called "Events", where you
can create-, fire-, and listen for- your 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.
EventEmitter is a class that helps us create a publisher-
subscriber pattern in NodeJS. With an event emitter, we can
simply raise a new event from a different part of an application,
and a listener will listen to the raised event and have some
action performed for the event.
To be able to access these properties and methods, create an
EventEmitter object:
var events = require('events');
var eventEmitter = new events.EventEmitter();
Listening for events
Events listeners can be added using the on() method which takes two
arguments:

1. The event name to listen for


2. A callback function which defines the action to take. The
arguments passed to the callback are event dependent.
* EventEmitter Object
•You can assign event handlers to your own events with the EventEmitter
object.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 eventhandler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');
Output:
C:\Users\My Name>node demo_eventemitter.js
I hear a scream!
Methods
1 addListener(event, listener)
Adds a listener at the end of the listeners array for the specified event. No checks are made
to see if the listener has already been added.

2 on(event, listener)
Adds a listener at the end of the listeners array for the specified event. No checks are made
to see if the listener has already been added.

3 once(event, listener)
Adds a one time listener to the event. This listener is invoked only the next time the event is
fired, after which it is removed. Returns emitter, so calls can be chained.

4 removeListener(event, listener)
Removes a listener from the listener array for the specified event. Caution − It changes the
array indices in the listener array behind the listener.

5 removeAllListeners([event])
Removes all listeners, or those of the specified event.

6 emit(event, [arg1], [arg2], [...])


Execute each of the listeners in order with the supplied arguments. Returns true if the event
had listeners, false otherwise.
Emitting Name events
An emitter object basically has two main features:
•Emitting name events.
•Registering and unregistering listener functions.
Example-1 :
const myEmitter =newEventEmitter();
functionc1(){
console.log('an event occurred!');
}
functionc2(){
console.log('yet another event occurred!');
}
myEmitter.on('eventOne', c1);// Register for eventOne
myEmitter.on('eventOne', c2);// Register for eventOne
//When the event ‘eventOne’ is emitted ,both the above callbacks should be invoked.
myEmitter.emit(eventOne’) //Emiiting name event (eventOne)
The output in the console will be as follows
An event occurred !
Yet another event occurred !
Registering and unregistering listener
functions
Registering for the event to be fired only one time using once.
•myEmitter.once('eventOnce', () => console.log('eventOnce once
fired'));
Emitting the event ‘eventOnce’:
•myEmitter.emit('eventOne');
output should appear in the console:eventOnce once fired
note:Emitting events registered with once again will have no
impact
•myEmitter.emit(‘eventOne’);
Since the event was only emitted once, the above statement will
have no impact.
Registering an event Once
1. varEventEmitter = require('events').EventEmitter;

varemitter = newEventEmitter();

emitter.once('foo', function () { //here Registering an event Once

console.log('foo has been raised'); });

// Emit twice

emitter.emit('foo');

emitter.emit('foo');

Output

foo has been raised


2a.
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
emitter.on('foo', function a() { });
emitter.on('foo', function b() { });
console.log(emitter.listeners('foo'));
// [ [Function: a], [Function: b]]

2b .
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var fooHandler = function ()
{ console.log('handler called');

// Unsubscribe

emitter.removeListener('foo',fooHandler);
};
2b-continued

emitter.on('foo', fooHandler);
// Emit twice
emitter.emit('foo');
emitter.emit('foo');
Output:
handler called
3.//Multiple Subscribers
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
emitter.on('foo', function ()
{
console.log('subscriber 1');
});
emitter.on('foo', function ()
{
console.log('subscriber 2');
});
emitter.emit('foo');
output:
subscriber 1
subscriber 2
Unregistering events : The removeListener/off

The removeListener function can be used to stop event listener


functions from listening to events. This takes two arguments: The first
is a string that represents the event name, the second is the function that
you want to stop using to listen to events.
Unregistering events
•myEmitter.off('eventOne', c1);
•Now if you emit the event as follows, nothing will happen and it
will be a no-op:
•myEmitter.emit('eventOne');// no-op
Getting Listener count
•console.log(myEmitter.listenerCount('eventOne'));
•NOTE: If the event has been unregistered using off or
removeListener method, then the count will be 0.
On ,Remove ,and Emit
// Importing events
const EventEmitter = require('events');

// Initializing event emitter instances


var eventEmitter = new EventEmitter();

var e1= (msg) => {


console.log("Message from e1: " + msg);
};

var e2 = (msg) => {


console.log("Message from e2: " + msg);
};
// Registering e1 and e2
eventEmitter.on('myEvent', e1);
eventEmitter.on('myEvent', e1);
eventEmitter.on('myEvent', e2);
// Removing listener e1 that was
// registered on the line 13
eventEmitter.removeListener('myEvent', e1);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
// Removing all the listeners to myEvent
eventEmitter.removeAllListeners('myEvent');
// Triggering myEvent
eventEmitter.emit('myEvent', "Event is it occurring");

Output:

Message from e1: Event occurred


Message from e2: Event occurred
Error Handling
•If the EventEmitter doesn’t have at least one error event listener register and an error
is emitted, the error is thrown, and the stack trace of the error will be printed, and the
process will exit. For example, if we have the following code:
const EventEmitter = require('events');
class Emitter extends EventEmitter {}
const eventEmitter = new Emitter();
eventEmitter.emit('error', new Error('Error occured'));
Then we get something like this and the program exits:
Error [Err_UNHANDLED_ERROR]:Unhandled error.
(Error:Error occurred
at evalmachine.<anonymous>:5:28
at Script.runInContext (vm.js:133:20)
•To prevent the Node.js program from crashing, we can listen to the error
event with a new event listener and handle the error gracefully in the
error event handler.
For example, we can write:
const EventEmitter = require(‘events’);
class Emitter extends EventEmitter {}
const eventEmitter =new Emitter();
eventEmitter.on (‘error’,(error) =>
{
Console.log(‘Error occurred’);
});
eventEmitter.emit(‘error’,newError(‘Error occurred ‘));
We will get something like this: for the previous slide program
•Error: Error occurred
•at evalmachine.<anonymous>:7:28
•at Script.runInContext (vm.js:133:20)

This a Visual Diagram1 showing Methods in our Event


Emitter- for you reference
Different ways to Deal with Events
•Node.js will emit one special event without writing any code to emit
the event: The newListener .
•The newListener event is emitted before a listener is added to the
internal array of listeners.
•The removeListener function can be used to stop event listener
functions from listening to events. This takes two arguments: The first
is a string that represents the event name, the second is the function that
you want to stop using to listen to events.
Custom Emitter
•The events.EventEmitter.call(this); invokes the events.EventEmitter constructor
so that it gets executed whenever a new equal to //super() in other languages.
•util.inherits is a function of Node.js that is in the util module where the constructor
inherits the prototype methods from one to another.
•To access the util.inherit function, the util module needs to be accessed, as shown
below.
const util = require('util');
Syntax
•util.inherits(constructor, superConstructor)
Parameters
•constructor: The function that the programmer wants to be inherited from the class.
•superConstructor: A function that is primarily used for adding/inheriting input
validation.
Database Connectivity

Install mongodb
https://treehouse.github.io/installation-guides/mac/mongo-mac.html
or
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
or(via cloud)
https://www.mongodb.com/nodejs-database
online resources
https://www.w3schools.com/nodejs/nodejs_mongodb.asp
Database Connectivity(Mongo DB)
Structuring Document Data
MongoDB documents are formatted in BSON (an extended Binary form of JSON)
, which allows you ultimate flexibility in structuring data of all types. Below are
just a few of the ways you can structure your documents.

Using the MongoDB Shell


The MongoDB shell is a great tool for navigating, inspecting, and even manipulating
document data. If you’re running MongoDB on your local machine, firing up the shell
is as simple as typing mongo and hitting enter, which will connect to MongoDB at
localhost on the standard port (27017).
● Go to http://www.mongodb.org, then download and install MongoDB as per the instructions given there.
● Create a folder named mongodb on your computer and create a subfolder under it named data.
● Move to the mongodb folder in terminal and then start the MongoDB server by typing the following
at the prompt:
mongod --dbpath=data --bind_ip 127.0.0.1
if you want to know the version at the terminal type : npm list mongodb

● Open another command window and then type the following at the command prompt to start the mongo REPL
shell
> mongo

● The Mongo REPL shell will start running and give you a prompt to issue commands to the MongoDB server.
● The Mongo REPL shell will start running and give you a prompt to issue commands to the MongoDB server. At the
Mongo REPL prompt, type the following commands one by one and see the resulting behavior:
db
use conFusion
db
db.help()
● You will now create a collection named dishes, and insert a new dish document in the collection:
>db.dishes.insert({ name: "John", description: "Test" });

● Then to print out the dishes in the collection, type:


> db.dishes.find().pretty();

//Note the "_id" assigned to the dish.


● //Next, we will learn the information encoded into the ObjectId by typing the following at the prompt:
>var id = new ObjectId();
>id.getTimestamp();

Type "exit" at the REPL prompt to exit the Mongo REPL


Here are a few more quick shell examples:

//List Databases
>show dbs
Admin 0.000GB
Config 0.000GB
Local 0.000GB
My_database 0.004GB

//List Collections
> use my_database;
> show collections
users
posts
>

//Count Documents in a Collection


>use my_database;
>db.users.count()
20234
>
Find the First Document in a Collection > db.users.findOne(){
“_id”: ObjectId(“5ce45d7606444f199acfba1e”)
“name” : {given:”Alex”,family:”Smith”},
“email”: [email protected]
“age”:27
}
>

Find a Document by ID
>db.users.findone({_id:objectId(“5ce45d7606444f199acfba1e”)})
{
“_id”: ObjectId(“5ce45d7606444f199acfba1e”),
“name” : { given : “Alex”,family :”Smith”},
“email” : [email protected],
“age”:27
}
>
Find a Limited Number of Results

> db.users.find().limit(10)
>

Find Users by Family name

Db.users.find{“name.family”: “smith”}).count()
1
>

Note that we enclose “name.family” in quotes, because it has a dot in the middle.

You might also like