SlideShare a Scribd company logo
1 of 72
Download to read offline
Node.js Crash Course
Haim Michael
October 4th
, 2018
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
lifemichael
Part 1:
https://youtu.be/fnwdm4yob2o
Part 2:
https://youtu.be/OWCDm5_RbRQ
© 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
10/04/18 © 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.
10/04/18 © 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).
10/04/18 © 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.
10/04/18 © abelski 8
We Do Everything
 The node.js platform is the environment. It doesn't include
any default HTTP server.
10/04/18 © 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/04/18 © abelski 10
Installing Node
10/04/18 © 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.
10/04/18 © abelski 12
The node.js CLI
10/04/18 © 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.
10/04/18 © abelski 14
Executing JavaScript Files
10/04/18 © 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.
10/04/18 © 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.
10/04/18 © abelski 17
Node Package Manager
10/04/18 © 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.
10/04/18 © 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/.
10/04/18 © 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.
10/04/18 © abelski 21
The npm Utility
10/04/18 © 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.
10/04/18 © 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');
10/04/18 © abelski 24
Running HTTP Server on Our Desktop
© 2008 Haim Michael 20150805
Query String
10/04/18 © 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.
10/04/18 © 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
10/04/18 © abelski 29
The Loop
 When Node.js starts, it first initializes the event loop and
then it starts with processing the input script.
10/04/18 © 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.
10/04/18 © 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
10/04/18 © 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

What's hot (20)

Express js
Express jsExpress js
Express js
 
Node js
Node jsNode js
Node js
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Nodejs vatsal shah
Nodejs vatsal shahNodejs vatsal shah
Nodejs vatsal shah
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
In the DOM, no one will hear you scream
In the DOM, no one will hear you screamIn the DOM, no one will hear you scream
In the DOM, no one will hear you scream
 
Express JS
Express JSExpress JS
Express JS
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML Apocalypse
 
Json
JsonJson
Json
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
jQuery
jQueryjQuery
jQuery
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Formation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-dataFormation jpa-hibernate-spring-data
Formation jpa-hibernate-spring-data
 
Nodejs
NodejsNodejs
Nodejs
 

Similar to Node JS Crash Course (20)

Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 
NodeJS
NodeJSNodeJS
NodeJS
 
Nodejs
NodejsNodejs
Nodejs
 
Node.js primer for ITE students
Node.js primer for ITE studentsNode.js primer for ITE students
Node.js primer for ITE students
 
Future of Serverless
Future of ServerlessFuture of Serverless
Future of Serverless
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
Basic API Creation with Node.JS
Basic API Creation with Node.JSBasic API Creation with Node.JS
Basic API Creation with Node.JS
 
An introduction to Node.js application development
An introduction to Node.js application developmentAn introduction to Node.js application development
An introduction to Node.js application development
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.js
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Node J pdf.docx
Node J pdf.docxNode J pdf.docx
Node J pdf.docx
 
Node J pdf.docx
Node J pdf.docxNode J pdf.docx
Node J pdf.docx
 
Sst hackathon express
Sst hackathon expressSst hackathon express
Sst hackathon express
 
Polymer Web Framework - Swecha Boot Camp
Polymer Web Framework - Swecha Boot CampPolymer Web Framework - Swecha Boot Camp
Polymer Web Framework - Swecha Boot Camp
 
Node js
Node jsNode js
Node js
 
Proposal
ProposalProposal
Proposal
 

More from Haim Michael

Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in JavaHaim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design PatternsHaim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL InjectionsHaim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in JavaHaim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design PatternsHaim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in PythonHaim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in PythonHaim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScriptHaim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump StartHaim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHPHaim Michael
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9Haim Michael
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on SteroidHaim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728Haim Michael
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]Haim Michael
 

More from Haim Michael (20)

Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

Node JS Crash Course

  • 1. Node.js Crash Course Haim Michael October 4th , 2018 All logos, trade marks and brand names used in this presentation belong to the respective owners. lifemichael Part 1: https://youtu.be/fnwdm4yob2o Part 2: https://youtu.be/OWCDm5_RbRQ
  • 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. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © abelski 8 We Do Everything  The node.js platform is the environment. It doesn't include any default HTTP server.
  • 9. 10/04/18 © 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. 10/04/18 © abelski 10 Installing Node
  • 11. 10/04/18 © 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. 10/04/18 © abelski 12 The node.js CLI
  • 13. 10/04/18 © 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. 10/04/18 © abelski 14 Executing JavaScript Files
  • 15. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © abelski 17 Node Package Manager
  • 18. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © abelski 21 The npm Utility
  • 22. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © abelski 24 Running HTTP Server on Our Desktop
  • 25. © 2008 Haim Michael 20150805 Query String
  • 26. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © abelski 29 The Loop  When Node.js starts, it first initializes the event loop and then it starts with processing the input script.
  • 30. 10/04/18 © 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. 10/04/18 © 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. 10/04/18 © 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 haim.michael@lifemichael.com +972+3+3726013 ext:700 lifemichael