FSD Node - Js Module 4
FSD Node - Js Module 4
Presentation Material
Faculty Name:
Node JS
url url module includes methods for URL resolution and parsing.
•
Example 1:
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);
Method Description
debuglog() Writes debug messages to the error object
inspect() Inspects the specified object and returns the object as a string
// Node.js util.format() demo Example
function fun1() {
var val1 = util.format('%s:%s:%s', 'tutorialsPoint');
// Function call
util.isArray(object) #
Returns true if the given "object" is an Array. false otherwise.
• 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 File System module has methods for creating new files:
1. fs.appendFile()
2. fs.open()
3. fs.writeFile()
• Example(Delete "mynewfile2.txt")
• var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Rename Files
• var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
Node.js Local Module
• 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)
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
Events” module provided by Node.js, which consists of the “EventEmitter” class that enables us to implement event-
driven programming
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.
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.
varemitter = newEventEmitter();
// Emit twice
emitter.emit('foo');
emitter.emit('foo');
Output
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
Output:
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.
● 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" });
//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
>
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)
>
Db.users.find{“name.family”: “smith”}).count()
1
>
Note that we enclose “name.family” in quotes, because it has a dot in the middle.