SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary.
Node.js Workshop
Quhan Arunasalam
March / 27 / 2015 NTU-IEEE
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Node.js
An open source, cross-platform
runtime environment for
server-side Javascript applications.
NPM A package manager for Javascript.
Express
A minimal and flexible Node.js
web application framework.
What we’re going to explore today
2
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Node.js
Run Javascript on the server
3
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Understanding the Event Loop
The guts of Node
4
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Do
JSON based REST APIs
Web / Mobile-Web Apps
Network Apps
Don’t CPU intensive work
When to use Node?
5
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Test the waters via REPL
The Read-Eval-Print Loop
6
• Provides a way to interactively
run JavaScript and see the
results.
• Useful for debugging,
testing, or just trying things
out.
https://www.flickr.com/photos/snype451/5752753663/
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.1: Test the waters via REPL
Read-Eval-Print-Loop
7
$	
  node	
  
>	
  var	
  a	
  =	
  [1,	
  2,	
  3];	
  
>	
  console.log(a);	
  
[	
  1,	
  2,	
  3	
  ]	
  
>	
  a.forEach(function	
  (z)	
  {	
  console.log(z);	
  });	
  
1	
  
2	
  
3
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.2: Baby-steps
Building the classic Hello World
8
$	
  mkdir	
  hello	
  &&	
  cd	
  hello	
  
$	
  touch	
  index.js	
  
//	
  index.js	
  
console.log('Hello	
  NTU');	
  
$	
  node	
  index	
  
Hello	
  NTU
https://www.flickr.com/photos/munakz/9228501911/
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
The module system
The building blocks of a Node app
9
http://pixabay.com/en/lego-building-blocks-shapes-puzzle-297773/
• Makes it possible to include
other Javascript files into your
app.
• Helps organize your code into
separate parts with limited
responsibilities.
• Using modules is simple -
You just require() them.
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.3: Requiring things
Modifying your previous Hello World example
10
$	
  touch	
  greet.js	
  
//	
  greet.js	
  
exports.hello	
  =	
  function	
  ()	
  {	
  
return	
  'Hello	
  NTU';	
  
}	
  
//	
  index.js	
  
var	
  greet	
  =	
  require('./greet.js');	
  
console.log(greet.hello());	
  
$	
  node	
  index	
  
Hello	
  NTU
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.4: Requiring things (again)
Let’s get bilingual
11
//	
  greet.js	
  
exports.hello	
  =	
  function	
  ()	
  {	
  
return	
  'Hello	
  NTU';	
  
}	
  
exports.konbanwa	
  =	
  function	
  ()	
  {	
  
return	
  'Konbanwa	
  NTU';	
  
}	
  
//	
  index.js	
  
var	
  greet	
  =	
  require('./greet.js');	
  
console.log(greet.hello());	
  
console.log(greet.konbanwa());	
  
$	
  node	
  index	
  
Hello	
  NTU	
  
Konbanwa	
  NTU
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.5: Requiring things (one last time)
Another way of handling exports
12
//	
  greet.js	
  
module.exports	
  =	
  {	
  
	
  	
  hello:	
  function	
  ()	
  {	
  
	
  	
  	
  	
  return	
  'Hello	
  NTU';	
  
	
  	
  },	
  
	
  	
  konbanwa:	
  function	
  ()	
  {	
  
	
  	
  	
  	
  return	
  'Konbanwa	
  NTU';	
  
	
  	
  }	
  
};
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
In-built modules
Don’t worry, we’re getting to the fun parts
13
http://commons.wikimedia.org/wiki/File:AMC_V8_engine_360_CID_customized_um.JPG
Node ships with a number of
core modules. For example:
• console - Sends output to
stdout or stderr.
• http - Provides a server and
client for HTTP traffic.
• fs - Provides functions to
interact with the file system.
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.6: Create a better (Hello) World
By building a web server
14
//	
  index.js	
  
var	
  http	
  =	
  require('http');	
  
var	
  greet	
  =	
  require('./greet.js');	
  
http.createServer(function	
  (req,	
  res)	
  {	
  
	
  	
  res.writeHead(200,	
  {'Content-­‐Type':	
  'text/plain'});	
  
	
  	
  res.end(greet.hello());	
  
}).listen(8000);	
  
console.log('Server	
  running	
  at	
  http://127.0.0.1:8000');
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Reuse and share code
NPM
15
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
What is npm?
It’s 3 things actually
16
https://www.flickr.com/photos/kamshots/3096111340/
• A module registry, containing
a collection of open-source
code.
• A standard, to define
dependencies on other
packages.
• A package manager, for
locally installed modules.
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
The npmjs.com registry
Note the 134,726 packages available (at the time of screenshot)
17
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.7: Initializing your Hello World project
With metadata
18
$	
  npm	
  init	
  
...	
  
name:	
  (hello)	
  	
  
version:	
  (1.0.0)	
  	
  
description:	
  An	
  app	
  to	
  say	
  Hello	
  NTU	
  
entry	
  point:	
  (index.js)	
  	
  
test	
  command:	
  	
  
git	
  repository:	
  	
  
keywords:	
  helloworld	
  
author:	
  Quhan	
  Arunasalam	
  
license:	
  (ISC)	
  
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.8: Saving the moment
Installing and using a 3rd party module
19
$	
  npm	
  install	
  -­‐-­‐save	
  moment	
  
//	
  index.js	
  
var	
  http	
  =	
  require('http');	
  
var	
  greet	
  =	
  require('./greet.js');	
  
var	
  moment	
  =	
  require('moment');	
  
http.createServer(function	
  (req,	
  res)	
  {	
  
	
  	
  res.writeHead(200,	
  {'Content-­‐Type':	
  'text/plain'});	
  
	
  	
  res.end('Hi!	
  It	
  is	
  now	
  '	
  +	
  moment().format('h:mm:ss	
  a'));	
  
}).listen(8000);
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary 20
Figuring out package.json
{	
  
	
  	
  "name":	
  "hello",	
  
	
  	
  "version":	
  "1.0.0",	
  
	
  	
  "description":	
  "An	
  app	
  to	
  say	
  Hello	
  NTU",	
  
	
  	
  "main":	
  "index.js",	
  
	
  	
  "scripts":	
  {	
  
	
  	
  	
  	
  "test":	
  "echo	
  "Error:	
  no	
  test	
  specified"	
  &&	
  exit	
  1"	
  
	
  	
  },	
  
	
  	
  "keywords":	
  [	
  
	
  	
  	
  	
  "helloworld"	
  
	
  	
  ],	
  
	
  	
  "author":	
  "Quhan	
  Arunasalam",	
  
	
  	
  "license":	
  "ISC",	
  
	
  	
  "dependencies":	
  {	
  
	
  	
  	
  	
  "moment":	
  "^2.9.0"	
  
	
  	
  }	
  
}
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Let’s not publish another hello world
8814 packages available (at the time of screenshot)
21
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Let’s not publish another hello world
Hiding away your little secrets
22
{	
  
	
  	
  "name":	
  "hello",	
  
	
  	
  "version":	
  "1.0.0",	
  
"private":	
  true,	
  
	
  	
  "description":	
  "An	
  app	
  to	
  say	
  Hello	
  NTU",	
  
	
  	
  ...	
  
}
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Express
Web app building, made easier
23
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
What is Express?
24
• A framework to help build web
applications.
• Is to Node what Sinatra / RoR is
to Ruby.
• Makes development easier with:
• Request routing
• Handling HTTP verbs
• And a whole lot more...
• Is made up of a series of
middleware calls.
http://pixabay.com/en/tunnel-light-speed-fast-auto-101976/
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.9: Expressive greetings
Modify your Hello World code to use Express
25
$	
  npm	
  install	
  -­‐-­‐save	
  express	
  
//	
  index.js	
  
var	
  express	
  =	
  require('express');	
  
var	
  greet	
  =	
  require('./greet.js');	
  
var	
  app	
  =	
  express();	
  
app.get('/',	
  function	
  (req,	
  res)	
  {	
  
res.send(greet.hello());	
  
});	
  
app.listen(8000);
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary 26
Middleware
Middleware
Middleware
ApplicationRequest Response
A function with access to the request object, the response object, and
the next middleware in line in the request-response cycle of an
application.
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
To list and save tasks. And yay! Finally done with the Hello World!
27
$	
  mkdir	
  tasks	
  &&	
  cd	
  tasks	
  
$	
  npm	
  init	
  
...	
  
$	
  npm	
  install	
  -­‐-­‐save	
  express	
  
$	
  npm	
  install	
  -­‐-­‐save	
  express-­‐session	
  
$	
  npm	
  install	
  -­‐-­‐save	
  body-­‐parser	
  
$	
  touch	
  index.js
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
Setting up the Express skeleton
28
//	
  index.js	
  
var	
  express	
  =	
  require('express');	
  
var	
  session	
  =	
  require('express-­‐session');	
  
var	
  bodyParser	
  =	
  require('body-­‐parser');	
  
var	
  app	
  =	
  express();	
  
app.listen(3000,	
  function	
  ()	
  {	
  
	
   console.log('API	
  server	
  started	
  on	
  port	
  3000');	
  
});
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
Setting up middleware (and some dummy data)
29
...	
  
var	
  app	
  =	
  express();	
  
app.use(session({secret:	
  'ntu-­‐ieee'}));	
  
app.use(bodyParser.urlencoded({extended:	
  false}));	
  
function	
  initializeTasks()	
  {	
  
	
   var	
  tasks	
  =	
  [];	
  
	
   tasks.push('Step	
  1:	
  Learn	
  Node');	
  
	
   tasks.push('Step	
  2:	
  Learn	
  NPM');	
  
	
   tasks.push('Step	
  3:	
  Learn	
  Express');	
  
	
   return	
  tasks;	
  
}	
  
app.listen(3000,	
  function	
  ()	
  {	
  
...
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
Listing out tasks via GET
30
...	
  
app.get('/',	
  function	
  (req,	
  res)	
  {	
  
	
   if	
  (!req.session.tasks)	
  {	
  
//	
  Tasks	
  not	
  found	
  in	
  session,	
  so	
  initialize	
  it	
   	
  
req.session.tasks	
  =	
  initializeTasks();	
  
	
   }	
  
	
   //	
  Returns	
  a	
  JSON	
  object	
  with	
  an	
  array	
  of	
  tasks	
  
	
   res.json({tasks:	
  req.session.tasks});	
  
});	
  
...
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
Testing it out by GETing a list of tasks (via Postman)
31
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
Add a task via POST
32
...	
  
app.post('/task',	
  function	
  (req,	
  res)	
  {	
  
	
   if	
  (!req.session.tasks)	
  {	
  
	
   	
   //	
  Tasks	
  not	
  found	
  in	
  session,	
  so	
  initialize	
  it	
  
	
   	
   req.session.tasks	
  =	
  initializeTasks();	
  
	
   }	
  
	
   //	
  Assign	
  the	
  POSTed	
  task	
  to	
  the	
  newTask	
  variable	
  
	
   var	
  newTask	
  =	
  req.body.task;	
  
	
   //	
  Save	
  the	
  new	
  task	
  to	
  the	
  session	
  array	
  of	
  tasks	
  
	
   req.session.tasks.push(newTask);	
  
	
   //	
  Returns	
  a	
  JSON	
  object	
  with	
  an	
  array	
  of	
  tasks	
  
	
   res.json({tasks:	
  req.session.tasks});	
  
});	
  
...
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary
Lab 2.10: Building an API server
Testing it out by POSTing a new task (via Postman)
33
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary 34
Cheatsheet
https://github.com/nodeworkshop/node
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary.
For more information, please contact:
PayPal Singapore

5 Temasek Boulevard #09-01, Suntec Tower Five, Singapore 038985
Quhan Arunasalam

Weitere ähnliche Inhalte

Was ist angesagt?

Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
Tatsuhiko Miyagawa
 

Was ist angesagt? (20)

Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 
Plack at YAPC::NA 2010
Plack at YAPC::NA 2010Plack at YAPC::NA 2010
Plack at YAPC::NA 2010
 
React Native in Production
React Native in ProductionReact Native in Production
React Native in Production
 
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's How
 
Java REST API Framework Comparison - UberConf 2021
Java REST API Framework Comparison - UberConf 2021Java REST API Framework Comparison - UberConf 2021
Java REST API Framework Comparison - UberConf 2021
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Maintaining a dependency graph with weaver
Maintaining a dependency graph with weaverMaintaining a dependency graph with weaver
Maintaining a dependency graph with weaver
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Wicket 10 years and beyond
Wicket   10 years and beyond Wicket   10 years and beyond
Wicket 10 years and beyond
 
JWT - Sécurisez vos APIs
JWT - Sécurisez vos APIsJWT - Sécurisez vos APIs
JWT - Sécurisez vos APIs
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
 
Whats up with wicket 8 and java 8
Whats up with wicket 8 and java 8Whats up with wicket 8 and java 8
Whats up with wicket 8 and java 8
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odyssey
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
When dynamic becomes static
When dynamic becomes staticWhen dynamic becomes static
When dynamic becomes static
 
Angular beans
Angular beansAngular beans
Angular beans
 

Andere mochten auch

Soldier's Travel Book
Soldier's Travel BookSoldier's Travel Book
Soldier's Travel Book
Dee Cammack
 
Corporate Group School
Corporate Group SchoolCorporate Group School
Corporate Group School
catxliii
 
Book of Memories 2
Book of Memories 2 Book of Memories 2
Book of Memories 2
Dee Cammack
 
Overview Aesthetic Philosophy 01
Overview  Aesthetic Philosophy 01Overview  Aesthetic Philosophy 01
Overview Aesthetic Philosophy 01
Patrick BLANCHETON
 
Book of Memories - 1
Book of Memories - 1Book of Memories - 1
Book of Memories - 1
Dee Cammack
 
Heating In Philadelphia
Heating In PhiladelphiaHeating In Philadelphia
Heating In Philadelphia
livvyloo92
 
The ABC’S Of Managed Care
The ABC’S Of Managed CareThe ABC’S Of Managed Care
The ABC’S Of Managed Care
catxliii
 

Andere mochten auch (16)

Node.js primer for ITE students
Node.js primer for ITE studentsNode.js primer for ITE students
Node.js primer for ITE students
 
Soldier's Travel Book
Soldier's Travel BookSoldier's Travel Book
Soldier's Travel Book
 
AAHAM
AAHAMAAHAM
AAHAM
 
Corporate Group School
Corporate Group SchoolCorporate Group School
Corporate Group School
 
Book of Memories 2
Book of Memories 2 Book of Memories 2
Book of Memories 2
 
Overview Aesthetic Philosophy 01
Overview  Aesthetic Philosophy 01Overview  Aesthetic Philosophy 01
Overview Aesthetic Philosophy 01
 
Book of Memories - 1
Book of Memories - 1Book of Memories - 1
Book of Memories - 1
 
Plaquette REPONSE - anglais
Plaquette REPONSE - anglaisPlaquette REPONSE - anglais
Plaquette REPONSE - anglais
 
Node.js primer
Node.js primerNode.js primer
Node.js primer
 
Heating In Philadelphia
Heating In PhiladelphiaHeating In Philadelphia
Heating In Philadelphia
 
עיצוב מחדש של אתר אינטרנט ומעבר למערכת דרופל
עיצוב מחדש של אתר אינטרנט ומעבר למערכת דרופלעיצוב מחדש של אתר אינטרנט ומעבר למערכת דרופל
עיצוב מחדש של אתר אינטרנט ומעבר למערכת דרופל
 
Html5 cheat-sheet
Html5 cheat-sheetHtml5 cheat-sheet
Html5 cheat-sheet
 
פרופ' יגאל ברונר - איך הפכתי להומניסט דיגיטלי
 פרופ' יגאל ברונר - איך הפכתי להומניסט דיגיטלי פרופ' יגאל ברונר - איך הפכתי להומניסט דיגיטלי
פרופ' יגאל ברונר - איך הפכתי להומניסט דיגיטלי
 
Bluemix setup
Bluemix setupBluemix setup
Bluemix setup
 
C# 3.0 Course
C# 3.0 CourseC# 3.0 Course
C# 3.0 Course
 
The ABC’S Of Managed Care
The ABC’S Of Managed CareThe ABC’S Of Managed Care
The ABC’S Of Managed Care
 

Ähnlich wie Node.js Workshop

Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
Edureka!
 

Ähnlich wie Node.js Workshop (20)

Open Source, infrastructure as Code, Cloud Native Apps 2015
Open Source, infrastructure as Code, Cloud Native Apps 2015Open Source, infrastructure as Code, Cloud Native Apps 2015
Open Source, infrastructure as Code, Cloud Native Apps 2015
 
Sst hackathon express
Sst hackathon expressSst hackathon express
Sst hackathon express
 
Owin and Katana
Owin and KatanaOwin and Katana
Owin and Katana
 
JAX London 2015: Java vs Nodejs
JAX London 2015: Java vs NodejsJAX London 2015: Java vs Nodejs
JAX London 2015: Java vs Nodejs
 
Java vs. Java Script for enterprise web applications - Chris Bailey
Java vs. Java Script for enterprise web applications - Chris BaileyJava vs. Java Script for enterprise web applications - Chris Bailey
Java vs. Java Script for enterprise web applications - Chris Bailey
 
Proposal
ProposalProposal
Proposal
 
HP Helion European Webinar Series ,Webinar #3
HP Helion European Webinar Series ,Webinar #3 HP Helion European Webinar Series ,Webinar #3
HP Helion European Webinar Series ,Webinar #3
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Nodejs
NodejsNodejs
Nodejs
 
Marcin Szałowicz - MySQL Workbench
Marcin Szałowicz - MySQL WorkbenchMarcin Szałowicz - MySQL Workbench
Marcin Szałowicz - MySQL Workbench
 
Node.js Tools Ecosystem
Node.js Tools EcosystemNode.js Tools Ecosystem
Node.js Tools Ecosystem
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
 
HP Helion Webinar #2
HP Helion Webinar #2 HP Helion Webinar #2
HP Helion Webinar #2
 
AWS 고객사를 위한 ‘AWS 컨테이너 교육’ - 유재석, AWS 솔루션즈 아키텍트
AWS 고객사를 위한 ‘AWS 컨테이너 교육’ - 유재석, AWS 솔루션즈 아키텍트AWS 고객사를 위한 ‘AWS 컨테이너 교육’ - 유재석, AWS 솔루션즈 아키텍트
AWS 고객사를 위한 ‘AWS 컨테이너 교육’ - 유재석, AWS 솔루션즈 아키텍트
 
Cloud Platforms for Java
Cloud Platforms for JavaCloud Platforms for Java
Cloud Platforms for Java
 
Java ee7 1hour
Java ee7 1hourJava ee7 1hour
Java ee7 1hour
 
murakumo Cloud Controller
murakumo Cloud Controllermurakumo Cloud Controller
murakumo Cloud Controller
 
Kubernetes for the PHP developer
Kubernetes for the PHP developerKubernetes for the PHP developer
Kubernetes for the PHP developer
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Node.js Workshop

  • 1. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary. Node.js Workshop Quhan Arunasalam March / 27 / 2015 NTU-IEEE
  • 2. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Node.js An open source, cross-platform runtime environment for server-side Javascript applications. NPM A package manager for Javascript. Express A minimal and flexible Node.js web application framework. What we’re going to explore today 2
  • 3. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Node.js Run Javascript on the server 3
  • 4. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Understanding the Event Loop The guts of Node 4
  • 5. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Do JSON based REST APIs Web / Mobile-Web Apps Network Apps Don’t CPU intensive work When to use Node? 5
  • 6. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Test the waters via REPL The Read-Eval-Print Loop 6 • Provides a way to interactively run JavaScript and see the results. • Useful for debugging, testing, or just trying things out. https://www.flickr.com/photos/snype451/5752753663/
  • 7. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.1: Test the waters via REPL Read-Eval-Print-Loop 7 $  node   >  var  a  =  [1,  2,  3];   >  console.log(a);   [  1,  2,  3  ]   >  a.forEach(function  (z)  {  console.log(z);  });   1   2   3
  • 8. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.2: Baby-steps Building the classic Hello World 8 $  mkdir  hello  &&  cd  hello   $  touch  index.js   //  index.js   console.log('Hello  NTU');   $  node  index   Hello  NTU https://www.flickr.com/photos/munakz/9228501911/
  • 9. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary The module system The building blocks of a Node app 9 http://pixabay.com/en/lego-building-blocks-shapes-puzzle-297773/ • Makes it possible to include other Javascript files into your app. • Helps organize your code into separate parts with limited responsibilities. • Using modules is simple - You just require() them.
  • 10. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.3: Requiring things Modifying your previous Hello World example 10 $  touch  greet.js   //  greet.js   exports.hello  =  function  ()  {   return  'Hello  NTU';   }   //  index.js   var  greet  =  require('./greet.js');   console.log(greet.hello());   $  node  index   Hello  NTU
  • 11. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.4: Requiring things (again) Let’s get bilingual 11 //  greet.js   exports.hello  =  function  ()  {   return  'Hello  NTU';   }   exports.konbanwa  =  function  ()  {   return  'Konbanwa  NTU';   }   //  index.js   var  greet  =  require('./greet.js');   console.log(greet.hello());   console.log(greet.konbanwa());   $  node  index   Hello  NTU   Konbanwa  NTU
  • 12. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.5: Requiring things (one last time) Another way of handling exports 12 //  greet.js   module.exports  =  {      hello:  function  ()  {          return  'Hello  NTU';      },      konbanwa:  function  ()  {          return  'Konbanwa  NTU';      }   };
  • 13. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary In-built modules Don’t worry, we’re getting to the fun parts 13 http://commons.wikimedia.org/wiki/File:AMC_V8_engine_360_CID_customized_um.JPG Node ships with a number of core modules. For example: • console - Sends output to stdout or stderr. • http - Provides a server and client for HTTP traffic. • fs - Provides functions to interact with the file system.
  • 14. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.6: Create a better (Hello) World By building a web server 14 //  index.js   var  http  =  require('http');   var  greet  =  require('./greet.js');   http.createServer(function  (req,  res)  {      res.writeHead(200,  {'Content-­‐Type':  'text/plain'});      res.end(greet.hello());   }).listen(8000);   console.log('Server  running  at  http://127.0.0.1:8000');
  • 15. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Reuse and share code NPM 15
  • 16. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary What is npm? It’s 3 things actually 16 https://www.flickr.com/photos/kamshots/3096111340/ • A module registry, containing a collection of open-source code. • A standard, to define dependencies on other packages. • A package manager, for locally installed modules.
  • 17. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary The npmjs.com registry Note the 134,726 packages available (at the time of screenshot) 17
  • 18. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.7: Initializing your Hello World project With metadata 18 $  npm  init   ...   name:  (hello)     version:  (1.0.0)     description:  An  app  to  say  Hello  NTU   entry  point:  (index.js)     test  command:     git  repository:     keywords:  helloworld   author:  Quhan  Arunasalam   license:  (ISC)  
  • 19. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.8: Saving the moment Installing and using a 3rd party module 19 $  npm  install  -­‐-­‐save  moment   //  index.js   var  http  =  require('http');   var  greet  =  require('./greet.js');   var  moment  =  require('moment');   http.createServer(function  (req,  res)  {      res.writeHead(200,  {'Content-­‐Type':  'text/plain'});      res.end('Hi!  It  is  now  '  +  moment().format('h:mm:ss  a'));   }).listen(8000);
  • 20. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary 20 Figuring out package.json {      "name":  "hello",      "version":  "1.0.0",      "description":  "An  app  to  say  Hello  NTU",      "main":  "index.js",      "scripts":  {          "test":  "echo  "Error:  no  test  specified"  &&  exit  1"      },      "keywords":  [          "helloworld"      ],      "author":  "Quhan  Arunasalam",      "license":  "ISC",      "dependencies":  {          "moment":  "^2.9.0"      }   }
  • 21. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Let’s not publish another hello world 8814 packages available (at the time of screenshot) 21
  • 22. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Let’s not publish another hello world Hiding away your little secrets 22 {      "name":  "hello",      "version":  "1.0.0",   "private":  true,      "description":  "An  app  to  say  Hello  NTU",      ...   }
  • 23. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Express Web app building, made easier 23
  • 24. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary What is Express? 24 • A framework to help build web applications. • Is to Node what Sinatra / RoR is to Ruby. • Makes development easier with: • Request routing • Handling HTTP verbs • And a whole lot more... • Is made up of a series of middleware calls. http://pixabay.com/en/tunnel-light-speed-fast-auto-101976/
  • 25. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.9: Expressive greetings Modify your Hello World code to use Express 25 $  npm  install  -­‐-­‐save  express   //  index.js   var  express  =  require('express');   var  greet  =  require('./greet.js');   var  app  =  express();   app.get('/',  function  (req,  res)  {   res.send(greet.hello());   });   app.listen(8000);
  • 26. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary 26 Middleware Middleware Middleware ApplicationRequest Response A function with access to the request object, the response object, and the next middleware in line in the request-response cycle of an application.
  • 27. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server To list and save tasks. And yay! Finally done with the Hello World! 27 $  mkdir  tasks  &&  cd  tasks   $  npm  init   ...   $  npm  install  -­‐-­‐save  express   $  npm  install  -­‐-­‐save  express-­‐session   $  npm  install  -­‐-­‐save  body-­‐parser   $  touch  index.js
  • 28. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server Setting up the Express skeleton 28 //  index.js   var  express  =  require('express');   var  session  =  require('express-­‐session');   var  bodyParser  =  require('body-­‐parser');   var  app  =  express();   app.listen(3000,  function  ()  {     console.log('API  server  started  on  port  3000');   });
  • 29. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server Setting up middleware (and some dummy data) 29 ...   var  app  =  express();   app.use(session({secret:  'ntu-­‐ieee'}));   app.use(bodyParser.urlencoded({extended:  false}));   function  initializeTasks()  {     var  tasks  =  [];     tasks.push('Step  1:  Learn  Node');     tasks.push('Step  2:  Learn  NPM');     tasks.push('Step  3:  Learn  Express');     return  tasks;   }   app.listen(3000,  function  ()  {   ...
  • 30. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server Listing out tasks via GET 30 ...   app.get('/',  function  (req,  res)  {     if  (!req.session.tasks)  {   //  Tasks  not  found  in  session,  so  initialize  it     req.session.tasks  =  initializeTasks();     }     //  Returns  a  JSON  object  with  an  array  of  tasks     res.json({tasks:  req.session.tasks});   });   ...
  • 31. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server Testing it out by GETing a list of tasks (via Postman) 31
  • 32. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server Add a task via POST 32 ...   app.post('/task',  function  (req,  res)  {     if  (!req.session.tasks)  {       //  Tasks  not  found  in  session,  so  initialize  it       req.session.tasks  =  initializeTasks();     }     //  Assign  the  POSTed  task  to  the  newTask  variable     var  newTask  =  req.body.task;     //  Save  the  new  task  to  the  session  array  of  tasks     req.session.tasks.push(newTask);     //  Returns  a  JSON  object  with  an  array  of  tasks     res.json({tasks:  req.session.tasks});   });   ...
  • 33. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary Lab 2.10: Building an API server Testing it out by POSTing a new task (via Postman) 33
  • 34. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary 34 Cheatsheet https://github.com/nodeworkshop/node
  • 35. © 2015 PayPal Inc. All rights reserved. Confidential and proprietary. For more information, please contact: PayPal Singapore
 5 Temasek Boulevard #09-01, Suntec Tower Five, Singapore 038985 Quhan Arunasalam