SlideShare a Scribd company logo
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
© 1996-2018 All Rights Reserved.
Haim Michael Introduction
● Snowboarding. Learning. Coding. Teaching. More
than 18 years of Practical Experience.
lifemichael
© 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
© 2008 Haim Michael 20150805
Introduction
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.
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).
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.
06/02/20 © abelski 8
We Do Everything
 The node.js platform is the environment. It doesn't include
any default HTTP server.
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
06/02/20 © abelski 10
Installing Node
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.
06/02/20 © abelski 12
The node.js CLI
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.
06/02/20 © abelski 14
Executing JavaScript Files
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.
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.
06/02/20 © abelski 17
Node Package Manager
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.
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/.
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.
06/02/20 © abelski 21
The npm Utility
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.
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');
06/02/20 © abelski 24
Running HTTP Server on Our Desktop
© 2008 Haim Michael 20150805
Query String
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.
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");});
© 2008 Haim Michael 20150805
Event Loop
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.
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.
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
06/02/20 © abelski 32
The Loop
 close
This phase is responsible for the invocation of close
callbacks (e.g. socket.on('close', …);).
© 2008 Haim Michael 20150805
MongoDB
© 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.
© 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.
© 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.
© 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.
© 2008 Haim Michael
Stored JavaScript
 MongoDB allows us to use JavaScript functions as stored
procedures.
© 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.
© 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.
© 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
© 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).
© 2008 Haim Michael
The Keys
 Keys that start with '_' are considered reserved keys. We
should avoid creating keys that start with this character.
© 2008 Haim Michael
The Values
 The values can be of several possible types. They can even
be other documents embedded into ours.
© 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!
© 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
© 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.
© 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.
© 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.
© 2008 Haim Michael
Collections Names
 The collection name cannot contain the '$' character. It is a
reserved character system collections use.
© 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
© 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.
© 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.
© 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.
© 2008 Haim Michael
Downloading MongoDB
 You can download the latest version of MongoDB at
www.mongodb.com.
© 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.
© 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.
© 2008 Haim Michael
Starting MongoDB
© 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
© Haim Michael
What is Mongoose.js?
© Haim Michael
Mongoose.js Popularity
 You can find a collection of projects that were developed
using mongoose.js at http://mongoosejs.tumblr.com.
© Haim Michael
Mongoose.js Popularity
© 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.
© Haim Michael
Installing Mongoose
© 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;
© 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")});
© 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 () { ... });
© 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);
© 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();
}
});
© 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);
}
});
});
© Haim Michael
Code Sample
© 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

More Related Content

What's hot (20)

PPTX
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
PPTX
JavaScript DOM - Dynamic interactive Code
Laurence Svekis ✔
 
PDF
Web components the future is here
Gil Fink
 
PPTX
JavaScript Performance (at SFJS)
Steve Souders
 
PDF
Data presentation with dust js technologies backing linkedin
Ruhaim Izmeth
 
PDF
Bootstrap Jump Start
Haim Michael
 
PDF
Hybrid App using WordPress
Haim Michael
 
PPTX
Java script session 3
Saif Ullah Dar
 
PDF
Why and How to Use Virtual DOM
Daiwei Lu
 
PPT
Node.js an introduction
Meraj Khattak
 
PDF
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
PDF
JAVA SCRIPT
Mohammed Hussein
 
DOC
Java script by Act Academy
actanimation
 
PDF
Node js projects
💾 Radek Fabisiak
 
PDF
Node.js Jump Start
Haim Michael
 
PPT
Top java script frameworks ppt
Omkarsoft Bangalore
 
PPTX
Node js crash course session 1
Abdul Rahman Masri Attal
 
PPT
Java Script
siddaram
 
PDF
The Complementarity of React and Web Components
Andrew Rota
 
PDF
Web components
Gil Fink
 
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
JavaScript DOM - Dynamic interactive Code
Laurence Svekis ✔
 
Web components the future is here
Gil Fink
 
JavaScript Performance (at SFJS)
Steve Souders
 
Data presentation with dust js technologies backing linkedin
Ruhaim Izmeth
 
Bootstrap Jump Start
Haim Michael
 
Hybrid App using WordPress
Haim Michael
 
Java script session 3
Saif Ullah Dar
 
Why and How to Use Virtual DOM
Daiwei Lu
 
Node.js an introduction
Meraj Khattak
 
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
JAVA SCRIPT
Mohammed Hussein
 
Java script by Act Academy
actanimation
 
Node js projects
💾 Radek Fabisiak
 
Node.js Jump Start
Haim Michael
 
Top java script frameworks ppt
Omkarsoft Bangalore
 
Node js crash course session 1
Abdul Rahman Masri Attal
 
Java Script
siddaram
 
The Complementarity of React and Web Components
Andrew Rota
 
Web components
Gil Fink
 

Similar to Node.js Crash Course (Jump Start) (20)

PDF
Node JS Crash Course
Haim Michael
 
PPTX
Introduction to Node.js
Winston Hsieh
 
PPTX
Intro To Node.js
Chris Cowan
 
PPTX
Intro to node and mongodb 1
Mohammad Qureshi
 
PPTX
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PPTX
NodeJS guide for beginners
Enoch Joshua
 
PPTX
Introduction to node.js
Md. Sohel Rana
 
PDF
Node Up And Running Scalable Serverside Code With Javascript 1st Edition Tom ...
nunleyagika
 
PDF
What is Node.js? (ICON UK)
Tim Davis
 
PDF
An introduction to Node.js
Kasey McCurdy
 
PDF
🚀 Node.js Simplified – A Visual Guide for Beginners!
Tpoint Tech Blog
 
PDF
NodeJS for Beginner
Apaichon Punopas
 
PDF
Download full ebook of Learning Node Shelley Powers instant download pdf
zeitsloyerqy
 
PPTX
An overview of node.js
valuebound
 
PDF
Nodejs vatsal shah
Vatsal N Shah
 
PPTX
Nodejs
Vinod Kumar Marupu
 
PDF
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
PDF
Getting started with node JS
Hamdi Hmidi
 
PPTX
Building Applications With the MEAN Stack
Nir Noy
 
Node JS Crash Course
Haim Michael
 
Introduction to Node.js
Winston Hsieh
 
Intro To Node.js
Chris Cowan
 
Intro to node and mongodb 1
Mohammad Qureshi
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Practical Use of MongoDB for Node.js
async_io
 
NodeJS guide for beginners
Enoch Joshua
 
Introduction to node.js
Md. Sohel Rana
 
Node Up And Running Scalable Serverside Code With Javascript 1st Edition Tom ...
nunleyagika
 
What is Node.js? (ICON UK)
Tim Davis
 
An introduction to Node.js
Kasey McCurdy
 
🚀 Node.js Simplified – A Visual Guide for Beginners!
Tpoint Tech Blog
 
NodeJS for Beginner
Apaichon Punopas
 
Download full ebook of Learning Node Shelley Powers instant download pdf
zeitsloyerqy
 
An overview of node.js
valuebound
 
Nodejs vatsal shah
Vatsal N Shah
 
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
Getting started with node JS
Hamdi Hmidi
 
Building Applications With the MEAN Stack
Nir Noy
 
Ad

More from Haim Michael (20)

PDF
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
PDF
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
PDF
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
PDF
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
PDF
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
PDF
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
PDF
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
PDF
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
PDF
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
PDF
Anti Patterns
Haim Michael
 
PDF
Virtual Threads in Java
Haim Michael
 
PDF
MongoDB Design Patterns
Haim Michael
 
PDF
Introduction to SQL Injections
Haim Michael
 
PDF
Record Classes in Java
Haim Michael
 
PDF
Microservices Design Patterns
Haim Michael
 
PDF
Structural Pattern Matching in Python
Haim Michael
 
PDF
Unit Testing in Python
Haim Michael
 
PDF
OOP Best Practices in JavaScript
Haim Michael
 
PDF
Java Jump Start
Haim Michael
 
PDF
What is new in PHP
Haim Michael
 
The Visitor Classic Design Pattern [Free Meetup]
Haim Michael
 
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Anti Patterns
Haim Michael
 
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
Haim Michael
 
Java Jump Start
Haim Michael
 
What is new in PHP
Haim Michael
 
Ad

Recently uploaded (20)

PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 

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
  • 4. © 2008 Haim Michael 20150805 Introduction
  • 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
  • 10. 06/02/20 © abelski 10 Installing Node
  • 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.
  • 12. 06/02/20 © abelski 12 The node.js 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.
  • 14. 06/02/20 © abelski 14 Executing JavaScript Files
  • 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.
  • 17. 06/02/20 © abelski 17 Node Package Manager
  • 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.
  • 21. 06/02/20 © abelski 21 The npm Utility
  • 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');
  • 24. 06/02/20 © abelski 24 Running HTTP Server on Our Desktop
  • 25. © 2008 Haim Michael 20150805 Query String
  • 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");});
  • 28. © 2008 Haim Michael 20150805 Event Loop
  • 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', …);).
  • 33. © 2008 Haim Michael 20150805 MongoDB
  • 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.
  • 58. © 2008 Haim Michael Starting MongoDB
  • 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
  • 60. © Haim Michael What is Mongoose.js?
  • 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 [email protected] +972+3+3726013 ext:700 lifemichael