SlideShare a Scribd company logo
1 of 28
Download to read offline
Node.js
K e l u m S e n a n a y a k e
Introduction
History
• First published for Linux use in 2009
• Original author: Ryan Dahl
• npm, a package manager for Node.js libraries,
was introduced in 2011
• In June 2011, Microsoft partnered with Joyent
to create a native Windows version of Node.js
• Used by Groupon, SAP, LinkedIn, Microsoft,
Yahoo!, Walmart, Rakuten, PayPal, Voxer,
GoDaddy …
What is Node.js
• Node is a platform for JavaScript applications
• Node uses V8, the virtual machine that
powers Google Chrome
• Node is
– Built on JavaScript
– Evented and asynchronous
– DIRTy by default
Built on JavaScript
• JavaScript is the world’s most popular
programming language
• Developers can write web applications (client
& server) in one language
• JSON is a very popular data interchange
format today and is native to JavaScript
• JavaScript is the language used in various
NoSQL databases
Asynchronous and evented
• Node is event-driven (uses an event loop) and
non-blocking when handling I/O (uses
asynchronous I/O)
• Example blocking code from PHP
• In Node, I/O is almost always performed
outside of the main event loop, allowing the
server to stay efficient and responsive
$result = mysql_query('SELECT * FROM myTable');
print_r($result);
Designed for data-intensive real-
time applications
• DIRT : data-intensive real-time
• https://browserling.com/
• Node tries to keep consistency between the browser
and the server by re-implementing common host
objects:
– Timer API (for example, setTimeout)
– Console API (for example, console.log)
• Also includes a core set of modules for many types of
network and file I/O.
– HTTP, TLS, HTTPS, filesystem (POSIX), Datagram (UDP), and
NET (TCP).
• The core is intentionally small, low-level, and
uncomplicated, including just the building blocks for
I/O-based applications.
– Ex: HTTP parser consisting of roughly 1,500 lines of
optimized C code.
Hello World HTTP server
var http = require('http');
var server = http.createServer();
server.on('request', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
});
server.listen(3000);
console.log('Server running at http://localhost:3000/');
Organizing and reusing Node
functionality
Create Modules
• Modules can either be single files or
directories containing one or more files
• Create a file that defines properties on the
exports object with any kind of data, such
as strings, objects, and functions
currency.js
var singaporeDollar = 0.80;
function roundTwoDecimals(amount) {
return Math.round(amount * 100) / 100;
}
exports.singDollerToUS = function(singDoller) {
return roundTwoDecimals(singDoller *
singaporeDollar);
}
exports.USToSingDoller = function(us) {
return roundTwoDecimals(us / singaporeDollar);
}
test-currency.js
var currency = require('./currency');
console.log('50 Singapore dollars equals this amount
of US dollars:');
console.log(currency.singDollerToUS(50));
console.log('30 US dollars equals this amount of
Singapore dollars:');
console.log(currency.USToSingDoller(30));
currency-v2.js
module.exports = {
singDollerToUS : function(singDoller) {
return roundTwoDecimals(singDoller * singaporeDollar);
},
USToSingDoller : function(us) {
return roundTwoDecimals(us / singaporeDollar);
},
}
var singaporeDollar = 0.80;
function roundTwoDecimals(amount) {
return Math.round(amount * 100) / 100;
}
currency-v3.js
var Currency = function(singaporeDollar) {
this.singaporeDollar = singaporeDollar;
}
Currency.prototype.roundTwoDecimals = function(amount) {
return Math.round(amount * 100) / 100;
}
Currency.prototype.singDollerToUS = function(singDoller) {
return this.roundTwoDecimals(singDoller *
this.singaporeDollar);
}
Currency.prototype.USToSingDoller = function(us) {
return this.roundTwoDecimals(us / this.singaporeDollar);
}
module.exports = Currency;
var Currency = require('./currency-v3');
var singDollar = 0.80;
var currency = new Currency(singDollar);
console.log(currency. singDollerToUS(50));
Reusing modules using node_modules
• Useful for code you’d like to reuse between
applications or share with others
• Allows modules to be required without
knowing their location in the file system
Asynchronous programming
techniques
The two model of Async Processing
• Callbacks generally define logic for one-off
responses.
– Ex: perform a database query
• Event listeners, are essentially callbacks that
are associated with a conceptual entity (an
event).
– Respond to repeating events
– EX: HTTP server emits a request event when an
HTTP request is made
Handling one-off events with
callbacks
• A callback is a function, passed as an
argument to an asynchronous function
• It describes what to do after the asynchronous
operation has completed
var fs = require('fs');
fs.readFile('./resource.json', function (er, data) {
console.log(data);
});
Callback function
The Node convention for asynchronous
callbacks
• Most Node built-in modules use callbacks with
two arguments
– First argument is for an error, should one occur.
often abbreviated as er or err
– Second argument is for the results
var fs = require('fs');
fs.readFile('./titles.json', function(er, data) {
if (er) throw er;
// do something with data if no error has occurred
});
Handling repeating events with
event emitters
• Event emitters fire events and include the
ability to handle them when triggered
• Events are handled through the use of
listeners
• A listener is the association of an event with a
callback function that gets triggered each time
the event occurs
var net = require('net');
var server = net.createServer(function(socket) {
socket.on('data', function(data) {
socket.write(data);
});
});
server.listen(8888);
data events
handled
whenever
new data
has been
read
Using the on method to respond to events
Responding to an event that should only
occur once
var net = require('net');
var server = net.createServer(function(socket) {
socket.once ('data', function(data) {
socket.write(data);
});
});
server.listen(8888);
data event
will only
be handled
once
References
• [1] Mike Cantelon, Marc Harter, T.J. Holowaychuk and
Nathan Rajlich, Node.js in Action, 1st ed. Manning
Publications, 2014.
• [2] "Node.js - Wikipedia, the free encyclopedia."
[Online]. Available:
http://en.wikipedia.org/wiki/Node.js. [Accessed: 26-
Apr-2015].
Q & A

More Related Content

What's hot

Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeAndrus Adamchik
 
.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2aminmesbahi
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code firstMaxim Shaptala
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
NiFi - First approach
NiFi - First approachNiFi - First approach
NiFi - First approachMickael Cassy
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questionsArun Vasanth
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Designing a RESTful web service
Designing a RESTful web serviceDesigning a RESTful web service
Designing a RESTful web serviceFilip Blondeel
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database ConnectivityGary Yeh
 

What's hot (20)

Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
 
.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2
 
Hibernate
HibernateHibernate
Hibernate
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
 
Apache ActiveMQ
Apache ActiveMQApache ActiveMQ
Apache ActiveMQ
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Advance java1.1
Advance java1.1Advance java1.1
Advance java1.1
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
NiFi - First approach
NiFi - First approachNiFi - First approach
NiFi - First approach
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
24 collections framework interview questions
24 collections framework interview questions24 collections framework interview questions
24 collections framework interview questions
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
JDBC
JDBCJDBC
JDBC
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Designing a RESTful web service
Designing a RESTful web serviceDesigning a RESTful web service
Designing a RESTful web service
 
Hibernate
HibernateHibernate
Hibernate
 
Rest
RestRest
Rest
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
 

Viewers also liked

What you need to know about GC
What you need to know about GCWhat you need to know about GC
What you need to know about GCKelum Senanayake
 
Security Risks & Vulnerabilities in Skype
Security Risks & Vulnerabilities in SkypeSecurity Risks & Vulnerabilities in Skype
Security Risks & Vulnerabilities in SkypeKelum Senanayake
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionKelum Senanayake
 
A Searchable Symmetric Key Cipher System
A Searchable Symmetric Key Cipher SystemA Searchable Symmetric Key Cipher System
A Searchable Symmetric Key Cipher SystemKelum Senanayake
 
Attacking Turkish Texts Encrypted by Homophonic Cipher
Attacking Turkish Texts Encrypted by Homophonic CipherAttacking Turkish Texts Encrypted by Homophonic Cipher
Attacking Turkish Texts Encrypted by Homophonic CipherSefik Ilkin Serengil
 
Secure Data Sharing in Cloud (SDSC)
Secure Data Sharing in Cloud (SDSC)Secure Data Sharing in Cloud (SDSC)
Secure Data Sharing in Cloud (SDSC)Jishnu Pradeep
 
Analysis of Searchable Encryption
Analysis of Searchable EncryptionAnalysis of Searchable Encryption
Analysis of Searchable EncryptionNagendra Posani
 
Searchable Encryption Systems
Searchable Encryption SystemsSearchable Encryption Systems
Searchable Encryption SystemsChristopher Frenz
 
Discrete Logarithmic Problem- Basis of Elliptic Curve Cryptosystems
Discrete Logarithmic Problem- Basis of Elliptic Curve CryptosystemsDiscrete Logarithmic Problem- Basis of Elliptic Curve Cryptosystems
Discrete Logarithmic Problem- Basis of Elliptic Curve CryptosystemsNIT Sikkim
 
Search on encrypted data
Search on encrypted dataSearch on encrypted data
Search on encrypted dataSELASI OCANSEY
 
The NFS Version 4 Protocol
The NFS Version 4 ProtocolThe NFS Version 4 Protocol
The NFS Version 4 ProtocolKelum Senanayake
 
Usage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesUsage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesWilliam Lee
 

Viewers also liked (18)

What you need to know about GC
What you need to know about GCWhat you need to know about GC
What you need to know about GC
 
Security Risks & Vulnerabilities in Skype
Security Risks & Vulnerabilities in SkypeSecurity Risks & Vulnerabilities in Skype
Security Risks & Vulnerabilities in Skype
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 
Knight's Tour
Knight's TourKnight's Tour
Knight's Tour
 
A Searchable Symmetric Key Cipher System
A Searchable Symmetric Key Cipher SystemA Searchable Symmetric Key Cipher System
A Searchable Symmetric Key Cipher System
 
Attacking Turkish Texts Encrypted by Homophonic Cipher
Attacking Turkish Texts Encrypted by Homophonic CipherAttacking Turkish Texts Encrypted by Homophonic Cipher
Attacking Turkish Texts Encrypted by Homophonic Cipher
 
Searchable Encryption
Searchable EncryptionSearchable Encryption
Searchable Encryption
 
Gırgır sunum
Gırgır sunum Gırgır sunum
Gırgır sunum
 
Secure Data Sharing in Cloud (SDSC)
Secure Data Sharing in Cloud (SDSC)Secure Data Sharing in Cloud (SDSC)
Secure Data Sharing in Cloud (SDSC)
 
Analysis of Searchable Encryption
Analysis of Searchable EncryptionAnalysis of Searchable Encryption
Analysis of Searchable Encryption
 
Searchable Encryption Systems
Searchable Encryption SystemsSearchable Encryption Systems
Searchable Encryption Systems
 
Discrete Logarithmic Problem- Basis of Elliptic Curve Cryptosystems
Discrete Logarithmic Problem- Basis of Elliptic Curve CryptosystemsDiscrete Logarithmic Problem- Basis of Elliptic Curve Cryptosystems
Discrete Logarithmic Problem- Basis of Elliptic Curve Cryptosystems
 
How to Share a Secret
How to Share a SecretHow to Share a Secret
How to Share a Secret
 
Search on encrypted data
Search on encrypted dataSearch on encrypted data
Search on encrypted data
 
GPU Programming with Java
GPU Programming with JavaGPU Programming with Java
GPU Programming with Java
 
The NFS Version 4 Protocol
The NFS Version 4 ProtocolThe NFS Version 4 Protocol
The NFS Version 4 Protocol
 
Cloud security ppt
Cloud security pptCloud security ppt
Cloud security ppt
 
Usage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesUsage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP Languages
 

Similar to Node.js Introduction

Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami SayarFITC
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Lucas Jellema
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Lucas Jellema
 
4th Lecture: JSP and such
4th Lecture:  JSP and such4th Lecture:  JSP and such
4th Lecture: JSP and suchManolis Vavalis
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
Vert.x keynote for EclipseCon 2013
Vert.x keynote for EclipseCon 2013Vert.x keynote for EclipseCon 2013
Vert.x keynote for EclipseCon 2013timfox111
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 

Similar to Node.js Introduction (20)

Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
Exploring Node.jS
Exploring Node.jSExploring Node.jS
Exploring Node.jS
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Node.js for beginner
Node.js for beginnerNode.js for beginner
Node.js for beginner
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)
 
4th Lecture: JSP and such
4th Lecture:  JSP and such4th Lecture:  JSP and such
4th Lecture: JSP and such
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
Vert.x keynote for EclipseCon 2013
Vert.x keynote for EclipseCon 2013Vert.x keynote for EclipseCon 2013
Vert.x keynote for EclipseCon 2013
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 

Recently uploaded

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Node.js Introduction

  • 1. Node.js K e l u m S e n a n a y a k e
  • 3. History • First published for Linux use in 2009 • Original author: Ryan Dahl • npm, a package manager for Node.js libraries, was introduced in 2011 • In June 2011, Microsoft partnered with Joyent to create a native Windows version of Node.js • Used by Groupon, SAP, LinkedIn, Microsoft, Yahoo!, Walmart, Rakuten, PayPal, Voxer, GoDaddy …
  • 4.
  • 5. What is Node.js • Node is a platform for JavaScript applications • Node uses V8, the virtual machine that powers Google Chrome • Node is – Built on JavaScript – Evented and asynchronous – DIRTy by default
  • 6. Built on JavaScript • JavaScript is the world’s most popular programming language • Developers can write web applications (client & server) in one language • JSON is a very popular data interchange format today and is native to JavaScript • JavaScript is the language used in various NoSQL databases
  • 7. Asynchronous and evented • Node is event-driven (uses an event loop) and non-blocking when handling I/O (uses asynchronous I/O) • Example blocking code from PHP • In Node, I/O is almost always performed outside of the main event loop, allowing the server to stay efficient and responsive $result = mysql_query('SELECT * FROM myTable'); print_r($result);
  • 8.
  • 9. Designed for data-intensive real- time applications • DIRT : data-intensive real-time • https://browserling.com/
  • 10. • Node tries to keep consistency between the browser and the server by re-implementing common host objects: – Timer API (for example, setTimeout) – Console API (for example, console.log) • Also includes a core set of modules for many types of network and file I/O. – HTTP, TLS, HTTPS, filesystem (POSIX), Datagram (UDP), and NET (TCP). • The core is intentionally small, low-level, and uncomplicated, including just the building blocks for I/O-based applications. – Ex: HTTP parser consisting of roughly 1,500 lines of optimized C code.
  • 11. Hello World HTTP server var http = require('http'); var server = http.createServer(); server.on('request', function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }); server.listen(3000); console.log('Server running at http://localhost:3000/');
  • 12. Organizing and reusing Node functionality
  • 13. Create Modules • Modules can either be single files or directories containing one or more files • Create a file that defines properties on the exports object with any kind of data, such as strings, objects, and functions
  • 14. currency.js var singaporeDollar = 0.80; function roundTwoDecimals(amount) { return Math.round(amount * 100) / 100; } exports.singDollerToUS = function(singDoller) { return roundTwoDecimals(singDoller * singaporeDollar); } exports.USToSingDoller = function(us) { return roundTwoDecimals(us / singaporeDollar); }
  • 15. test-currency.js var currency = require('./currency'); console.log('50 Singapore dollars equals this amount of US dollars:'); console.log(currency.singDollerToUS(50)); console.log('30 US dollars equals this amount of Singapore dollars:'); console.log(currency.USToSingDoller(30));
  • 16. currency-v2.js module.exports = { singDollerToUS : function(singDoller) { return roundTwoDecimals(singDoller * singaporeDollar); }, USToSingDoller : function(us) { return roundTwoDecimals(us / singaporeDollar); }, } var singaporeDollar = 0.80; function roundTwoDecimals(amount) { return Math.round(amount * 100) / 100; }
  • 17. currency-v3.js var Currency = function(singaporeDollar) { this.singaporeDollar = singaporeDollar; } Currency.prototype.roundTwoDecimals = function(amount) { return Math.round(amount * 100) / 100; } Currency.prototype.singDollerToUS = function(singDoller) { return this.roundTwoDecimals(singDoller * this.singaporeDollar); } Currency.prototype.USToSingDoller = function(us) { return this.roundTwoDecimals(us / this.singaporeDollar); } module.exports = Currency; var Currency = require('./currency-v3'); var singDollar = 0.80; var currency = new Currency(singDollar); console.log(currency. singDollerToUS(50));
  • 18. Reusing modules using node_modules • Useful for code you’d like to reuse between applications or share with others • Allows modules to be required without knowing their location in the file system
  • 19.
  • 21. The two model of Async Processing • Callbacks generally define logic for one-off responses. – Ex: perform a database query • Event listeners, are essentially callbacks that are associated with a conceptual entity (an event). – Respond to repeating events – EX: HTTP server emits a request event when an HTTP request is made
  • 22. Handling one-off events with callbacks • A callback is a function, passed as an argument to an asynchronous function • It describes what to do after the asynchronous operation has completed var fs = require('fs'); fs.readFile('./resource.json', function (er, data) { console.log(data); }); Callback function
  • 23. The Node convention for asynchronous callbacks • Most Node built-in modules use callbacks with two arguments – First argument is for an error, should one occur. often abbreviated as er or err – Second argument is for the results var fs = require('fs'); fs.readFile('./titles.json', function(er, data) { if (er) throw er; // do something with data if no error has occurred });
  • 24. Handling repeating events with event emitters • Event emitters fire events and include the ability to handle them when triggered • Events are handled through the use of listeners • A listener is the association of an event with a callback function that gets triggered each time the event occurs
  • 25. var net = require('net'); var server = net.createServer(function(socket) { socket.on('data', function(data) { socket.write(data); }); }); server.listen(8888); data events handled whenever new data has been read Using the on method to respond to events
  • 26. Responding to an event that should only occur once var net = require('net'); var server = net.createServer(function(socket) { socket.once ('data', function(data) { socket.write(data); }); }); server.listen(8888); data event will only be handled once
  • 27. References • [1] Mike Cantelon, Marc Harter, T.J. Holowaychuk and Nathan Rajlich, Node.js in Action, 1st ed. Manning Publications, 2014. • [2] "Node.js - Wikipedia, the free encyclopedia." [Online]. Available: http://en.wikipedia.org/wiki/Node.js. [Accessed: 26- Apr-2015].
  • 28. Q & A