More Related Content Similar to Node.js Crash Course (Jump Start) (20) More from Haim Michael (20) Node.js Crash Course (Jump Start) 1. Node.js Jump Start
Haim Michael
June 2nd
, 2020
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
2. © 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Snowboarding. Learning. Coding. Teaching. More
than 18 years of Practical Experience.
lifemichael
3. © 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Professional Certifications
Zend Certified Engineer in PHP
Certified Java Professional
Certified Java EE Web Component Developer
OMG Certified UML Professional
● MBA (cum laude) from Tel-Aviv University
Information Systems Management
lifemichael
5. 06/02/20 © abelski 5
What is Node.js?
The node.js platform allows us to execute code in
JavaScript outside of the web browser, which allows us to
use this platform for developing web applications excellent
in their performance.
The node.js platform is based on JavaScript v8. We use the
JavaScript language.
6. 06/02/20 © abelski 6
Asynchronous Programming
Most of the functions in node.js are asynchronous ones. As
a result of that everything is executed in the background
(instead of blocking the thread).
7. 06/02/20 © abelski 7
The Module Architecture
The node.js platform uses the module architecture. It
simplifies the creation of complex applications.
Each module contains a set of related functions.
We use the require() function in order to include a module
we want to use.
8. 06/02/20 © abelski 8
We Do Everything
The node.js platform is the environment. It doesn't include
any default HTTP server.
9. 06/02/20 © abelski 9
Installing Node
Installing node.js on your desktop is very simple. You just
need to download the installation file and execute it.
www.nodejs.org
11. 06/02/20 © abelski 11
The node.js CLI
Once node.js is installed on your desktop you can easy start
using its CLI. Just open the terminal and type node for
getting the CLI.
13. 06/02/20 © abelski 13
Executing JavaScript Files
Using node.js CLI we can execute files that include code in
JavaScript. We just need to type node following with the
name of the file.
15. 06/02/20 © abelski 15
Node Package Manager
The Node Package Manager, AKA as NPM, allows us to
manage the packages installed on our computer.
NPM provides us with an online public registry service that
contains all the packages programmers publish using the
NPM.
The NPM provides us with a tool we can use for
downloading, installing the managing those packages.
16. 06/02/20 © abelski 16
Node Package Manager
As of Node.js 6 the NPM is installed as part of the node.js
installation.
The centralized repository of public modules that NPM
maintains is available for browsing at http://npmjs.org.
18. 06/02/20 © abelski 18
The npm Utility
There are two modes for using the node.js package
manager, also known as npm.
The local mode is the default one. In order to be in the
global mode we should add the -g flag when using the npm
command.
19. 06/02/20 © abelski 19
The npm Utility
Using npm in the local mode means that we get a copy of
the module on our desktop saved in a subfolder within our
current folder.
Using npm in the global mode the module file will be saved
together with all other modules that were fetched globally
inside /usr/local/lib/node_modules/.
20. 06/02/20 © abelski 20
The npm Utility
Let's assume we want to use the facebook module from the
npm repository. Typing npm install facebook will
download and install the facebook module into our platform
so from now on we will be able to use it.
22. 06/02/20 © abelski 22
Running HTTP Server on Our Desktop
We can easily set up on our desktop an up and running
HTTP server that runs a web application developed in
node.js.
We just need to write our code in a separated JavaScript file
and execute it.
23. 06/02/20 © abelski 23
Running HTTP Server on Our Desktop
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World!n');
});
server.listen(1400,'127.0.0.1');
26. 06/02/20 © abelski 26
Accessing The Query String
The url module allows us to access the query string. Calling
the parse method on the url module passing over req.url as
the first argument and true as the second one will get us an
object that its properties are the parameters the query string
includes. The keys are the parameters names. The values
are their values.
27. 06/02/20 © abelski 27
Accessing The Query String
var http = require('http');
var url = require('url') ;
http.createServer(function (req, res) {
//var area = req.query.width * req.query.height;
res.writeHead(200, {'Content-Type': 'text/plain'});
var queryObject = url.parse(req.url,true).query;
res.end('area is '+(queryObject.width*queryObject.height));
}).listen(1400, function(){console.log("listening in port 1400");});
29. 06/02/20 © abelski 29
The Loop
When Node.js starts, it first initializes the event loop and
then it starts with processing the input script.
30. 06/02/20 © abelski 30
The Loop
timers
This phase executes callbacks scheduled by
setTimeout() and setInterval().
pending callbacks
This phase executes I/O callbacks deferred to the next loop
iteration.
idle, prepare
This phase is been used internally only.
31. 06/02/20 © abelski 31
The Loop
poll
This phase retrieves new I/O events; execute I/O related
callbacks (almost all with the exception of close callbacks,
the ones scheduled by timers, and setImmediate()); node
will block here when appropriate.
check
This phase includes the invocation of setImmediate()
callbacks
32. 06/02/20 © abelski 32
The Loop
close
This phase is responsible for the invocation of close
callbacks (e.g. socket.on('close', …);).
34. © 2008 Haim Michael
What is MongoDB?
MongoDB is a flexible and a scalable document oriented
database that supports most of the useful features relational
databases have.
35. © 2008 Haim Michael
Document Oriented Database
The document concept is more flexible comparing with the
row concept we all know from relational databases. The
document model allows us to represent hierarchical
relationships with a single record.
36. © 2008 Haim Michael
Flexibility
Using MongoDB we don't need to set a schema. The
document's keys don't need to be predefined or fixed. This
feature allows us an easy migration of our application into
other platforms.
37. © 2008 Haim Michael
Scaling
When the amount of data grows there is a need in scaling up
(getting a stronger hardware) our data store or scaling out
(partition the data across more computers). MongoDB
document oriented data model allows us to automatically split
up the data across multiple servers. MongoDB handles most
of this process automatically.
38. © 2008 Haim Michael
Stored JavaScript
MongoDB allows us to use JavaScript functions as stored
procedures.
39. © 2008 Haim Michael
Speed
MongoDB uses a binary wire protocol as its primary mode of
interaction with the server, while other databases usually use
heavy protocols such as HTTP/REST.
In order to achieve high performance many of the well known
features from relational databases were taken away.
40. © 2008 Haim Michael
Simple Administration
In order to keep the MongoDB easy and simple to use its
administration was simplified and is much simpler comparing
with other databases.
When the master server goes down MongoDB automatically
failover to a backup slave and promote the slave to be the
master.
41. © 2008 Haim Michael
Documents
Document is a set of keys with associated values, such as a
map.
In JavaScript a document is represented as an object.
{“lecture“:“Haim Michael“, “topic“:“Scala Course“, “id“: 2345335321}
The values a document holds can be of different types. They
can even be other documents.
key value key value key value
42. © 2008 Haim Michael
The Keys
We cannot contain duplicate keys within the same document.
The keys are strings. These strings can include any UTF-8
character.
The '0' character cannot be part of a key. This character is in
use for separating keys from their values.
The '.' and the '$' characters have a special meaning
(explained later).
43. © 2008 Haim Michael
The Keys
Keys that start with '_' are considered reserved keys. We
should avoid creating keys that start with this character.
44. © 2008 Haim Michael
The Values
The values can be of several possible types. They can even
be other documents embedded into ours.
45. © 2008 Haim Michael
Case Sensitivity
MongoDB is a type sensitive and a case sensitive database.
Documents differ in any of those two aspects are considered
as different documents.
{“id“,123123} {“id“,”123123”}
These two documents are considered different!
46. © 2008 Haim Michael
Collection
Collection is a group of documents. We can analogue
documents to rows and collections to tables.
The collection is schema free. We can hold within the same
single collection any number of documents and each
document can be of a different structure.
{“id“:1423123}
{“hoby“:“jogging“,“gender“:“man“,“telephone“:“0546655837“}
{“country“:“canada“,“zip“:76733}
Valid Collection That Includes Three Maps
47. © 2008 Haim Michael
Separated Collections
Although we can place within the same collection documents
with different structure, each and every one of them with
different keys, different types of values and even different
number of key value pairs, there are still very good reasons
for creating separated collections.
48. © 2008 Haim Michael
Separated Collections
The separation into separated collections assists with keeping
the data organized, simpler to maintain and it speeds up our
applications allowing us to index our collections more
efficiently.
49. © 2008 Haim Michael
Collections Names
Each collection is identified by its name. The name can
include any UTF-8 character, with the following limits.
The collection name cannot include the '0' character (null).
The collection name cannot be an empty string (“”).
The collection name cannot start with “system”. It is a prefix
reserved for system collections.
50. © 2008 Haim Michael
Collections Names
The collection name cannot contain the '$' character. It is a
reserved character system collections use.
51. © 2008 Haim Michael
Sub Collections
We can organize our collections as sub collections by using
name-spaced sub-collections. We use the '.' character for
creating sub collections.
forum.users
forum.posts
forum.administrators
52. © 2008 Haim Michael
Databases
MongoDB groups collections into databases. Each MongoDB
installation can host as many databases as we want.
Each database is separated and independent.
Each database has its own permissions setting and each
database is stored in a separated file.
It is a common practice to set a separated database for each
application.
53. © 2008 Haim Michael
Databases
The database name cannot contain the following characters: '
' (single character space), '.', '$', '/', '', '0'.
The database name should include lower case letters only.
The length of the database name is limited to a maximum of
64 characters.
The following are reserved names for databases that already
exist and can be accessed directly: admin, local and
config.
54. © 2008 Haim Michael
Namespaces
When prepending a collection name with the name of its
containing database we will get a fully qualified collection
name, also known as a namespace.
Let's assume we have the abelski database and it includes the posts collection.
The abelski.posts is a namespace.
The length of each namespace is limited to 121 characters.
55. © 2008 Haim Michael
Downloading MongoDB
You can download the latest version of MongoDB at
www.mongodb.com.
56. © 2008 Haim Michael
Starting MongoDB
Within the bin folder you should expect to find various utilities
for working with MongoDB.
Before we start the MongoDB server we first need to create
the folder where MongoDB will save the data. By default,
MongoDB will store the data within c:datadb. We must
create this folder in advance. MongoDB won't do that for us.
The mongod.exe utility starts the MongoDB server. The
mongo.exe utility starts the MongoDB client shell.
57. © 2008 Haim Michael
Starting MongoDB
The MongoDB assumes the folder where all data should be
saved is c:datadb. You should create that folder in
advance before you run the MongoDB server. We can create
another folder and set it as the data folder instead of the
default one.
Once the MongoDB server is up and running we can start the
MongoDB shell command by executing the mongo.exe utility.
59. © Haim Michael
What is Mongoose.js?
Mongoose.js is a JavaScript library that provides us with
an object oriented interface for using the MongoDB in
our node.js web applications.
www.mongoosejs.com
61. © Haim Michael
Mongoose.js Popularity
You can find a collection of projects that were developed
using mongoose.js at http://mongoosejs.tumblr.com.
63. © Haim Michael
Installing Mongoose
In order to install mongoose you first need to have
node.js platform already installed.
Using the npm utility you can easily get the mongoose
module available on your desktop.
65. © Haim Michael
Connecting MongoDB
Calling the connect method on the mongoose object we
will get a connection with an up and running mongodb
server.
mongoose.connect('mongodb://localhost/test');
Referring the connection property in the mongoose
object we will get the connection object itself.
var db = mongoose.connection;
66. © Haim Michael
Handling Connection Events
Calling the on method on the connection object we can
handle its various related events.
The first argument should be the event name. The
second argument should be the function we want to be
invoked when the event takes place.
Passing over error as the first argument we can handle
connection errors.
db.on('error', function() {console.log("error")});
67. © Haim Michael
Handling Connection Events
We shall write our code within the function we pass over
to be invoked when the open event takes place.
db.once('open', function () { ... });
68. © Haim Michael
Code Sample
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {console.log("error")});
db.once('open', function () {
console.log("connected!");
var productSchema = mongoose.Schema(
{id:Number, name: String});
productSchema.methods.printDetails = function() {
var str = "id=" + this.id + " name="+this.name;
console.log(str);
};
var Product = mongoose.model('products',productSchema);
69. © Haim Michael
Code Sample
var carpeta = new Product({id:123123,name:'carpetax'});
var tabola = new Product({id:432343,name:'Tabolala'});
carpeta.save(function(error,prod) {
if(error) {
console.log(error);
}
else {
console.log("carpeta was saved to mongodb");
carpeta.printDetails();
}
});
70. © Haim Michael
Code Sample
tabola.save(function(error,prod) {
if(error) {
console.log(error);
}
else {
console.log("tabola was saved to mongodb");
tabola.printDetails();
}
});
Product.find(function(error,products) {
if(error) {
console.log(error);
}
else {
console.log(products);
}
});
});
72. © 2009 Haim Michael All Rights Reserved 72
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
lifemichael