SlideShare a Scribd company logo
An opinionated intro to Node.js
Luciano Mammino
@loige
👋 Hello, I am Luciano
Cloud & Full stack software engineer
nodejsdesignpatterns.com
Let’s connect:
🌎 loige.co
🐦 @loige
🧳 lucianomammino
👇 Get the slides (and click around…)
loige.link/devrupt-node - loige.link/devrupt-node-code
@loige
Agenda
Node.js intro
Blocking vs async I/O
Dealing with async I/O
Some interesting patterns
@loige
What is Node.js
Node.js is an open-source, cross-platform,
JavaScript runtime environment that executes
JavaScript code outside a web browser.
@loige
Ryan Dahl
Created and launched in 2009 by
Ryan Dahl to have a way to run
JavaScript code outside a browser.
npm was launched in the same
year.
Big companies (Linkedin, Uber,
Paypal, Walmart) adopted Node.js
early on.
@loige
Node.js vs JavaScript in the browser
● Node.js does not run in the browser
○ It doesn’t have a DOM
○ It doesn’t have browser specific APIs
● It is not as sandboxed as the browser
○ Node.js can access the filesystem
○ It can interact with the network layer (TCP/UDP)
○ ...and even have bindings to native libraries (N-API interface)
@loige
Node.js + JavaScript: when?
● Building for the web
○ Websites, APIs, Servers, Single Page Applications, Bots, etc…
● Command-line applications and tools
● Mobile applications (React Native, Ionic, NativeScript, etc.)
● Desktop apps (Electron)
● Embedded & IoT (Espruino, Johnny-Five)
@loige
Node.js + JavaScript: when not?
● You don’t like the async model
● You need fine-grained control on memory
● You have to rely heavily on CPU/GPU rather than I/O
● You prefer to release native (compiled) applications
@loige
Async I/O
In JavaScript and in Node.js, input/output operations (e.g. making an HTTP
request) are non-blocking.
@loige
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://google.com")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
System.out.println("Request completed");
A blocking HTTP request (Java)
Output
blocking...
blocking...
<google home page HTML code>
Request completed
Code executed
“In order”
@loige
Is blocking I/O bad?
It depends…
If your application is I/O heavy, then you might have a problem...
@loige
Let’s make 3 requests...
Req 1
Req 2
Req 3
time
@loige
You can always use threads...
Req 1
Req 2
Req 3
time
But threads are…
Complicated
Expensive
A lot of idle time per thread!
wait...
wait...
wait...
@loige
client.get('https://google.com',
(err, resp) => {
console.log(resp.body)
}
)
console.log('Request completed (?)')
👍
With Node.js async I/O
Output
Request “in the
background”
Request completed (?)
<google home page HTML
code>
⚠ Code executed
“OUT of order”
Not really completed!
Non-blocking:
execution continues
Callback function
1
2
3
@loige
Mental model
You “just” schedule async I/O and you will get notified when the
operation is completed!
● Async I/O happens in the background asynchronously
● You don’t have to manage threads to get concurrency!
@loige
Let’s do 3 requests with Async I/O
“User” thread
Event loop
(libuv)
time
idle... idle... idle...
Simpler code for the user
Idle time only in one thread
Sched. req1
Sched. req2
Sched. req3 req1 result req3 result req2 result
@loige
I am oversimplifying a bit… 😛
Watch loige.link/event-loop-what-the-heck if
you want to go more in depth!
@loige
Many ways to
handle async flows
@loige
Delete last reservation if confirmed
● Get a guest object from a guest id (async)
● Get the last reservation from the guest object
● Get the details of that reservation (async)
● Delete that reservation if “confirmed” (async)
@loige
Callbacks
function deleteLastReservationIfConfirmed (client, guestId, cb) {
client.getGuest(guestId, (err, guest) => {
if (err) { return cb(err) }
const lastReservation = guest.reservations.pop()
if (typeof lastReservation === 'undefined') {
return cb(null, false)
}
client.getReservation(lastReservation, (err, reservation) => {
if (err) { return cb(err) }
if (reservation.status === 'confirmed') {
client.deleteReservation(reservation.id, (err) => {
if (err) { return cb(err) }
return cb(null, true)
})
}
})
})
}
@loige
Promises
function deleteLastReservationIfConfirmed (client, guestId) {
return client.getGuest(guestId)
.then((guest) => {
const lastReservation = guest.reservations.pop()
if (typeof lastReservation !== 'undefined') {
return client.getReservation(lastReservation)
}
})
.then((reservation) => {
if (!reservation || reservation.status !== 'confirmed') {
return false
}
return client.deleteReservation(reservation.id)
})
}
@loige
Async/Await
async function deleteLastReservationIfConfirmed (client, guestId) {
const guest = await client.getGuest(guestId)
const lastReservation = guest.reservations.pop()
if (typeof lastReservation === 'undefined') {
return false
}
const reservation = await client.getReservation(lastReservation)
if (!reservation || reservation.status !== 'confirmed') {
return false
}
return client.deleteReservation(reservation.id)
}
@loige
Advantages of Async/Await
● Easier to read and reason about (“sequential flow”)
● Easier to deal with conditional async operations
● Unified error handling
(you can catch both synchronous and asynchronous errors)
⚠ To fully understand async/await, you still need to understand callbacks and
promises, don’t ignore them!
@loige
Other ways to handle async
● Events
● Streams
● Async iterators/generators
@loige
Some interesting
async patterns
@loige
Sequential execution
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi']
for (const guestId of guestIds) {
await deleteLastReservationIfConfirmed(client, guestId)
}
@loige
Sequential execution ⚠ Common pitfall
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi']
guestIds.forEach(async (guestId) => {
await deleteLastReservationIfConfirmed(client, guestId)
})
Don’t use Array.map or Array.forEach!
forEach will run all the functions without awaiting them, so all the delete
invocations will happen concurrently!
@loige
Concurrent execution
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi']
await Promise.all(
guestIds.map(
guestId => deleteLastReservationIfConfirmed(client, guestId)
)
)
⚠ Promise.all rejects as soon as one promise rejects. A failure will result in the failure of the entire operation.
@loige
Concurrent execution - Alternative
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi']
const results = await Promise.allSettled(
guestIds.map(
guestId => deleteLastReservationIfConfirmed(client, guestId)
)
) [
{ status: 'fulfilled', value: true },
{ status: 'fulfilled', value: true },
{ status: 'rejected', reason: Error },
{ status: 'fulfilled', value: true }
]
@loige
Concurrent execution - limited
const mapLimit = require('async/mapLimit')
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi', '...']
const results = await mapLimit(
guestIds,
2, // max concurrency
async (guestId) => deleteLastReservationIfConfirmed(client, guestId)
)
When you have a lot of tasks to run and what to keep limited concurrency
Uses the third-party async module (npm.im/async)
@loige
Request batching
Classic flow - one user
@loige
HTTP
Server DB
/availability/v1/units
Request batching
Classic flow - multiple users (no batching)
@loige
HTTP
Server DB
/availability/v1/units
/availability/v1/units
/availability/v1/units
Request batching
Classic flow - multiple users (with batching!)
@loige
HTTP
Server DB
/availability/v1/units
/availability/v1/units
/availability/v1/units
📘 Requests in-flight
pending
fulfilled
⏱ /availability/v1/units
⏱
The web server
@loige
const { createServer } = require('http')
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost')
if (url.pathname !== '/availability/v1/units') {
res.writeHead(404, 'Not found')
return res.end()
}
const units = await getAvailableUnitsFromDb()
res.writeHead(200)
res.end(JSON.stringify(units))
})
server.listen(8000)
Get units from DB
@loige
let pendingRequest = null
async function getAvailableUnitsFromDb () {
if (pendingRequest) {
console.log('batching')
return pendingRequest
}
console.log('Getting data from db')
pendingRequest = db.query('SELECT * FROM units WHERE "availability" > 0')
pendingRequest.finally(() => {
pendingRequest = null
})
return pendingRequest
}
Performance comparison
@loige
Without batching With batching
+15%
throughput
In conclusion
● Node.js is a great runtime for I/O bound applications
● It’s also great for full stack web development
● The async model allows you to express concurrent computation effectively
● You still need to master callbacks, promises and async / await!
● There are many patterns that can help you out to keep your code organised
and more performant.
@loige
Want to learn more?
● nodejsdesignpatterns.com - possibly a great book :)
● loige.link/javascript-mdn - mozilla guides
● eloquentjavascript.net - free e-book
● freecodecamp.org - interactive code training
● nodejs.org/api - Node.js official docs
@loige
THANK YOU
@loige
loige.link/devrupt-node
loige.link/devrupt-node-code

More Related Content

What's hot

Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
Felix Geisendörfer
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
Doris Chen
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
fakedarren
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
Josh Glover
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingCracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Luciano Mammino
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
Felix Geisendörfer
 
hacking with node.JS
hacking with node.JShacking with node.JS
hacking with node.JS
Harsha Vashisht
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
Tatsuhiko Miyagawa
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
Mike Brevoort
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
Concept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized ApplicationConcept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized Application
Seiji Takahashi
 
Node.js 0.8 features
Node.js 0.8 featuresNode.js 0.8 features
Node.js 0.8 features
Nicholas McClay
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
Dinh Pham
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
Steve Rhoades
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
Julian Viereck
 
Node.js code tracing
Node.js code tracingNode.js code tracing
Node.js code tracing
Geng-Dian Huang
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
Paweł Kowalczuk
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 

What's hot (20)

Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingCracking JWT tokens: a tale of magic, Node.JS and parallel computing
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
hacking with node.JS
hacking with node.JShacking with node.JS
hacking with node.JS
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Concept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized ApplicationConcept of BlockChain & Decentralized Application
Concept of BlockChain & Decentralized Application
 
Node.js 0.8 features
Node.js 0.8 featuresNode.js 0.8 features
Node.js 0.8 features
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
 
Node.js code tracing
Node.js code tracingNode.js code tracing
Node.js code tracing
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 

Similar to An opinionated intro to Node.js - devrupt hospitality hackathon

From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns
Luciano Mammino
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
som_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
wilburlo
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Node js
Node jsNode js
Node js
hazzaz
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
Tatsuhiko Miyagawa
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
Yiguang Hu
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
Ngoc Dao
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
jessesanford
 
Node azure
Node azureNode azure
Node azure
Emanuele DelBono
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
Jackson Tian
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
guileen
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 

Similar to An opinionated intro to Node.js - devrupt hospitality hackathon (20)

From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Node js
Node jsNode js
Node js
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Node azure
Node azureNode azure
Node azure
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 

More from Luciano Mammino

Did you know JavaScript has iterators? DublinJS
Did you know JavaScript has iterators? DublinJSDid you know JavaScript has iterators? DublinJS
Did you know JavaScript has iterators? DublinJS
Luciano Mammino
 
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
Luciano Mammino
 
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
Building an invite-only microsite with Next.js & Airtable - ReactJS MilanoBuilding an invite-only microsite with Next.js & Airtable - ReactJS Milano
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
Luciano Mammino
 
From Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiperFrom Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiper
Luciano Mammino
 
Let's build a 0-cost invite-only website with Next.js and Airtable!
Let's build a 0-cost invite-only website with Next.js and Airtable!Let's build a 0-cost invite-only website with Next.js and Airtable!
Let's build a 0-cost invite-only website with Next.js and Airtable!
Luciano Mammino
 
Everything I know about S3 pre-signed URLs
Everything I know about S3 pre-signed URLsEverything I know about S3 pre-signed URLs
Everything I know about S3 pre-signed URLs
Luciano Mammino
 
Serverless for High Performance Computing
Serverless for High Performance ComputingServerless for High Performance Computing
Serverless for High Performance Computing
Luciano Mammino
 
Serverless for High Performance Computing
Serverless for High Performance ComputingServerless for High Performance Computing
Serverless for High Performance Computing
Luciano Mammino
 
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
JavaScript Iteration Protocols - Workshop NodeConf EU 2022JavaScript Iteration Protocols - Workshop NodeConf EU 2022
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
Luciano Mammino
 
Building an invite-only microsite with Next.js & Airtable
Building an invite-only microsite with Next.js & AirtableBuilding an invite-only microsite with Next.js & Airtable
Building an invite-only microsite with Next.js & Airtable
Luciano Mammino
 
Let's take the monolith to the cloud 🚀
Let's take the monolith to the cloud 🚀Let's take the monolith to the cloud 🚀
Let's take the monolith to the cloud 🚀
Luciano Mammino
 
A look inside the European Covid Green Certificate - Rust Dublin
A look inside the European Covid Green Certificate - Rust DublinA look inside the European Covid Green Certificate - Rust Dublin
A look inside the European Covid Green Certificate - Rust Dublin
Luciano Mammino
 
Monoliths to the cloud!
Monoliths to the cloud!Monoliths to the cloud!
Monoliths to the cloud!
Luciano Mammino
 
The senior dev
The senior devThe senior dev
The senior dev
Luciano Mammino
 
Node.js: scalability tips - Azure Dev Community Vijayawada
Node.js: scalability tips - Azure Dev Community VijayawadaNode.js: scalability tips - Azure Dev Community Vijayawada
Node.js: scalability tips - Azure Dev Community Vijayawada
Luciano Mammino
 
A look inside the European Covid Green Certificate (Codemotion 2021)
A look inside the European Covid Green Certificate (Codemotion 2021)A look inside the European Covid Green Certificate (Codemotion 2021)
A look inside the European Covid Green Certificate (Codemotion 2021)
Luciano Mammino
 
AWS Observability Made Simple
AWS Observability Made SimpleAWS Observability Made Simple
AWS Observability Made Simple
Luciano Mammino
 
Semplificare l'observability per progetti Serverless
Semplificare l'observability per progetti ServerlessSemplificare l'observability per progetti Serverless
Semplificare l'observability per progetti Serverless
Luciano Mammino
 
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Luciano Mammino
 
Finding a lost song with Node.js and async iterators - EnterJS 2021
Finding a lost song with Node.js and async iterators - EnterJS 2021Finding a lost song with Node.js and async iterators - EnterJS 2021
Finding a lost song with Node.js and async iterators - EnterJS 2021
Luciano Mammino
 

More from Luciano Mammino (20)

Did you know JavaScript has iterators? DublinJS
Did you know JavaScript has iterators? DublinJSDid you know JavaScript has iterators? DublinJS
Did you know JavaScript has iterators? DublinJS
 
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
 
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
Building an invite-only microsite with Next.js & Airtable - ReactJS MilanoBuilding an invite-only microsite with Next.js & Airtable - ReactJS Milano
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
 
From Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiperFrom Node.js to Design Patterns - BuildPiper
From Node.js to Design Patterns - BuildPiper
 
Let's build a 0-cost invite-only website with Next.js and Airtable!
Let's build a 0-cost invite-only website with Next.js and Airtable!Let's build a 0-cost invite-only website with Next.js and Airtable!
Let's build a 0-cost invite-only website with Next.js and Airtable!
 
Everything I know about S3 pre-signed URLs
Everything I know about S3 pre-signed URLsEverything I know about S3 pre-signed URLs
Everything I know about S3 pre-signed URLs
 
Serverless for High Performance Computing
Serverless for High Performance ComputingServerless for High Performance Computing
Serverless for High Performance Computing
 
Serverless for High Performance Computing
Serverless for High Performance ComputingServerless for High Performance Computing
Serverless for High Performance Computing
 
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
JavaScript Iteration Protocols - Workshop NodeConf EU 2022JavaScript Iteration Protocols - Workshop NodeConf EU 2022
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
 
Building an invite-only microsite with Next.js & Airtable
Building an invite-only microsite with Next.js & AirtableBuilding an invite-only microsite with Next.js & Airtable
Building an invite-only microsite with Next.js & Airtable
 
Let's take the monolith to the cloud 🚀
Let's take the monolith to the cloud 🚀Let's take the monolith to the cloud 🚀
Let's take the monolith to the cloud 🚀
 
A look inside the European Covid Green Certificate - Rust Dublin
A look inside the European Covid Green Certificate - Rust DublinA look inside the European Covid Green Certificate - Rust Dublin
A look inside the European Covid Green Certificate - Rust Dublin
 
Monoliths to the cloud!
Monoliths to the cloud!Monoliths to the cloud!
Monoliths to the cloud!
 
The senior dev
The senior devThe senior dev
The senior dev
 
Node.js: scalability tips - Azure Dev Community Vijayawada
Node.js: scalability tips - Azure Dev Community VijayawadaNode.js: scalability tips - Azure Dev Community Vijayawada
Node.js: scalability tips - Azure Dev Community Vijayawada
 
A look inside the European Covid Green Certificate (Codemotion 2021)
A look inside the European Covid Green Certificate (Codemotion 2021)A look inside the European Covid Green Certificate (Codemotion 2021)
A look inside the European Covid Green Certificate (Codemotion 2021)
 
AWS Observability Made Simple
AWS Observability Made SimpleAWS Observability Made Simple
AWS Observability Made Simple
 
Semplificare l'observability per progetti Serverless
Semplificare l'observability per progetti ServerlessSemplificare l'observability per progetti Serverless
Semplificare l'observability per progetti Serverless
 
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
 
Finding a lost song with Node.js and async iterators - EnterJS 2021
Finding a lost song with Node.js and async iterators - EnterJS 2021Finding a lost song with Node.js and async iterators - EnterJS 2021
Finding a lost song with Node.js and async iterators - EnterJS 2021
 

Recently uploaded

Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
Ayan Halder
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 

Recently uploaded (20)

Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 

An opinionated intro to Node.js - devrupt hospitality hackathon

  • 1. An opinionated intro to Node.js Luciano Mammino @loige
  • 2. 👋 Hello, I am Luciano Cloud & Full stack software engineer nodejsdesignpatterns.com Let’s connect: 🌎 loige.co 🐦 @loige 🧳 lucianomammino
  • 3. 👇 Get the slides (and click around…) loige.link/devrupt-node - loige.link/devrupt-node-code @loige
  • 4. Agenda Node.js intro Blocking vs async I/O Dealing with async I/O Some interesting patterns @loige
  • 5. What is Node.js Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser. @loige
  • 6. Ryan Dahl Created and launched in 2009 by Ryan Dahl to have a way to run JavaScript code outside a browser. npm was launched in the same year. Big companies (Linkedin, Uber, Paypal, Walmart) adopted Node.js early on. @loige
  • 7. Node.js vs JavaScript in the browser ● Node.js does not run in the browser ○ It doesn’t have a DOM ○ It doesn’t have browser specific APIs ● It is not as sandboxed as the browser ○ Node.js can access the filesystem ○ It can interact with the network layer (TCP/UDP) ○ ...and even have bindings to native libraries (N-API interface) @loige
  • 8. Node.js + JavaScript: when? ● Building for the web ○ Websites, APIs, Servers, Single Page Applications, Bots, etc… ● Command-line applications and tools ● Mobile applications (React Native, Ionic, NativeScript, etc.) ● Desktop apps (Electron) ● Embedded & IoT (Espruino, Johnny-Five) @loige
  • 9. Node.js + JavaScript: when not? ● You don’t like the async model ● You need fine-grained control on memory ● You have to rely heavily on CPU/GPU rather than I/O ● You prefer to release native (compiled) applications @loige
  • 10. Async I/O In JavaScript and in Node.js, input/output operations (e.g. making an HTTP request) are non-blocking. @loige
  • 11. OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://google.com") .build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); System.out.println("Request completed"); A blocking HTTP request (Java) Output blocking... blocking... <google home page HTML code> Request completed Code executed “In order” @loige
  • 12. Is blocking I/O bad? It depends… If your application is I/O heavy, then you might have a problem... @loige
  • 13. Let’s make 3 requests... Req 1 Req 2 Req 3 time @loige
  • 14. You can always use threads... Req 1 Req 2 Req 3 time But threads are… Complicated Expensive A lot of idle time per thread! wait... wait... wait... @loige
  • 15. client.get('https://google.com', (err, resp) => { console.log(resp.body) } ) console.log('Request completed (?)') 👍 With Node.js async I/O Output Request “in the background” Request completed (?) <google home page HTML code> ⚠ Code executed “OUT of order” Not really completed! Non-blocking: execution continues Callback function 1 2 3 @loige
  • 16. Mental model You “just” schedule async I/O and you will get notified when the operation is completed! ● Async I/O happens in the background asynchronously ● You don’t have to manage threads to get concurrency! @loige
  • 17. Let’s do 3 requests with Async I/O “User” thread Event loop (libuv) time idle... idle... idle... Simpler code for the user Idle time only in one thread Sched. req1 Sched. req2 Sched. req3 req1 result req3 result req2 result @loige
  • 18. I am oversimplifying a bit… 😛 Watch loige.link/event-loop-what-the-heck if you want to go more in depth! @loige
  • 19. Many ways to handle async flows @loige
  • 20. Delete last reservation if confirmed ● Get a guest object from a guest id (async) ● Get the last reservation from the guest object ● Get the details of that reservation (async) ● Delete that reservation if “confirmed” (async) @loige
  • 21. Callbacks function deleteLastReservationIfConfirmed (client, guestId, cb) { client.getGuest(guestId, (err, guest) => { if (err) { return cb(err) } const lastReservation = guest.reservations.pop() if (typeof lastReservation === 'undefined') { return cb(null, false) } client.getReservation(lastReservation, (err, reservation) => { if (err) { return cb(err) } if (reservation.status === 'confirmed') { client.deleteReservation(reservation.id, (err) => { if (err) { return cb(err) } return cb(null, true) }) } }) }) } @loige
  • 22. Promises function deleteLastReservationIfConfirmed (client, guestId) { return client.getGuest(guestId) .then((guest) => { const lastReservation = guest.reservations.pop() if (typeof lastReservation !== 'undefined') { return client.getReservation(lastReservation) } }) .then((reservation) => { if (!reservation || reservation.status !== 'confirmed') { return false } return client.deleteReservation(reservation.id) }) } @loige
  • 23. Async/Await async function deleteLastReservationIfConfirmed (client, guestId) { const guest = await client.getGuest(guestId) const lastReservation = guest.reservations.pop() if (typeof lastReservation === 'undefined') { return false } const reservation = await client.getReservation(lastReservation) if (!reservation || reservation.status !== 'confirmed') { return false } return client.deleteReservation(reservation.id) } @loige
  • 24. Advantages of Async/Await ● Easier to read and reason about (“sequential flow”) ● Easier to deal with conditional async operations ● Unified error handling (you can catch both synchronous and asynchronous errors) ⚠ To fully understand async/await, you still need to understand callbacks and promises, don’t ignore them! @loige
  • 25. Other ways to handle async ● Events ● Streams ● Async iterators/generators @loige
  • 27. Sequential execution const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi'] for (const guestId of guestIds) { await deleteLastReservationIfConfirmed(client, guestId) } @loige
  • 28. Sequential execution ⚠ Common pitfall const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi'] guestIds.forEach(async (guestId) => { await deleteLastReservationIfConfirmed(client, guestId) }) Don’t use Array.map or Array.forEach! forEach will run all the functions without awaiting them, so all the delete invocations will happen concurrently! @loige
  • 29. Concurrent execution const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi'] await Promise.all( guestIds.map( guestId => deleteLastReservationIfConfirmed(client, guestId) ) ) ⚠ Promise.all rejects as soon as one promise rejects. A failure will result in the failure of the entire operation. @loige
  • 30. Concurrent execution - Alternative const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi'] const results = await Promise.allSettled( guestIds.map( guestId => deleteLastReservationIfConfirmed(client, guestId) ) ) [ { status: 'fulfilled', value: true }, { status: 'fulfilled', value: true }, { status: 'rejected', reason: Error }, { status: 'fulfilled', value: true } ] @loige
  • 31. Concurrent execution - limited const mapLimit = require('async/mapLimit') const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi', '...'] const results = await mapLimit( guestIds, 2, // max concurrency async (guestId) => deleteLastReservationIfConfirmed(client, guestId) ) When you have a lot of tasks to run and what to keep limited concurrency Uses the third-party async module (npm.im/async) @loige
  • 32. Request batching Classic flow - one user @loige HTTP Server DB /availability/v1/units
  • 33. Request batching Classic flow - multiple users (no batching) @loige HTTP Server DB /availability/v1/units /availability/v1/units /availability/v1/units
  • 34. Request batching Classic flow - multiple users (with batching!) @loige HTTP Server DB /availability/v1/units /availability/v1/units /availability/v1/units 📘 Requests in-flight pending fulfilled ⏱ /availability/v1/units ⏱
  • 35. The web server @loige const { createServer } = require('http') const server = createServer(async (req, res) => { const url = new URL(req.url, 'http://localhost') if (url.pathname !== '/availability/v1/units') { res.writeHead(404, 'Not found') return res.end() } const units = await getAvailableUnitsFromDb() res.writeHead(200) res.end(JSON.stringify(units)) }) server.listen(8000)
  • 36. Get units from DB @loige let pendingRequest = null async function getAvailableUnitsFromDb () { if (pendingRequest) { console.log('batching') return pendingRequest } console.log('Getting data from db') pendingRequest = db.query('SELECT * FROM units WHERE "availability" > 0') pendingRequest.finally(() => { pendingRequest = null }) return pendingRequest }
  • 37. Performance comparison @loige Without batching With batching +15% throughput
  • 38. In conclusion ● Node.js is a great runtime for I/O bound applications ● It’s also great for full stack web development ● The async model allows you to express concurrent computation effectively ● You still need to master callbacks, promises and async / await! ● There are many patterns that can help you out to keep your code organised and more performant. @loige
  • 39. Want to learn more? ● nodejsdesignpatterns.com - possibly a great book :) ● loige.link/javascript-mdn - mozilla guides ● eloquentjavascript.net - free e-book ● freecodecamp.org - interactive code training ● nodejs.org/api - Node.js official docs @loige