SlideShare uma empresa Scribd logo
1 de 55
Baixar para ler offline
May 4, 2016
#PTW16 Intro to Node.JS
Ross Kukulinski
© 2016 Ross Kukulinski2
@RossKukulinski
Product Manager — NodeSource
Node Foundation Evangelist
Container Advocate & Consultant
Introduction to CoreOS - O’Reilly Media
© 2016 Ross Kukulinski
Overview
3
phillydev.org
#ptw-nodejs-workshop
© 2016 Ross Kukulinski
Overview
4
Why are you here?
© 2016 Ross Kukulinski
Overview
5
Workshop Goals
• Learn what Node.JS is and is not
• Understand non-blocking I/O and event-driven programming
• Hands on with Node.JS!
• Prepare you for future Node.JS learning
© 2016 Ross Kukulinski
Overview
6
Schedule
• 9:00 - 9:05 — Intro & Overview
• 9:05 - 9:45 — What is Node.JS
• 9:45 - 10:00 — Hands-on with NodeJS
• 10:00 - 10:30 — NodeSchool Pair-Programming
• 10:30 - 10:45 — Coffee Refill
• 10:45 - 11:00 — Questions / Review
• 11:00 - 11:45 — Continued Pair-Programming
• 11:45 - 12:00 — Wrap up & Summary
© 2016 Ross Kukulinski
What is Node.JS
7
© 2016 Ross Kukulinski8
© 2016 Ross Kukulinski
What is Node.JS
9
Node.JS is a JavaScript runtime
built on Chrome’s JavaScript
engine* for building fast, scalable
network applications.
© 2016 Ross Kukulinski
Node.JS is NOT
10
… a language
… a web framework
© 2016 Ross Kukulinski
What is Node.JS
11
Node by the Numbers
• Node.JS is the fastest growing development platform
• 3.5 million users and annual growth rate of 100%
• npm is the largest ecosystem of open source libraries in the world
https://nodejs.org/static/documents/2016-survey-report.pdf
© 2016 Ross Kukulinski
What is Node.JS
12
Enterprises have
already adopted
Node.js
© 2016 Ross Kukulinski
Why does Node.JS exist?
13
© 2016 Ross Kukulinski
Why does Node.JS Exist?
14
Latency: Memory vs I/O
L1 cache 0.5ns
L2 cache 7ns
Main memory 100ns
Send 1K bytes over 1 Gbps network 10,000ns
Round trip within same datacenter 500,000ns
Disk seek 10,000,000ns
Packet CA->Netherlands->CA 150,000,000ns
https://gist.github.com/jhclark/2845836
© 2016 Ross Kukulinski15
I/O is Expensive
Why does Node.JS Exist?
© 2016 Ross Kukulinski16
console.log('Fetching article...');
var result = query("SELECT * FROM articles WHERE id = 1");
console.log('Here is the result:', result);
Blocking I/O
Blocking vs Non-Blocking
© 2016 Ross Kukulinski17
1 // Java: Spot the I/O
2
3 System.out.println("Reading file...");
4 BufferedReader br = new BufferedReader(new
5 FileReader("in.txt"));
6
7 try {
8 StringBuilder sb = new StringBuilder();
9 String line;
10
11 while ((line = br.readLine()) != null)
12 sb.append(line + "n");
13 System.out.print(sb.toString());
14 } finally {
15 br.close();
16 }
17
18 System.out.println("Finished reading file!");
© 2016 Ross Kukulinski18
Some solutions
• One process per connection (Apache Web Server 1)
• One thread per connection (Apache Web Server 2)
• Event-Driven (nginx, node.js)
Blocking vs Non-Blocking
© 2016 Ross Kukulinski
Event-Driven, Non-Blocking Programming
19
function handleResult(result) {
console.log('Here is the result:', result);
}
select('SELECT * FROM articles WHERE id = 1', handleResult);
console.log('Fetching article...');
© 2016 Ross Kukulinski
Why JavaScript?
20
JavaScript well-suited to event-driven model
© 2016 Ross Kukulinski
Functions are First-Class Objects
21
Treat functions like any other object
• Pass them as arguments
• Return them from functions
• Store them as variables for later use
© 2016 Ross Kukulinski
Functions are Closures
22
function calculateSum (list) {
var sum = 0;
function addItem(item) {
sum += item;
}
list.forEach(addItem);
console.log('sum: ' + sum);
}
calculateSum([ 2, 5, 10, 42, 67, 78, 89, 120 ]);
© 2016 Ross Kukulinski
Functions are Closures
23
function calculateSum (list) {
var sum = 0;
function addItem(item) {
sum += item;
}
list.forEach(addItem);
return function() { // return a function that can print the result
console.log('sum: ' + sum);
}
}
var printSum = calculateSum([ 2, 5, 10, 42, 67, 78, 89, 120 ]);
// printSum is a function returned by calculateSum but it still
// has access to the scope within its parent function
printSum();
© 2016 Ross Kukulinski
Node.JS Non-Blocking I/O
24
• Kernel-level non-blocking socket I/O using epoll() or select()
system calls (depending on the operating system)
• File system I/O delegated to worker threads
• Glued together with an “event loop”
© 2016 Ross Kukulinski
Node.JS Event Loop
25
• Perform work triggered by JavaScript code
• Perform work triggered by external events
• Pass events & data to JavaScript via callback
functions
• Exit when no more pending work or events
© 2016 Ross Kukulinski
Node.JS Event Loop
26
When does it stop?
// 1.
fs.readFile('bigdata.txt', 'utf8', function (err, data) {
console.log(data.split('n').length, 'lines of data');
});
© 2016 Ross Kukulinski
Node.JS Event Loop
27
When does it stop?
// 2.
setTimeout(function () {
console.log('Waited 10s');
}, 10000);
© 2016 Ross Kukulinski
Node.JS Event Loop
28
When does it stop?
// 3.
var i = 0;
var timer = setInterval(function () {
console.log('tick', i);
if (++i === 60)
clearInterval(timer);
}, 1000);
© 2016 Ross Kukulinski
Blocking the event loop
29
// some Monte Carlo madness
// estimating π by plotting *many* random points on a plane
var points = 100000000;
var inside = 0;
for (var i = 0; i < points; i++) {
if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) <= 1)
inside++;
}
// the event loop is blocked until the calculations are done
console.log(‘π ≈ ’, (inside / points) * 4);
© 2016 Ross Kukulinski
Sync vs Async
30
var bigdata = fs.readFileSync('bigdata', 'utf8');
fs.readFile('bigdata', 'utf8', function (err, bigdata) {
// ...
});
Synchronous
Asynchronous
© 2016 Ross Kukulinski
Node.JS Summary
31
Rules of Thumb
• Choose asynchronous I/O over synchronous I/O
• Opt for parallel I/O wherever possible
• Don’t hog the JavaScript thread with long-running
calculations or iterations
© 2016 Ross Kukulinski
Node.JS Summary
32
Node.JS is Minimal
• Complexity is in user-land
• Instead of a big framework, Node.JS provides minimal
viable library for doing I/O
• All the rest is built on top in user-land
• Pick and choose from HUGE library of third-party modules
© 2016 Ross Kukulinski
npm - Node Package Manger
33
https://www.npmjs.com/
250,000+ packages of reusable code
© 2016 Ross Kukulinski
Node.JS Strengths
34
Node is great for:
• REST APIs
• Mobile Backend
• Real-time applications
• Streaming services
• Prototyping
• Front-end development
© 2016 Ross Kukulinski
Node.JS Weaknesses
35
Node is NOT good for:
• CPU-bound workloads
• Serving static content
© 2016 Ross Kukulinski
Hands-on with Node.JS
36
© 2016 Ross Kukulinski
Installing Node.JS
37
https://nodejs.org/en/download/
https://github.com/creationix/nvm
OSX/Linux
Windows
© 2016 Ross Kukulinski38
What do you get?
• node — The Node.JS runtime binary
• npm — CLI tool allows you to use the extensive module ecosystem
Installing Node.JS
© 2016 Ross Kukulinski
Example Code
39
github.com/rosskukulinski/ptw16_node
© 2016 Ross Kukulinski
Hands-on with NodeJS
40
Live demo time!
© 2016 Ross Kukulinski
NodeSchool Pair-Programming
41
© 2016 Ross Kukulinski
NodeSchool.io
42
Workshoppers
Open source lesson modules to teach
JavaScript, Node.JS, npm, and many more
topics. All lessons are self-guided and most
work offline.
© 2016 Ross Kukulinski43
Find a Partner!
NodeSchool.io
© 2016 Ross Kukulinski
learnyounode
44
Getting started
1. npm install -g learnyounode
2. Make a folder to store your code
3. learnyounode
© 2016 Ross Kukulinski
learnyounode
45
Let’s work through the
first exercise together
© 2016 Ross Kukulinski
Break time! Back at 10:45
46
© 2016 Ross Kukulinski
Questions / Review
47
© 2016 Ross Kukulinski
Back to it!
48
© 2016 Ross Kukulinski
Wrap Up
49
© 2016 Ross Kukulinski
Wrap Up
50
Resources for future learning
• http://nodeschool.io
• https://nodejs.org/api/
• https://github.com/nodejs/help
• #node.js on irc.freenode.net
• http://nodeweekly.com/
• http://planetnodejs.com/
• http://nodeup.com/
• http://stackoverflow.com/questions/tagged/node.js
• http://www.meetup.com/nodejs-philly/
© 2016 Ross Kukulinski
Wrap Up
51
Package recommendations
• Logging: Bunyan, winston
• Webserver: Express, hapi, kraken
• REST APIs: restify, hapi
• Testing: mocha, tap, jasmine
• Frontend: browserify, gulp, grunt, webpack
• Real-time: socket.io, ws
Also experiment with functional programming (Node.JS Streams)
© 2016 Ross Kukulinski
Wrap Up
52
Want to get involved?
• https://nodejs.org/en/get-involved/
• Help with documentation
• Contribute to Node Core
• Contribute to npm modules
• Run your own NodeSchool
© 2016 Ross Kukulinski
NodeSource
53
The Enterprise Node Company™
https://nodesource.com
© 2016 Ross Kukulinski
NodeSource
54
N|Solid: Enterprise Grade Node
• Production Monitoring
• Performance Analysis
• Platform Security
• Free for Development
Thank you.
Ross Kukulinski
ross@nodesource.com
@RossKukulinski

Mais conteúdo relacionado

Mais procurados

Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
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
 

Mais procurados (20)

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
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
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
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
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking io
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
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?
 
(C)NodeJS
(C)NodeJS(C)NodeJS
(C)NodeJS
 
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
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 

Destaque

Destaque (9)

Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Build App with Nodejs - YWC Workshop
Build App with Nodejs - YWC WorkshopBuild App with Nodejs - YWC Workshop
Build App with Nodejs - YWC Workshop
 
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
 
Node js meetup
Node js meetupNode js meetup
Node js meetup
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
Best node js course
Best node js courseBest node js course
Best node js course
 
Nodejs Intro - Part2 Introduction to Web Applications
Nodejs Intro - Part2 Introduction to Web ApplicationsNodejs Intro - Part2 Introduction to Web Applications
Nodejs Intro - Part2 Introduction to Web Applications
 
Vagrant plugin development intro
Vagrant plugin development introVagrant plugin development intro
Vagrant plugin development intro
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 

Semelhante a Philly Tech Week Introduction to NodeJS

Who needs containers in a serverless world
Who needs containers in a serverless worldWho needs containers in a serverless world
Who needs containers in a serverless world
Matthias Luebken
 

Semelhante a Philly Tech Week Introduction to NodeJS (20)

Configuration as Code in Jenkins. What's new? Nov 2016
Configuration as Code in Jenkins. What's new? Nov 2016Configuration as Code in Jenkins. What's new? Nov 2016
Configuration as Code in Jenkins. What's new? Nov 2016
 
Campus HTC at #TechEX15
Campus HTC at #TechEX15Campus HTC at #TechEX15
Campus HTC at #TechEX15
 
Architecting a Cloud Native Internet Archive
Architecting a Cloud Native Internet ArchiveArchitecting a Cloud Native Internet Archive
Architecting a Cloud Native Internet Archive
 
From CoreOS to Kubernetes and Concourse CI
From CoreOS to Kubernetes and Concourse CIFrom CoreOS to Kubernetes and Concourse CI
From CoreOS to Kubernetes and Concourse CI
 
Nodejs
NodejsNodejs
Nodejs
 
SpringOne 2016 in a nutshell
SpringOne 2016 in a nutshellSpringOne 2016 in a nutshell
SpringOne 2016 in a nutshell
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)
 
Cloud, SDN, NFV
Cloud, SDN, NFVCloud, SDN, NFV
Cloud, SDN, NFV
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
An introduction to node3
An introduction to node3An introduction to node3
An introduction to node3
 
The Butler is still young – applying modern Jenkins features to the Embedded ...
The Butler is still young – applying modern Jenkins features to the Embedded ...The Butler is still young – applying modern Jenkins features to the Embedded ...
The Butler is still young – applying modern Jenkins features to the Embedded ...
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational database
 
Python And The MySQL X DevAPI - PyCaribbean 2019
Python And The MySQL X DevAPI - PyCaribbean 2019Python And The MySQL X DevAPI - PyCaribbean 2019
Python And The MySQL X DevAPI - PyCaribbean 2019
 
Who needs containers in a serverless world
Who needs containers in a serverless worldWho needs containers in a serverless world
Who needs containers in a serverless world
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
NodeJS
NodeJSNodeJS
NodeJS
 
Open Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational DatabaseOpen Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational Database
 

Mais de Ross Kukulinski

BayNode Logging Discussion
BayNode Logging DiscussionBayNode Logging Discussion
BayNode Logging Discussion
Ross Kukulinski
 

Mais de Ross Kukulinski (12)

State of State in Containers - PHL Kubernetes
State of State in Containers - PHL KubernetesState of State in Containers - PHL Kubernetes
State of State in Containers - PHL Kubernetes
 
Kubernetes 101 for Developers
Kubernetes 101 for DevelopersKubernetes 101 for Developers
Kubernetes 101 for Developers
 
Workshop: Deploying and Scaling Node.js with Kubernetes
Workshop: Deploying and Scaling Node.js with KubernetesWorkshop: Deploying and Scaling Node.js with Kubernetes
Workshop: Deploying and Scaling Node.js with Kubernetes
 
Introduction to Kubernetes
Introduction to KubernetesIntroduction to Kubernetes
Introduction to Kubernetes
 
Node.js and Containers Go Together Like Peanut Butter and Jelly
Node.js and Containers Go Together Like Peanut Butter and JellyNode.js and Containers Go Together Like Peanut Butter and Jelly
Node.js and Containers Go Together Like Peanut Butter and Jelly
 
State of the Art Containerized Nodejs
State of the Art Containerized NodejsState of the Art Containerized Nodejs
State of the Art Containerized Nodejs
 
Yodlr Realtime Technology Stack
Yodlr Realtime Technology StackYodlr Realtime Technology Stack
Yodlr Realtime Technology Stack
 
Building A SaaS with CoreOS, Docker, and Etcd
Building A SaaS with CoreOS, Docker, and EtcdBuilding A SaaS with CoreOS, Docker, and Etcd
Building A SaaS with CoreOS, Docker, and Etcd
 
Building a SaaS with Nodejs, Docker, and CoreOS
Building a SaaS with Nodejs, Docker, and CoreOSBuilding a SaaS with Nodejs, Docker, and CoreOS
Building a SaaS with Nodejs, Docker, and CoreOS
 
Shipping NodeJS with Docker and CoreOS (No Notes)
Shipping NodeJS with Docker and CoreOS (No Notes)Shipping NodeJS with Docker and CoreOS (No Notes)
Shipping NodeJS with Docker and CoreOS (No Notes)
 
Shipping NodeJS with Docker and CoreOS
Shipping NodeJS with Docker and CoreOSShipping NodeJS with Docker and CoreOS
Shipping NodeJS with Docker and CoreOS
 
BayNode Logging Discussion
BayNode Logging DiscussionBayNode Logging Discussion
BayNode Logging Discussion
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 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
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Philly Tech Week Introduction to NodeJS

  • 1. May 4, 2016 #PTW16 Intro to Node.JS Ross Kukulinski
  • 2. © 2016 Ross Kukulinski2 @RossKukulinski Product Manager — NodeSource Node Foundation Evangelist Container Advocate & Consultant Introduction to CoreOS - O’Reilly Media
  • 3. © 2016 Ross Kukulinski Overview 3 phillydev.org #ptw-nodejs-workshop
  • 4. © 2016 Ross Kukulinski Overview 4 Why are you here?
  • 5. © 2016 Ross Kukulinski Overview 5 Workshop Goals • Learn what Node.JS is and is not • Understand non-blocking I/O and event-driven programming • Hands on with Node.JS! • Prepare you for future Node.JS learning
  • 6. © 2016 Ross Kukulinski Overview 6 Schedule • 9:00 - 9:05 — Intro & Overview • 9:05 - 9:45 — What is Node.JS • 9:45 - 10:00 — Hands-on with NodeJS • 10:00 - 10:30 — NodeSchool Pair-Programming • 10:30 - 10:45 — Coffee Refill • 10:45 - 11:00 — Questions / Review • 11:00 - 11:45 — Continued Pair-Programming • 11:45 - 12:00 — Wrap up & Summary
  • 7. © 2016 Ross Kukulinski What is Node.JS 7
  • 8. © 2016 Ross Kukulinski8
  • 9. © 2016 Ross Kukulinski What is Node.JS 9 Node.JS is a JavaScript runtime built on Chrome’s JavaScript engine* for building fast, scalable network applications.
  • 10. © 2016 Ross Kukulinski Node.JS is NOT 10 … a language … a web framework
  • 11. © 2016 Ross Kukulinski What is Node.JS 11 Node by the Numbers • Node.JS is the fastest growing development platform • 3.5 million users and annual growth rate of 100% • npm is the largest ecosystem of open source libraries in the world https://nodejs.org/static/documents/2016-survey-report.pdf
  • 12. © 2016 Ross Kukulinski What is Node.JS 12 Enterprises have already adopted Node.js
  • 13. © 2016 Ross Kukulinski Why does Node.JS exist? 13
  • 14. © 2016 Ross Kukulinski Why does Node.JS Exist? 14 Latency: Memory vs I/O L1 cache 0.5ns L2 cache 7ns Main memory 100ns Send 1K bytes over 1 Gbps network 10,000ns Round trip within same datacenter 500,000ns Disk seek 10,000,000ns Packet CA->Netherlands->CA 150,000,000ns https://gist.github.com/jhclark/2845836
  • 15. © 2016 Ross Kukulinski15 I/O is Expensive Why does Node.JS Exist?
  • 16. © 2016 Ross Kukulinski16 console.log('Fetching article...'); var result = query("SELECT * FROM articles WHERE id = 1"); console.log('Here is the result:', result); Blocking I/O Blocking vs Non-Blocking
  • 17. © 2016 Ross Kukulinski17 1 // Java: Spot the I/O 2 3 System.out.println("Reading file..."); 4 BufferedReader br = new BufferedReader(new 5 FileReader("in.txt")); 6 7 try { 8 StringBuilder sb = new StringBuilder(); 9 String line; 10 11 while ((line = br.readLine()) != null) 12 sb.append(line + "n"); 13 System.out.print(sb.toString()); 14 } finally { 15 br.close(); 16 } 17 18 System.out.println("Finished reading file!");
  • 18. © 2016 Ross Kukulinski18 Some solutions • One process per connection (Apache Web Server 1) • One thread per connection (Apache Web Server 2) • Event-Driven (nginx, node.js) Blocking vs Non-Blocking
  • 19. © 2016 Ross Kukulinski Event-Driven, Non-Blocking Programming 19 function handleResult(result) { console.log('Here is the result:', result); } select('SELECT * FROM articles WHERE id = 1', handleResult); console.log('Fetching article...');
  • 20. © 2016 Ross Kukulinski Why JavaScript? 20 JavaScript well-suited to event-driven model
  • 21. © 2016 Ross Kukulinski Functions are First-Class Objects 21 Treat functions like any other object • Pass them as arguments • Return them from functions • Store them as variables for later use
  • 22. © 2016 Ross Kukulinski Functions are Closures 22 function calculateSum (list) { var sum = 0; function addItem(item) { sum += item; } list.forEach(addItem); console.log('sum: ' + sum); } calculateSum([ 2, 5, 10, 42, 67, 78, 89, 120 ]);
  • 23. © 2016 Ross Kukulinski Functions are Closures 23 function calculateSum (list) { var sum = 0; function addItem(item) { sum += item; } list.forEach(addItem); return function() { // return a function that can print the result console.log('sum: ' + sum); } } var printSum = calculateSum([ 2, 5, 10, 42, 67, 78, 89, 120 ]); // printSum is a function returned by calculateSum but it still // has access to the scope within its parent function printSum();
  • 24. © 2016 Ross Kukulinski Node.JS Non-Blocking I/O 24 • Kernel-level non-blocking socket I/O using epoll() or select() system calls (depending on the operating system) • File system I/O delegated to worker threads • Glued together with an “event loop”
  • 25. © 2016 Ross Kukulinski Node.JS Event Loop 25 • Perform work triggered by JavaScript code • Perform work triggered by external events • Pass events & data to JavaScript via callback functions • Exit when no more pending work or events
  • 26. © 2016 Ross Kukulinski Node.JS Event Loop 26 When does it stop? // 1. fs.readFile('bigdata.txt', 'utf8', function (err, data) { console.log(data.split('n').length, 'lines of data'); });
  • 27. © 2016 Ross Kukulinski Node.JS Event Loop 27 When does it stop? // 2. setTimeout(function () { console.log('Waited 10s'); }, 10000);
  • 28. © 2016 Ross Kukulinski Node.JS Event Loop 28 When does it stop? // 3. var i = 0; var timer = setInterval(function () { console.log('tick', i); if (++i === 60) clearInterval(timer); }, 1000);
  • 29. © 2016 Ross Kukulinski Blocking the event loop 29 // some Monte Carlo madness // estimating π by plotting *many* random points on a plane var points = 100000000; var inside = 0; for (var i = 0; i < points; i++) { if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) <= 1) inside++; } // the event loop is blocked until the calculations are done console.log(‘π ≈ ’, (inside / points) * 4);
  • 30. © 2016 Ross Kukulinski Sync vs Async 30 var bigdata = fs.readFileSync('bigdata', 'utf8'); fs.readFile('bigdata', 'utf8', function (err, bigdata) { // ... }); Synchronous Asynchronous
  • 31. © 2016 Ross Kukulinski Node.JS Summary 31 Rules of Thumb • Choose asynchronous I/O over synchronous I/O • Opt for parallel I/O wherever possible • Don’t hog the JavaScript thread with long-running calculations or iterations
  • 32. © 2016 Ross Kukulinski Node.JS Summary 32 Node.JS is Minimal • Complexity is in user-land • Instead of a big framework, Node.JS provides minimal viable library for doing I/O • All the rest is built on top in user-land • Pick and choose from HUGE library of third-party modules
  • 33. © 2016 Ross Kukulinski npm - Node Package Manger 33 https://www.npmjs.com/ 250,000+ packages of reusable code
  • 34. © 2016 Ross Kukulinski Node.JS Strengths 34 Node is great for: • REST APIs • Mobile Backend • Real-time applications • Streaming services • Prototyping • Front-end development
  • 35. © 2016 Ross Kukulinski Node.JS Weaknesses 35 Node is NOT good for: • CPU-bound workloads • Serving static content
  • 36. © 2016 Ross Kukulinski Hands-on with Node.JS 36
  • 37. © 2016 Ross Kukulinski Installing Node.JS 37 https://nodejs.org/en/download/ https://github.com/creationix/nvm OSX/Linux Windows
  • 38. © 2016 Ross Kukulinski38 What do you get? • node — The Node.JS runtime binary • npm — CLI tool allows you to use the extensive module ecosystem Installing Node.JS
  • 39. © 2016 Ross Kukulinski Example Code 39 github.com/rosskukulinski/ptw16_node
  • 40. © 2016 Ross Kukulinski Hands-on with NodeJS 40 Live demo time!
  • 41. © 2016 Ross Kukulinski NodeSchool Pair-Programming 41
  • 42. © 2016 Ross Kukulinski NodeSchool.io 42 Workshoppers Open source lesson modules to teach JavaScript, Node.JS, npm, and many more topics. All lessons are self-guided and most work offline.
  • 43. © 2016 Ross Kukulinski43 Find a Partner! NodeSchool.io
  • 44. © 2016 Ross Kukulinski learnyounode 44 Getting started 1. npm install -g learnyounode 2. Make a folder to store your code 3. learnyounode
  • 45. © 2016 Ross Kukulinski learnyounode 45 Let’s work through the first exercise together
  • 46. © 2016 Ross Kukulinski Break time! Back at 10:45 46
  • 47. © 2016 Ross Kukulinski Questions / Review 47
  • 48. © 2016 Ross Kukulinski Back to it! 48
  • 49. © 2016 Ross Kukulinski Wrap Up 49
  • 50. © 2016 Ross Kukulinski Wrap Up 50 Resources for future learning • http://nodeschool.io • https://nodejs.org/api/ • https://github.com/nodejs/help • #node.js on irc.freenode.net • http://nodeweekly.com/ • http://planetnodejs.com/ • http://nodeup.com/ • http://stackoverflow.com/questions/tagged/node.js • http://www.meetup.com/nodejs-philly/
  • 51. © 2016 Ross Kukulinski Wrap Up 51 Package recommendations • Logging: Bunyan, winston • Webserver: Express, hapi, kraken • REST APIs: restify, hapi • Testing: mocha, tap, jasmine • Frontend: browserify, gulp, grunt, webpack • Real-time: socket.io, ws Also experiment with functional programming (Node.JS Streams)
  • 52. © 2016 Ross Kukulinski Wrap Up 52 Want to get involved? • https://nodejs.org/en/get-involved/ • Help with documentation • Contribute to Node Core • Contribute to npm modules • Run your own NodeSchool
  • 53. © 2016 Ross Kukulinski NodeSource 53 The Enterprise Node Company™ https://nodesource.com
  • 54. © 2016 Ross Kukulinski NodeSource 54 N|Solid: Enterprise Grade Node • Production Monitoring • Performance Analysis • Platform Security • Free for Development