35
© 2015 PayPal Inc. All rights reserved. Confidential and proprietary. Node.js Workshop Quhan Arunasalam March / 27 / 2015 NTU-IEEE

Node.js Workshop

Embed Size (px)

Citation preview

Page 1: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary.

Node.js Workshop

Quhan ArunasalamMarch / 27 / 2015 NTU-IEEE

Page 2: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Node.jsAn 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

Page 3: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Node.jsRun Javascript on the server

3

Page 4: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Understanding the Event LoopThe guts of Node

4

Page 5: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

DoJSON based REST APIs Web / Mobile-Web Apps Network Apps

Don’t CPU intensive work

When to use Node?

5

Page 6: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Test the waters via REPLThe 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/

Page 7: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.1: Test the waters via REPLRead-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

Page 8: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.2: Baby-stepsBuilding 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/

Page 9: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

The module systemThe 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.

Page 10: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.3: Requiring thingsModifying 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

Page 11: Node.js Workshop

© 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

Page 12: Node.js Workshop

© 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';      }  

};

Page 13: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

In-built modulesDon’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.

Page 14: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.6: Create a better (Hello) WorldBy 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');

Page 15: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Reuse and share code

NPM

15

Page 16: Node.js Workshop

© 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.

Page 17: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

The npmjs.com registryNote the 134,726 packages available (at the time of screenshot)

17

Page 18: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.7: Initializing your Hello World projectWith 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)  

Page 19: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.8: Saving the momentInstalling 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);

Page 20: Node.js Workshop

© 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"      }  }

Page 21: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Let’s not publish another hello world8814 packages available (at the time of screenshot)

21

Page 22: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Let’s not publish another hello worldHiding away your little secrets

22

{      "name":  "hello",      "version":  "1.0.0",  

"private":  true,      "description":  "An  app  to  say  Hello  NTU",      ...  }

Page 23: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

ExpressWeb app building, made easier

23

Page 24: Node.js Workshop

© 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/

Page 25: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.9: Expressive greetingsModify 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);

Page 26: Node.js Workshop

© 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.

Page 27: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverTo 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

Page 28: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverSetting 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');  });

Page 29: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverSetting 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  ()  {  ...

Page 30: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverListing 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});  });  

...

Page 31: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverTesting it out by GETing a list of tasks (via Postman)

31

Page 32: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverAdd 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});  });  

...

Page 33: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary

Lab 2.10: Building an API serverTesting it out by POSTing a new task (via Postman)

33

Page 34: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary 34

Cheatsheet

https://github.com/nodeworkshop/node

Page 35: Node.js Workshop

© 2015 PayPal Inc. All rights reserved. Confidential and proprietary.

For more information, please contact:

PayPal Singapore5 Temasek Boulevard #09-01, Suntec Tower Five, Singapore 038985

Quhan Arunasalam