Top Banner
V9.1 cover IBM Training Front cover Student Exercises Developing BlueMix applications with IBM SDK for Node.js Course code VY102 ERC 1.0
118

vy1021xstud

Jan 29, 2016

Download

Documents

Ahmed Elgendy

ibm bluemix training
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: vy1021xstud

V9.1

cover

IBM Training Front cover

Student Exercises

Developing BlueMix applications with IBM SDK for Node.jsCourse code VY102 ERC 1.0

Page 2: vy1021xstud

Student Exercises

Trademarks

IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business Machines Corp., registered in many jurisdictions worldwide.

The following are trademarks of International Business Machines Corporation, registered in many jurisdictions worldwide:

Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.

Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both.

Java™ and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or its affiliates.

Other product and service names might be trademarks of IBM or other companies.

Express® Power Systems™ Power®System z® WebSphere®

January 2015 edition

The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis without any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. While each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.

© Copyright International Business Machines Corporation 2015.This document may not be reproduced in whole or in part without the prior written permission of IBM.US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

Page 3: vy1021xstud

Student ExercisesV9.0

TOC

Contents

Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

Exercises description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Exercise 1. Set up your Node.js development environment in IBM BlueMix . . . . . . . . . . . . 1-1Part 1: Create your IBM BlueMix and IBM DevOps accounts . . . . . . . . . . . . . . . . . . . . . . 1-3Part 2: Set up the IBM SDK for Node.js run time environment . . . . . . . . . . . . . . . . . . . . . 1-3Part 3: Create a server application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9Part 4: Deploy and test the application in IBM BlueMix . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14Part 5: Update and deploy changes to your application . . . . . . . . . . . . . . . . . . . . . . . . . 1-18Part 6: Write a dynamic message in the HTTP response message . . . . . . . . . . . . . . . . 1-20Part 7: Defining a module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22Part 8: Importing a module into your application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25

Exercise 2. Asynchronous I/O with callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1Part 1: Review the National Weather Service weather observation web service . . . . . . . 2-2Part 2: Set up the IBM SDK for Node.js run time environment . . . . . . . . . . . . . . . . . . . . . 2-3Part 3: Create a server application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8Part 4: Deploy and test the application in IBM BlueMix . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13Part 5: Make an HTTP request to a third-party web service . . . . . . . . . . . . . . . . . . . . . . 2-15Part 6: Test the HTTP request to a third-party web service . . . . . . . . . . . . . . . . . . . . . . 2-19Part 7: Parse the web service response message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21Part 8: Create a package for the weather observation web service client . . . . . . . . . . . . 2-23

Exercise 3. Node packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Part 1: Fork the IBM DevOps repository from the previous exercise . . . . . . . . . . . . . . . . . 3-2Part 2: Pass parameters to a Node module function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11Part 3: Propagating errors to callback functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14Part 4: Defining a third-party package in the package manifest . . . . . . . . . . . . . . . . . . . 3-18Part 5: The Express web application framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Contents iii

Page 4: vy1021xstud

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

iv IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 5: vy1021xstud

Student ExercisesV9.0

TMK

Trademarks

The reader should recognize that the following terms, which appear in the content of this training document, are official trademarks of IBM or other companies:

IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business Machines Corp., registered in many jurisdictions worldwide.

The following are trademarks of International Business Machines Corporation, registered in many jurisdictions worldwide:

Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.

Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both.

Java™ and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or its affiliates.

Other product and service names might be trademarks of IBM or other companies.

Express® Power Systems™ Power®System z® WebSphere®

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Trademarks v

Page 6: vy1021xstud

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

vi IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 7: vy1021xstud

Student ExercisesV9.0

pref

Exercises description

This course includes the following exercises:

• Set up your Node.js development environment

• Asynchronous I/O with callback

• Node packages

In the exercise instructions, you can check off the line before each step as you complete it to track your progress.

Most exercises include required sections which should always be completed. It might be necessary to complete these sections before you can start later exercises. Some exercises might also include optional sections that you might want to complete if you have sufficient time and want an extra challenge.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercises description vii

Page 8: vy1021xstud

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

viii IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 9: vy1021xstud

Student ExercisesV9.0

EXempty

Exercise 1. Set up your Node.js development environment in IBM BlueMix

What this exercise is about

In this exercise, you set up your IBM BlueMix and IBM DevOps environments to develop and test IBM SDK for Node.js applications. Create an IBM SDK for Node.js application. Examine a simple IBM SDK for Node.js web server implementation. Add features to the IBM SDK for Node.js frameworks with modules.

What you should be able to do

At the end of this exercise, you should be able to:

• Create an IBM SDK for Node.js application

• Install the IBM SDK for Node.js runtime engine in a BlueMix account

• Deploy an IBM SDK for Node.js application in a BlueMix account

• Import IBM SDK for Node.js modules into a script

Introduction

Web developers write JavaScript applications to add interactivity to client-side web applications. As an interpreted scripting language, developers do not need to use compilers to write applications. The syntax of the programming language is simple enough for web developers with little programming experience to write simple applications.

IBM SDK for Node.js uses the JavaScript programming language for server-side applications. Instead of running scripts in a web browser, the node application interprets and runs JavaScript applications on a server. Node.js works on an event-driven model - it responds to network events through event handler functions.

In this exercise, you install the IBM SDK for Node.js on an IBM BlueMix account. You develop a server application that responds to web browser requests.

Requirements

Before you start this exercise, sign up for an IBM BlueMix and an IBM DevOps account.

This exercise requires a workstation with internet access. You can complete this exercise on a computer that runs Linux, Mac OS, or Microsoft Windows.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-1

Page 10: vy1021xstud

Student Exercises

For a list of compatible web browsers, see: https://developer.ibm.com/bluemix/support/#prereqs

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-2 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 11: vy1021xstud

Student ExercisesV9.0

EXempty

Exercise instructions

Part 1: Create your IBM BlueMix and IBM DevOps accounts

You must sign up and create your IBM BlueMix and IBM DevOps accounts before you start this exercise. The IBM BlueMix account provides a runtime environment for your IBM SDK for Node.js application. The IBM DevOps account maintains the source code for your application.

Important

Complete the steps in the tutorial to sign up for an IBM BlueMix and IBM DevOps account with your IBM ID. Review the “Getting Started with IBM BlueMix and IBM DevOps services with Node.js” tutorial.

https://hub.jazz.net/tutorials/jazzeditor/

Part 2: Set up the IBM SDK for Node.js run time environment

Create an application with the IBM SDK for Node.js runtime to set up your IBM BlueMix account.

__ 1. Log in to your IBM BlueMix account.

__ a. Open a web browser.

__ b. Navigate to https://bluemix.net.

__ c. Click on the Log in link on the page.

__ d. Enter your IBM ID and password for your IBM BlueMix account.

__ e. Click Sign in.

__ 2. Create an application with the IBM SDK for Node.js server run time environment.

__ a. In your IBM BlueMix account page, select Dashboard.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-3

Page 12: vy1021xstud

Student Exercises

__ b. Click on Create an App in the application section of the Dashboard.

__ c. In the list of application types, select SDK for Node.js from the Runtimes catalog.

__ d. In the application wizard, enter the following

- Host: <yourname>Ex01

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-4 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 13: vy1021xstud

Student ExercisesV9.0

EXempty

- Name: <yourname>Ex01

Note

Replace <yourname> with your user name. The value of <yourname> must be unique across all BlueMix accounts.

__ e. Leave the Selected Plan setting to Default.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-5

Page 14: vy1021xstud

Student Exercises

__ 3. Confirm that the IBM SDK for Node.js run time environment starts successfully in your IBM BlueMix account.

__ a. Wait until your <yourname>Ex01 application is in the Started state.

__ 4. Open the sample application start page from the Routes link.

__ a. In the Overview page for the <yourname>Ex01 application, select the Routes link.

__ b. Confirm that the Node.js Start Application web page appears in your browser.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-6 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 15: vy1021xstud

Student ExercisesV9.0

EXempty

Information

Git is an open source, distributed version control system. The IBM DevOps services hosts Git repositories for your IBM BlueMix applications.

When you add an IBM DevOps Git repository to your IBM BlueMix application, the system asks for your Jazz.net ID. You can link your IBM BlueMix user ID with your Jazz.net ID, to avoid entering your credentials every time you switch from IBM BlueMix to IBM DevOps.

__ 5. Create a Git repository in IBM DevOps services to manage the source code of your application.

__ a. In the IBM BlueMix application overview page for <yourname>Ex01, select Add Git.

__ b. Log in to IBM DevOps services with the Jazz ID you created.

__ c. Make sure to uncheck the option labeled “Populate the repository with the start application package and deploy it to the application”.

__ d. Click Continue.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-7

Page 16: vy1021xstud

Student Exercises

__ e. After the wizard creates the Git repository, select Close.

__ 6. Open the IBM DevOps project for the <yourname>Ex01 application.

__ a. In the BlueMix application dashboard, select Edit Code beside the Git URL link.

__ b. Wait until the Git repository for your application appears.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-8 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 17: vy1021xstud

Student ExercisesV9.0

EXempty

Information

The IBM DevOps service provides an integrated development environment (IDE) that runs within your web browser. You do not need to install a desktop application, such as Eclipse, to manage and edit your source code.

Part 3: Create a server application

The main use case for Node.js is to build server-side applications and services. In this section, build a server application that returns a greeting to the client’s web browser. Learn how to handle HTTP request and response messages with the http package.

__ 1. Create a JavaScript file named hellotoday.js in the <yourname>Ex01 Git Repository.

__ a. In the web IDE (Integrated Development Environment) view, select File > New > File from the menu.

__ b. Enter hellotoday.js as the file name.

__ 2. Open hellotoday.js in an editor.

__ a. Double-click on the hellotoday.js file to edit the file.

__ b. Confirm that the hellotoday.js file opens in the web browser.

__ 3. Define the application host name and port variables in the hellotoday.js script.

__ a. Define the host and port variables at the beginning of the script.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-9

Page 18: vy1021xstud

Student Exercises

Information

The BlueMix environment initializes the process.env.VCAPP_APP_HOST and process.env.VCAP_APP_PORT JavaScript variables. These two variables represent the host name and port number assigned to the IBM SDK for Node.js application. When you run the hellotoday.js script outside of the BlueMix environment, the host and the port variables take the values of localhost and 8080.

__ b. Define a variable, http, as a reference to the http Node module.

var http = require('http');

Information

Use the require statement with the name of a module to import Node modules that are managed by the Node Package Manager (NPM).

var http = require('http');

In this example, http is the name of the module that is managed by the Node Package Manager.

__ 4. Use the http.createServer() function to create a web application server.

__ a. Create a server object with the http.createServer() function.

var server = http.createServer( function(request, response) {});

Information

The createServer() function expects a callback function as the first parameter. The callback function has two parameters: the HTTP request and response messages.

__ 5. Modify the callback handler in http.createServer to print the message “Hello WebSphere!” in the HTTP response message

__ a. In the anonymous function in http.createServer(), write the response message body in a variable, body.

var body = 'Hello WebSphere!';

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-10 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 19: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Use the response.writeHead() function to set an HTTP response status code of OK (200).

var server = http.createServer( function(request, response) {var body = 'Hello WebSphere!';response.writeHead( 200 );

});

Information

The writeHead() function takes two parameters: an HTTP status code, and an object with HTTP response header names and values.

__ c. Set the HTTP Content-Length header to the length of the response message body.

__ d. Set the HTTP Content-Type header to ‘text/plain’.

__ e. Compare your script with the following solution code:

var server = http.createServer( function(request, response) {var body = 'Hello WebSphere!';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});});

__ f. After the response.writeHead() function call, add the following line:

response.write(body);

Note

To intercept HTTP requests, you must set the server object to listen to HTTP requests on a specific port.

__ 6. Set the server object to listen to HTTP requests on port 8080.

__ a. Add the following line at the end of the script:

server.listen(port);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-11

Page 20: vy1021xstud

Student Exercises

__ 7. Compare your code with the model solution.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var server = http.createServer( function(request, response) {var body = 'Hello WebSphere!';

response.writeHead( 200, {'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);

});server.listen(port);

__ 8. Save hellotoday.js.

__ a. Select File > Save to save your changes to hellotoday.js.

__ 9. Create a manifest.yml file to describe how to deploy the <yourname>Ex01 application to your BlueMix account.

__ a. Create a file named manifest.yml.

__ b. Open manifest.yml in an editor view.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-12 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 21: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Add the following lines to the manifest.yml file.

applications:- disk_quota: 1024M host: <yourname>Ex01 name: <yourname>Ex01 command: node hellotoday.js path: . domain: mybluemix.net instances: 1 memory: 128M

__ d. Save manifest.yml.

Information

The IBM BlueMix environment reads the settings from the manifest.yml file during deployment.

The applications block begins with a heading, followed by a colon. The next line begins with a single dash and one space. The host and name must match the name when you created the app domain in IBM BlueMix.

A detailed description of manifest file specification is available at:

http://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html

__ 10. Create a package.json file to describe the Node module dependencies for the <yourname>Ex01 application.

__ a. Create a file named package.json.

__ b. Open package.json in an editor view.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-13

Page 22: vy1021xstud

Student Exercises

__ c. Add the following lines to the package.json file.

{"name": "Exercise01App","version": "0.0.1","description": "A nodejs app for Bluemix",

}

__ d. Save package.json.

Part 4: Deploy and test the application in IBM BlueMix

The Build and Deploy feature in the IBM DevOps service publishes your IBM SDK for Node.js application to your IBM BlueMix account. In the first part of the exercise, review your Node

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-14 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 23: vy1021xstud

Student ExercisesV9.0

EXempty

application and commit your changes to the Git repository. Publish your work to your IBM BlueMix application. Test the application from a web browser.

__ 1. Commit the changes to the <yourname>Ex01 Git repository.

__ a. In the IBM DevOps web page, select the Git repository icon in the toolbar.

__ b. The Git repository page lists the recently changed files in your project. Enter a comment to describe the changes in this revision.

__ c. Check Select All to mark all changed files for check in.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-15

Page 24: vy1021xstud

Student Exercises

__ d. Select Commit to save the revision to the repository.

__ 2. Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.

__ a. In the Repository view of the Git repository page, click Push.

The Push result displays at the top of the browser with a value of OK.

__ b. Review the changes to your BlueMix environment by selecting Build & Deploy.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-16 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 25: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Confirm that IBM DevOps successfully pushed the changes to the <yourname>Ex01 application on IBM BlueMix.

__ 3. Verify that the <yourname>Ex01 application is running.

__ a. Switch to your IBM BlueMix dashboard web browser tab.

__ b. Open the <yourname>Ex01 IBM BlueMix application overview page.

__ c. Wait until the <yourname>Ex01 application status is set to started.

__ 4. Test the <yourname>Ex01 application in a web browser.

__ a. From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-17

Page 26: vy1021xstud

Student Exercises

__ b. Confirm that the web page opens the web page at http://<yourname>.mybluemix.net.

The callback function must call response.write() or response.end() to send the response message to the web browser. Node.js keeps the HTTP connection open but it does not send the data to the web browser until the application calls one of the two functions.

Part 5: Update and deploy changes to your application

The IBM DevOps service and the IBM BlueMix environment seamlessly works together to push changes to your test and production environments. In this section, fix the issue with your IBM SDK for Node.js application and push the change to your IBM BlueMix account. Verify that your update works correctly on the mybluemix.net site.

__ 1. Open the IBM DevOps project for the <yourname>Ex01 application.

__ a. In the <yourname>Ex01 application page on IBM BlueMix, select Edit Code.

__ 2. Add a statement to close the HTTP response message connection in hellotoday.js.

__ a. The IBM DevOps project for the <yourname>Ex01 application appears. Open hellotoday.js.

__ b. Add the following statement at the end of the callback function in the http.createServer() call:

response.end();

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-18 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 27: vy1021xstud

Student ExercisesV9.0

EXempty

__ 3. Save the file.

__ 4. Close hellotoday.js.

Note

For more detailed instructions on how to commit, push, and test an IBM BlueMix application from IBM DevOps services, review the previous section of this exercise.

__ 5. Commit the changes to the <yourname>Ex01 Git repository.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-19

Page 28: vy1021xstud

Student Exercises

__ 6. Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.

__ 7. Verify that the <yourname>Ex01 application is running.

__ 8. Test the <yourname>Ex01 application in a web browser.

__ a. From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.

__ b. Confirm that the web page opens the web page at http://<yourname>.mybluemix.net.

__ c. Confirm that the web page displays the following message: Hello WebSphere!

Part 6: Write a dynamic message in the HTTP response message

You verified that the <yourname>Ex01 application returns an HTTP response message to the client. In this section, modify the message that your application sends back to the client. Specifically, send a message in the form of “Hello <day>!”, where <day> is the current day of the week. For example, the message is “Hello Monday!” when the client runs the application on Monday.

__ 1. Open the hellotoday.js script in your IBM DevOps account.

__ a. In your <yourname>Ex01 application in the IBM BlueMix web page, select Edit Code.

__ b. In the <yourname>Ex01 IBM DevOps project, open hellotoday.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-20 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 29: vy1021xstud

Student ExercisesV9.0

EXempty

__ 2. Write a JavaScript program that displays the day of the week in the web browser.

__ a. In the hellotoday.js script, locate the anonymous callback function in the http.createServer() function call.

var server = http.createServer( function(request, response) {var body = 'Hello WebSphere!';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});

__ b. Remove the var body = 'Hello WebSphere!' line.

__ c. Write a program that displays the text “Happy <day>!” to the console log. Replace <day> with the current day of the week. For example, print “Happy Monday!” when you run the script on Monday.

Hint

The Date JavaScript object returns the current day of the week with the getDay() method.

For example:

var date = new Date();response.write(date.getDay());

The code prints the number 1 to the console log on Monday.

On Monday, the following script writes the text “The day of the week is 1.” to the web browser.

response.write("The day of the week is " + date.getDay() + ".");

To print the sentence “Happy Monday!” on Monday, you must map the number 1 to the string “Monday”.

One technique is to map numbers to string values with an array. For example, you define an array of strings for each day of the week.

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

Keep in mind that array indexes start with 0, not 1. For example, days[0] maps to the string “Monday”.

__ 3. Save the script as hellotoday.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-21

Page 30: vy1021xstud

Student Exercises

Note

For more detailed instructions on how to commit, push, and test an IBM BlueMix application from IBM DevOps services, review the previous section of this exercise.

__ 4. Commit the changes to the <yourname>Ex01 Git repository.

__ 5. Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.

__ 6. Verify that the <yourname>Ex01 application is running.

__ 7. Test the <yourname>Ex01 application in a web browser.

__ a. From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.

__ b. Confirm that the web page opens the web page at http://<yourname>.mybluemix.net:8080.

__ 8. Confirm that the web page displays a dynamic greeting according to the day of the week:

Hint

If your greeting does not match the screen capture, compare your work against the solution at the end of this exercise.

Part 7: Defining a module

By design, Node.js provides a minimal set of features to support server-side applications. Node.js provides a collection of components, called modules, that encapsulate server features.

In this section, take the hellotoday.js sample application and export its function as a user-defined module.

__ 1. Create the today Node package.

__ a. In the IBM DevOps <yourname>Ex01 project, select File > New > Folder from the menu bar.

__ b. Enter today as the folder name.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-22 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 31: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Confirm that the IBM DevOps <yourname>Ex01 project includes the today folder.

__ 2. Define a package manifest file for the today module.

__ a. In the IBM DevOps project, select the today folder.

__ b. Select File > New > File from the menu bar.

__ c. Create a text file, package.json, in the today folder.

__ d. Enter the following package description into the package.json file:

{ "name": "today", "main": "./lib/today" }

__ e. Save the package.json file.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-23

Page 32: vy1021xstud

Student Exercises

Note

You now have a package.json file in the root directory of the project, and another package.json file in the today folder. Both the main Node module and the today module has its own package manifest file.

__ 3. Define a function named dayOfWeek in the /today/lib/today.js script.

__ a. In the today directory, create a directory with a name of lib.

__ b. Create a file today.js in the today/lib directory.

__ c. In the today.js script, define a Node module with a function, dayOfWeek, that returns the day of the week.

Hint

In a previous section, you wrote an application that returns the day of the week. Copy your implementation from hellotoday.js into today.js. Encapsulate the implementation into a function.

Node.js adds an object that is visible to other Node applications: exports. To export a function to other Node applications, add an anonymous function as a property to exports:

exports.dayOfWeek = function() {return "My exported function!";

}

__ 4. Save your changes to the /today/lib/today.js script.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-24 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 33: vy1021xstud

Student ExercisesV9.0

EXempty

Part 8: Importing a module into your application

In this section, create a JavaScript application, helloclient.js, that imports the today Node module.

__ 1. Create a Node script called helloclient.js.

__ a. In the <yourname>Ex01 project, select the main directory.

__ b. Select File > New > File from the menu bar.

__ c. Set the file name to helloclient.js.

__ 2. Write a Node application that listens to HTTP requests with the IBM SDK for Node.js runtime on IBM BlueMix.

__ a. Copy the source code from hellotoday.js.

__ b. Paste the sample code into helloclient.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-25

Page 34: vy1021xstud

Student Exercises

__ c. In the anonymous function within the http.createServer() call, delete the body variable declaration.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);var http = require(‘http’);

var server = http.createServer(function(request,response){response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});server.listen(port,host);

__ 3. Write a Node application that displays the greeting “Good day, <day>!” with the today.dayOfWeek function. The variable <day> represents the day of the week.

__ a. Assign a variable named today to the today module.

var today = require('./today');

__ b. Before the response.writeHead() call in the callback function, write out the greeting with the day of the week.

var body = 'Good day, ' + today.dayOfWeek() + '!';

__ 4. Verify that your helloclient.js script matches the sample code.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var today = require('./today');

var server = http.createServer( function(request, response) {var body = 'Good day, ' + today.dayOfWeek() + '!';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});server.listen(port);

__ 5. Save helloclient.js.

__ 6. Modify manifest.yml to run helloclient.js.

__ a. Open manifest.yml.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-26 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 35: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Change the command parameter to node helloclient.js.

__ c. Save manifest.yml.

Note

For more detailed instructions on how to commit, push, and test an IBM BlueMix application from IBM DevOps services, review the previous section of this exercise.

__ 7. Commit the changes to the <yourname>Ex01 Git repository.

__ 8. Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.

__ 9. Verify that the <yourname>Ex01 application is running.

__ 10. Test the <yourname>Ex01 application in a web browser.

__ a. From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.

__ b. Confirm that the web page opens the web page at http://<yourname>.mybluemix.net.

__ 11. Confirm that the web page displays a dynamic greeting according to the day of the week:

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-27

Page 36: vy1021xstud

Student Exercises

Note

If the greeting is not correct, check your implementation in the following files:

helloclient.js/today/lib/today.js/today/package.json

You can also compare your implementation against the model solution at the end of this exercise write-up.

End of exercise

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-28 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 37: vy1021xstud

Student ExercisesV9.0

EXempty

Solution

Sample code for hellotoday.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var server = http.createServer( function(request, response) {var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",

"Saturday", "Sunday"];var date = new Date();

var body = 'Hello ' + days[date.getDay() - 1] + '!';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});server.listen(port);

Sample code for /today/lib/today.js:

var date = new Date();var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

exports.dayOfWeek = function () {return days[ date.getDay() - 1 ];

};

Sample definition for /today/package.json:

{ "name": "today", "main": "./lib/today" }

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-29

Page 38: vy1021xstud

Student Exercises

Sample code for helloclient.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var today = require('./today');var server = http.createServer( function(request, response) {

var body = 'Good day, ' + today.dayOfWeek() + '!';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});server.listen(port);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-30 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 39: vy1021xstud

Student ExercisesV9.0

EXempty

Exercise review and wrap-up

The first part of the exercise you created an IBM SDK for Node.js application in IBM BlueMix environment. You created a Git repository in IBM DevOps to store the source code for the application.

In the second part of the exercise, you developed a Node application that displayed a result as an HTTP response message. Building on that example, you developed a Node module that factored out the logic for the application.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 1. Set up your Node.js development environment in IBM 1-31

Page 40: vy1021xstud

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-32 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 41: vy1021xstud

Student ExercisesV9.0

EXempty

Exercise 2. Asynchronous I/O with callback

What this exercise is about

In this exercise, implement callback functions that intercept network traffic directed on a server resource. Parse the JSON data within the network message. Create a response message from the network request. Test the callback method with a web browser.

What you should be able to do

At the end of this exercise, you should be able to:

• Develop anonymous JavaScript functions

• Handle network traffic with anonymous callback functions

• Parse JSON data from network

Introduction

One common pattern for Node applications is a proxy for an external web service. With the http module from the Node programming model, developers can send HTTP requests and handle HTTP responses.

Since network calls in the IBM SDK for Node.js programming model are asynchronous by nature, you develop callback functions to handle segments of the response message as the Node application receives them.

Requirements

You must install and configure the IBM SDK for Node.js according to the instructions in exercise 1.

Before you start this exercise, sign up for an IBM BlueMix and an IBM DevOps account.

This exercise requires a workstation with internet access. You can complete this exercise on a computer that runs Linux, Mac OS, or Microsoft Windows. For a list of compatible web browsers, see: https://developer.ibm.com/bluemix/support/#prereqs

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-1

Page 42: vy1021xstud

Student Exercises

Exercise instructions

Part 1: Review the National Weather Service weather observation web service

The National Weather Service provides weather observations from major airports in the United States. You can retrieve the current weather conditions from a web service on the weather.gov website. Review the format of the XML data from the web service.

__ 1. Review the current weather observation at San Francisco International Airport.

__ a. In a web browser, open http://weather.gov/xml/current_obs/KSFO.xml

__ b. Select the View Page Source command to examine the contents of the KSFO.xml file.

<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?><current_observation version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=

"http://www.weather.gov/view/current_observation.xsd"><credit>NOAA's National Weather Service</credit><credit_URL>http://weather.gov/</credit_URL> ...<observation_time>Last Updated on May 29 2014, 12:56 pm PDT

</observation_time><observation_time_rfc822>Thu, 29 May 2014 12:56:00 -0700

</observation_time_rfc822><weather>A Few Clouds</weather><temperature_string>77.0 F (25.0 C)</temperature_string><temp_f>77.0</temp_f><temp_c>25.0</temp_c> ...

</current_observation>

__ c. Locate the XML element that displays the current temperature reading in degrees Fahrenheit.

Optional

The International Civil Aviation Organization (ICAO) airport code for San Francisco International Airport is KSFO. To view the current weather observation at another US airport, browse to:

http://weather.gov/xml/current_obs/<airport_code>.xml

Replace <airport_code> with a valid ICAO airport code.

Examples of ICAO airport codes:

• KORD – Chicago O’Hare International Airport, Chicago, Illinois:

• KLAX – Los Angeles International Airport, Los Angeles, California

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-2 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 43: vy1021xstud

Student ExercisesV9.0

EXempty

• KSJC – San Jose International Airport, San Jose, California

• KSEA – Seattle-Tacoma International Airport, Seattle, Washington

• KEWR – Newark International Airport, Newark, New Jersey

• KJFK – Kennedy International Airport, New York, New York

• KLGA – La Guardia Airport, New York, New York

• KIAD – Washington-Dulles International Airport, Dulles, Virginia

• KATL – Hartsfield-Jackson Atlanta International Airport, Atlanta, Georgia

Part 2: Set up the IBM SDK for Node.js run time environment

Before you build your IBM SDK for Node.js application, you must set up an application run time on IBM BlueMix and a Git repository for the application on IBM DevOps services.

__ 1. Log in to your IBM BlueMix account.

__ a. Open a web browser.

__ b. Navigate to https://bluemix.net.

__ c. Click on the Log in link on the page.

__ d. Enter your IBM ID and password for your IBM BlueMix account.

__ e. Click Sign in.

__ 2. Create an application with the IBM SDK for Node.js server run time environment.

__ a. In your IBM BlueMix account page, select Dashboard.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-3

Page 44: vy1021xstud

Student Exercises

__ b. Click on Create an App in the application section of the Dashboard.

__ c. In the list of application types, select SDK for Node.js from the Runtimes catalog.

__ d. In the application wizard, enter the following

- Host: <yourname>Ex02

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-4 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 45: vy1021xstud

Student ExercisesV9.0

EXempty

- Name: <yourname>Ex02

Note

Replace <yourname> with your user name. The value of <yourname> must be unique across all BlueMix accounts.

__ e. Leave the Selected Plan setting to Default.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-5

Page 46: vy1021xstud

Student Exercises

__ 3. Confirm that the IBM SDK for Node.js run time environment starts successfully in your IBM BlueMix account.

__ a. Wait until your <yourname>Ex02 application is in the Started state.

Information

Git is an open source, distributed version control system. The IBM DevOps services hosts Git repositories for your IBM BlueMix applications.

__ 4. Create a Git repository in IBM DevOps services to manage the source code of your application.

__ a. In the IBM BlueMix application overview page for <yourname>Ex02, select Add Git.

__ b. Log in to IBM DevOps services with the Jazz ID you created.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-6 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 47: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Make sure to uncheck the option labeled “Populate the repository with the start application package and deploy it to the application”.

Information

The default option creates a sample IBM SDK for Node.js application in the Git repository on IBM DevOps. Since you are creating your own application, uncheck this option to create a Git repository without any implementation code.

__ d. Click Continue.

__ e. After the wizard creates the Git repository, select Close.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-7

Page 48: vy1021xstud

Student Exercises

__ 5. Open the IBM DevOps project for the <yourname>Ex02 application.

__ a. In the BlueMix application dashboard, select Edit Code beside the Git URL link.

__ b. Wait until the Git repository for your application appears.

Part 3: Create a server application

In this section, build a server application that returns a greeting to the client’s web browser.

__ 1. Create a Node script, weather-request.js.

__ a. In the IBM DevOps <yourname>Ex02 Git project, select File > New > File from the menu bar.

__ b. Set the file name as weather-request.js.

__ 2. Develop a Node application that creates a web server for the default IBM BlueMix application port.

__ a. Open weather-request.js in the IBM DevOps editor.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-8 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 49: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Define the IBM BlueMix application host and port variables at the beginning of the script.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

__ c. Define a variable, http, as a reference to the http Node module.

var http = require('http');

__ d. Create a server object with the http.createServer() function.

var server = http.createServer( function(request, response) {});

__ e. Add a sample HTTP response message body and header to the response object.

var server = http.createServer( function(request, response) {var body = 'This is a test.';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});

__ f. Set the server object to listen to HTTP requests on the default IBM BlueMix application port.

server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-9

Page 50: vy1021xstud

Student Exercises

__ 3. Verify that the weather-request.js script matches the solution.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var server = http.createServer( function(request, response) { var body = 'This is a test.'; response.writeHead( 200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); response.write(body); response.end();});

server.listen(port, host);

__ 4. Save weather-request.js.

__ 5. Create a manifest.yml file to describe how to deploy the <yourname>Ex02 application to your BlueMix account.

__ a. Create a file named manifest.yml.

__ b. Open manifest.yml in an editor view.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-10 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 51: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Add the following lines to the manifest.yml file.

applications:- disk_quota: 1024M host: <yourname>Ex02 name: <yourname>Ex02 command: node weather-request.js path: . domain: mybluemix.net instances: 1 memory: 128M

__ d. Save manifest.yml.

__ 6. Create a package.json file to describe the Node module dependencies for the <yourname>Ex02 application.

__ a. Create a file named package.json.

__ b. Open package.json in an editor view.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-11

Page 52: vy1021xstud

Student Exercises

__ c. Add the following lines to the package.json file.

{"name": "Exercise02App","version": "1.0","description": "A nodejs app for Bluemix"

}

__ d. Save package.json.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-12 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 53: vy1021xstud

Student ExercisesV9.0

EXempty

Part 4: Deploy and test the application in IBM BlueMix

Make sure that the sample Node application runs properly before you continue on this exercise. Commit your changes to the Git repository and publish your work to your IBM BlueMix application. Test the application from a web browser.

__ 1. Commit the changes to the <yourname>Ex02 Git repository.

__ a. In the IBM DevOps web page, select the Git repository icon in the toolbar.

__ b. The Git repository page lists the recently changed files in your project. Enter a comment to describe the changes in this revision.

__ c. Check Select All to mark all changed files for check in.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-13

Page 54: vy1021xstud

Student Exercises

__ d. Select Commit to save the revision to the repository.

__ 2. Push the changes to the <yourname>Ex02 application on the IBM BlueMix environment.

__ a. In the Deploy view of the Git repository page, click Push.

__ 3. Review the changes in your IBM BlueMix account.

__ a. In your IBM BlueMix account page, open the <yourname>Ex02 application.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-14 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 55: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Wait until the <yourname>Ex02 application status is set to started.

__ 4. Test the <yourname>Ex02 application in a web browser.

__ a. From the IBM BlueMix web page for the <yourname>Ex02 application, select Routes.

__ b. Confirm that the web page opens the web page at http://<yourname>Ex02.mybluemix.net.

Note

You set up a sample web application running on the IBM SDK for Node.js runtime in your IBM BlueMix account. In the rest of this exercise, you build upon this sample application to explore the features of the Node framework.

Part 5: Make an HTTP request to a third-party web service

The National Weather Service web service returns the current weather observation as an XML document. In this part, write a Node application that makes an HTTP request to the web service. Parse through the response and return the current observation and temperature reading.

__ 1. Remove the sample application code from weather-request.js.

__ a. Open weather-request.js in the IBM DevOps service project.

__ b. Remove the code inside the http.createServer() anonymous callback function.

var server = http.createServer( function(request, response) {});

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-15

Page 56: vy1021xstud

Student Exercises

__ 2. Develop a Node application that makes a web service call to the National Weather Service web service.

__ a. Store the host name and relative path to the weather observation web service in an object.

var options = { host: 'w1.weather.gov', path: '/xml/current_obs/KSFO.xml'};

__ b. In the anonymous function in the http.createServer parameter, write a callback function to handle two network events: ‘data’ and ‘end’.

var weatherCallback = function(weatherResponse) {var buffer = '';

weatherResponse.on('data', function(chunk){buffer += chunk;

});

weatherResponse.on('end', function() {var body = buffer;response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});};

Information

Certain Node objects send out events. To register a listener to an event, call the object.on(event, callback) function with two parameters: the event name, and a callback function that Node calls when the event fires.

When the response object sends a ‘data‘ event, it passes a part of the HTTP response message body to the first parameter of the callback function. The buffer variable saves each data ‘chunk’ as it is sent to the client. The same object emits ‘end’ when the remote server finishes sending the response message.

__ c. Make a web service call with the http.request() function.

var weatherRequest = http.request( options, weatherCallback );

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-16 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 57: vy1021xstud

Student ExercisesV9.0

EXempty

Information

Use the http.request() function to make an HTTP method call. The function takes two parameters:

http.request(options, callback);

The options parameter is an object with two properties. Host is the host name of the web service. Path stores the relative path to the web service resource.

When the http module receives a response from the remote server, it calls the callback function. Access the contents of the web service reply message from the response parameter.

__ d. Add an error handler for the request. The Node framework starts the callback function if an error occurs when it sends the request message.

weatherRequest.on('error', function(e) {response.writeHead( 500, {

'Content-Length': e.message.length,'Content-Type': 'text/plain'

});response.write(e.message);response.end();

});

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-17

Page 58: vy1021xstud

Student Exercises

__ 3. Compare your code against the exercise solution.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var options = {host: 'w1.weather.gov',path: '/xml/current_obs/KSFO.xml'

};

var server = http.createServer( function(request, response) {

var weatherCallback = function(weatherResponse) {var buffer = '';

weatherResponse.on('data', function(chunk){buffer += chunk;

});

weatherResponse.on('end', function() {var body = buffer;response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});};

var weatherRequest = http.request( options, weatherCallback );

weatherRequest.on('error', function(e) {response.writeHead( 500, {

'Content-Length': e.message.length,'Content-Type': 'text/plain'

});response.write(e.message);response.end();

});});

server.listen(port, host);

__ 4. Save the weather-request.js script.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-18 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 59: vy1021xstud

Student ExercisesV9.0

EXempty

Part 6: Test the HTTP request to a third-party web service

Start the weather-request.js script from the IBM BlueMix application page. Compare the weather observation information against the data from the National Weather Service web page.

__ 1. Commit the changes in the weather-request.js script to the IBM DevOps Git repository.

__ 2. Push the changes to your IBM BlueMix <yourname>Ex02 application.

__ 3. Verify that IBM BlueMix successfully restarted the <yourname>Ex02 application.

__ 4. Test the <yourname>Ex02 application.

__ a. In the <yourname>Ex02 application summary page, select the Routes link.

__ b. Verify that your web browser opens the link at http://<yourname>ex02.mybluemix.net.

<HTML><HEAD>

<TITLE>Request Timeout</TITLE></HEAD><BODY><H1>Request Timeout</H1>The server timed out while waiting for the browser's request.<P>Reference&#32;&#35;2&#46;4f3600cc&#46;1416962068&#46;0</BODY></HTML>

Information

After the http.request() function completes, it returns a request object. To send a request to the remote server, you must call request.end() to close the network connection.

If you do not call request.end(), the remote server returns a timeout error in the HTTP response message.

__ 5. Open the weather-request.js script in the IBM DevOps editor.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-19

Page 60: vy1021xstud

Student Exercises

__ 6. Call weatherRequest.end() to close the network connection to the web service.

__ a. Add a call to the weatherRequest.end() function in the line after the http.request() function call.

var weatherRequest = http.request( options, weatherCallback );weatherRequest.end();

__ b. Save your changes to the script.

__ 7. Commit the changes in the weather-request.js script to the IBM DevOps Git repository.

__ 8. Push the changes to your IBM BlueMix <yourname>Ex02 application.

__ 9. Verify that IBM BlueMix successfully restarted the <yourname>Ex02 application.

__ 10. Test the <yourname>Ex02 application..

__ a. Open http://<yourname>ex02.mybluemix.net in a web browser.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-20 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 61: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Examine the response in the web browser.

<?xml version="1.0" encoding="ISO-8859-1"?><?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?><current_observation version="1.0" ... > ... <weather>Partly Cloudy</weather> <temperature_string>64.0 F (17.8 C)</temperature_string> <temp_f>64.0</temp_f> <temp_c>17.8</temp_c> ...</current_observation>

__ c. The weather-request.js script prints the response from the National Weather Service web service. Confirm that the weather observation matches the result that you retrieved earlier in this exercise.

Part 7: Parse the web service response message

The weather-request.js Node application prints the entire HTTP response message body. In this part, parse through the message and print the temperature in degrees Fahrenheit from the weather observation.

__ 1. In the IBM DevOps service <yourname>Ex02 project, open weather-request.js in a text editor.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-21

Page 62: vy1021xstud

Student Exercises

__ 2. Modify the response.on(’end’) event handler. Parse and display the value in the temp_f XML element from the HTTP response message body.

__ a. Write a regular expression to match the <temp_f> XML element tag.

var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g);

__ b. If the regular expression matches a result, strip the XML element tag from the match.

if ( null != matches && matches.length > 0 ) {body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/, "");

}

__ c. Print the result into the console log.

console.log(result);

__ 3. Compare your weatherResponse.on(...) event hander against the solution code.

weatherResponse.on('end', function() {var body = buffer;var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g);if ( null != matches && matches.length > 0 ) {

body = matches[0].replace(/\<temp_f>/, "").replace(/\<\/temp_f\>/, "");

}response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});};

__ 4. Save your changes.

__ 5. Commit the changes in the weather-request.js script to the IBM DevOps Git repository.

__ 6. Push the changes to your IBM BlueMix <yourname>Ex02 application.

__ 7. Verify that IBM BlueMix successfully restarted the <yourname>Ex02 application.

__ 8. Test the <yourname>Ex02 application.

__ a. Open http://<yourname>ex02.mybluemix.net in a web browser.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-22 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 63: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Verify that the current weather reading in degrees Fahrenheit appears in the console.

Part 8: Create a package for the weather observation web service client

In the previous section, you tested weather-request.js, a Node application that starts the National Weather Service web service. Take the logic from the script and place it into a custom Node package.

__ 1. Create a Node package named weather.

__ a. In the IBM DevOps <yourname>Ex02 application project, create a folder with the name weather.

__ b. Within the weather folder, create a folder with the name lib.

__ c. Move weather-request.js to the ‘weather/lib’ directory.

__ d. Define a package.json file in the weather folder.

{ "name": "weather", "main": "./lib/weather-request" }

Information

The main property defines the primary entry point into the package. State the relative path and the name of the script.

__ 2. Export a function named ‘current’ that saves the current weather reading to the temp_f parameter.

__ a. Open /lib/weather-request.js in a text editor.

__ b. After the var options = {...} statement, add current as a property to the exports object.

__ c. Add a parameter, temp_f, to the anonymous function assigned to the current property.

exports.current = function( temp_f ) {

};

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-23

Page 64: vy1021xstud

Student Exercises

__ d. In the event handler for the ‘end’ response event, save the weather observation reading to the temp_f parameter.

weatherResponse.on('end', function() { var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g); if ( null != matches && matches.length > 0 ) { var result = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/, ""); } temp_f = result;});

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-24 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 65: vy1021xstud

Student ExercisesV9.0

EXempty

__ e. Place the code for the web service call from the weather-request.js script into the anonymous function.

var http = require('http');

var options = {host: 'w1.weather.gov',path: '/xml/current_obs/KSFO.xml'

};

exports.current = function ( temp_f ) {var weatherCallback = function(weatherResponse) {

var buffer = '';

weatherResponse.on('data', function(chunk){buffer += chunk;

});

weatherResponse.on('end', function() {var body = buffer;var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g);if ( null != matches && matches.length > 0 ) {

body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/,"");

}temp_f = body;

});};

var weatherRequest = http.request( options, weatherCallback );weatherRequest.end();

};

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-25

Page 66: vy1021xstud

Student Exercises

__ 3. Save /weather/lib/weather-request.js.

__ 4. Create a Node application that starts the current function from the weather package.

__ a. In the root directory of the <yourname>Ex02 application project, create a file with the name weather-caller.js.

__ b. Define the host and port variables for the IBM BlueMix application.

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

__ c. Import the http and weather packages to the script.

var http = require('http');var weather = require('./weather');

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-26 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 67: vy1021xstud

Student ExercisesV9.0

EXempty

__ d. Call the current method from the weather Node package.

var server = http.createServer( function(request, response) {var temp_f = '';weather.current(temp_f);

var body = 'The current weather reading is ' + temp_f +' degrees Fahrenheit';

response.writeHead( 200, {'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});server.listen(port, host);

__ 5. Save weather-caller.js in the Node installation directory.

__ 6. Update manifest.yml to invoke the weather-caller.js script.

__ a. Open manifest.yml.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-27

Page 68: vy1021xstud

Student Exercises

__ b. Change the command property to node weather-caller.js.

applications:- disk_quota: 1024M host: warrenfEx02 name: warrenfEx02 command: node weather-caller.js path: . domain: mybluemix.net instances: 1 memory: 128M

__ c. Save manifest.yml.

__ 7. Commit the changes to the IBM DevOps Git repository.

__ 8. Push the changes to your IBM BlueMix <yourname>Ex02 application.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-28 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 69: vy1021xstud

Student ExercisesV9.0

EXempty

__ 9. Verify that IBM BlueMix successfully restarted the <yourname>Ex02 application.

__ 10. Test the <yourname>Ex02 application.

__ a. Open http://<yourname>ex02.mybluemix.net in a web browser.

__ b. Verify that the current weather reading in degrees Fahrenheit appears in the console.

The current weather reading is degrees Fahrenheit

Questions

In the previous part, you verified that the weather.current function calls the National Weather Service properly. However, the weather reading is not passed back to the weather-caller application. Why is the value of temp_f blank?

The JavaScript application does not wait for the HTTP response message before it completes the weather.current() function call.

To retrieve the weather reading, the weather-caller application must pass a callback function to the weather.current() function. When weather.current() finishes processing the HTTP response message, it calls the callback function to pass the weather reading to weather-caller.

Although this style is more complicated than a return parameter, it ensures that the Node.js server does not block the execution of a thread while waiting on a response.

__ 11. Create a callback function in the weather-caller.js application.

__ a. Open weather-caller.js in a text editor.

__ b. Remove the temp_f variable declaration.

__ c. Remove the temp_f parameter from the weather.current() function call.

__ d. In the weather.current() function call, add an anonymous function that displays the temperature reading as a parameter.

weather.current( function( temp_f ) { response.write("The current weather reading is %s degrees Fahrenheit", temp_f); response.end();});

__ e. In the response.writeHead() call, remove the content-length header.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-29

Page 70: vy1021xstud

Student Exercises

__ f. Remove the response.write() and response.end() calls after response.writeHead().

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var weather = require('./weather');

var server = http.createServer( function(request, response) {weather.current( function(temp_f) {

response.writeHead( 200, {'Content-Type': 'text/plain'

});response.write('The current weather reading is ' + temp_f +

' degrees Fahrenheit');response.end();

});});server.listen(port, host);

__ g. Save weather-caller.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-30 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 71: vy1021xstud

Student ExercisesV9.0

EXempty

Information

The weather.current() call passes an anonymous function as the first parameter. This function prints the current weather reading into HTTP response message.

In the next step, modify the /weather/lib/weather-request.js script to call the callback function after the module receives the entire web service response message from the National Weather Service.

__ 12. Modify the weather-request.js script to return the weather reading to the callback function.

__ a. Open /weather/lib/weather-request.js in a text editor.

__ b. Change the function declaration for exports.current to accept a parameter that is named resultCallback.

exports.current = function ( resultCallback ) {

__ c. Locate the weatherResponse.on(‘end’, function() {...}) event handler function.

__ d. Remove the line temp_f = result.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-31

Page 72: vy1021xstud

Student Exercises

__ e. Invoke the callback function with the weather reading.

weatherResponse.on('end', function() { var body = buffer; var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g); if ( null != matches && matches.length > 0 ) { body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/, ""); } resultCallback(body);});

__ f. Save weather-request.js.

__ 13. Commit the changes to the IBM DevOps Git repository.

__ 14. Push the changes to your IBM BlueMix <yourname>Ex02 application.

__ 15. Verify that IBM BlueMix successfully restarted the <yourname>Ex02 application.

__ 16. Test the <yourname>Ex02 application.

__ a. Open http://<yourname>ex02.mybluemix.net in a web browser.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-32 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 73: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Verify that the current weather reading in degrees Fahrenheit appears in the console.

The current weather reading is 64.0 degrees Fahrenheit

End of exercise

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-33

Page 74: vy1021xstud

Student Exercises

Solution

Parts 1 to 4:

In the first part of this exercise, you create a sample IBM SDK for Node.js application in your IBM BlueMix account. Manage the source code for your application in the <yourname>Ex02 IBM DevOps services repository. You define a unique value for the <yourname> variable.

Sample code for weather-request.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var server = http.createServer( function(request, response) {var body = 'This is a test.';response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});

server.listen(port, host);

Parts 5 and 6:

In the first iteration of the application, the weather-request.js script is a stand-alone Node application. This script makes an http.request() call to the National Weather Service web service for the San Francisco International Airport.

The callback function in weather-request.js takes the HTTP response message and prints the response message body to the console log.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-34 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 75: vy1021xstud

Student ExercisesV9.0

EXempty

Sample code for weather-request.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var options = {host: 'w1.weather.gov',path: '/xml/current_obs/KSFO.xml'

};

var server = http.createServer( function(request, response) {

var weatherCallback = function(weatherResponse) {var buffer = '';

weatherResponse.on('data', function(chunk){buffer += chunk;

});

weatherResponse.on('end', function() {var body = buffer;response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});};

var weatherRequest = http.request( options, weatherCallback );weatherRequest.end();

weatherRequest.on('error', function(e) {response.writeHead( 500, {

'Content-Length': e.message.length,'Content-Type': 'text/plain'

});response.write(e.message);response.end();

});});

server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-35

Page 76: vy1021xstud

Student Exercises

Part 7:

In the second iteration of the application, you added a string match expression in the request.on(‘end’) event handler. The regular expression extracted the temperature reading in degrees Fahrenheit from the response message body.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-36 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 77: vy1021xstud

Student ExercisesV9.0

EXempty

Sample code for weather-request.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');

var options = {host: 'w1.weather.gov',path: '/xml/current_obs/KSFO.xml'

};

var server = http.createServer( function(request, response) {

var weatherCallback = function(weatherResponse) {var buffer = '';

weatherResponse.on('data', function(chunk){buffer += chunk;

});

weatherResponse.on('end', function() {var body = buffer;var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g);if ( null != matches && matches.length > 0 ) {

body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/, "");

}response.writeHead( 200, {

'Content-Length': body.length,'Content-Type': 'text/plain'

});response.write(body);response.end();

});};

var weatherRequest = http.request( options, weatherCallback );weatherRequest.end();

weatherRequest.on('error', function(e) {response.writeHead( 500, {

'Content-Length': e.message.length,'Content-Type': 'text/plain'

});response.write(e.message);response.end();

});

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-37

Page 78: vy1021xstud

Student Exercises

});

server.listen(port, host);

Part 8:

In the third iteration of the application, you encapsulated the logic from weather-request.js script in a Node module named weather. The Node application weather-caller.js imports the weather node and calls the weather.current() method to print the weather reading. The function does not return a value to the calling function.

Sample code for weather-caller.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var weather = require('./weather');

var server = http.createServer( function(request, response) {weather.current( function(temp_f) {

response.writeHead( 200, {'Content-Type': 'text/plain'

});response.write('The current weather reading is ' + temp_f +

' degrees Fahrenheit');response.end();

} );});server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-38 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 79: vy1021xstud

Student ExercisesV9.0

EXempty

Sample code for /weather/lib/weather-request.js:

var http = require('http');

var options = {host: 'w1.weather.gov',path: '/xml/current_obs/KSFO.xml'

};

exports.current = function ( resultCallback ) {var weatherCallback = function(weatherResponse) {

var buffer = '';

weatherResponse.on('data', function(chunk){buffer += chunk;

});

weatherResponse.on('end', function() {var body = buffer;var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g);if ( null != matches && matches.length > 0 ) {

body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/,"");

}resultCallback( body );

});};

var weatherRequest = http.request( options, weatherCallback );weatherRequest.end();

};

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 2. Asynchronous I/O with callback 2-39

Page 80: vy1021xstud

Student Exercises

Exercise review and wrap-up

The first part of the exercise explored the HTTP interface from the Node.js API. You send HTTP request messages and process response messages with the http module. Since servers send HTTP messages in parts, your callback function must collect and assemble individual chunks of a response message.

The second part of the exercise focused on the role of callback functions in Node applications. As AJAX network calls are asynchronous in nature, you must provide a callback function to handle a response message and pass a result back to the original application. This design makes Node applications call a nest of callback functions. Before you implement your application, draw out a sequence diagram to trace the flow of calls and callbacks between different parts of your application.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-40 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 81: vy1021xstud

Student ExercisesV9.0

EXempty

Exercise 3. Node packages

What this exercise is about

This exercise covers how to design custom Node modules. Learn how to pass input parameters to a module function. Return error information and status to the calling function. Build a web application on IBM SDK for Node.js with the Express framework. Install and import a third-party Node module in your application.

What you should be able to do

At the end of this exercise, you should be able to:

• Pass objects as parameters to functions

• Return error objects from Node module functions

• Parse XML data with the xml2js module

• Set up the Express web application framework on IBM SDK for Node.js

• Create an Express server object

Introduction

This exercise focuses on common programming patterns when a developer writes a custom Node module. In the first part, you pass a JavaScript object that encapsulates input parameters. In the second part, you place an error object as the first parameter in a callback function. In the last part, you import ready-made Node modules from the Node Package Manager (npm) website.

Requirements

Before you start this exercise, sign up for an IBM BlueMix and an IBM DevOps account.

You must complete the instructions in exercise 2 before starting this lab.

This exercise requires a workstation with internet access. You can complete this exercise on a computer that runs Linux, Mac OS, or Microsoft Windows. For a list of compatible web browsers, see: https://developer.ibm.com/bluemix/support/#prereqs.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-1

Page 82: vy1021xstud

Student Exercises

Exercise instructions

Part 1: Fork the IBM DevOps repository from the previous exercise

In the previous exercise, you developed an IBM BlueMix application that returns the current weather reading from San Francisco International Airport.

You copy your exercise 2 application as a starting point for exercise 3.

__ 1. Create an IBM BlueMix application, <yourname>Ex03.

__ 1. Log in to your IBM BlueMix account.

__ a. Open a web browser.

__ b. Navigate to https://bluemix.net.

__ c. Click on the Log in link on the page.

__ d. Enter your IBM ID and password for your IBM BlueMix account.

__ e. Click Sign in.

__ 2. Create an application with the IBM SDK for Node.js server run time environment.

__ a. In your IBM BlueMix account page, select Dashboard.

__ b. Click on Create an App in the application section of the Dashboard.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-2 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 83: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. In the list of application types, select SDK for Node.js from the Runtimes catalog.

__ d. In the application wizard, enter the following

- Host: <yourname>Ex03

- Name: <yourname>Ex03

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-3

Page 84: vy1021xstud

Student Exercises

Note

Replace <yourname> with your user name. The value of <yourname> must be unique across all BlueMix accounts.

__ e. Leave the Selected Plan setting to Default.

__ 3. Confirm that the IBM SDK for Node.js run time environment starts successfully in your IBM BlueMix account.

__ a. Wait until your <yourname>Ex03 application is in the Started state.

Note

Instead of creating a Git repository, make a copy of the IBM DevOps repository from exercise 2 as the starting point from this exercise.

__ 4. Open your IBM DevOps account.

__ a. Open https://hub.jazz.net in a web browser.

__ b. Log in with your IBM DevOps user name and password.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-4 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 85: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Select your <yourname>Ex02 project. Recall that <yourname> is the name that you assigned to your projects.

__ 5. Fork the exercise 2 application into a separate application, <yourname>Ex03.

__ a. In the <yourname>Ex02 project page, select Fork Project.

__ b. Set the project name to <yourname>Ex03.

__ c. Make sure that the Deploy to Bluemix option is selected.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-5

Page 86: vy1021xstud

Student Exercises

__ d. Confirm that the organization is set to your IBM BlueMix account.

__ e. Click Create.

__ 6. Update the manifest file to <yourname>Ex03.

__ a. In the <yourname>Ex03 project, open manifest.yml.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-6 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 87: vy1021xstud

Student ExercisesV9.0

EXempty

__ b. Change the name and host properties to <yourname>Ex03.

__ c. Save and close the file.

__ 7. Update application name in the package.json file to ‘Exercise03App’.

__ a. Open package.json.

__ b. Edit the value of the name property to “Exercise03App”.

__ c. Save and close the file.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-7

Page 88: vy1021xstud

Student Exercises

__ 8. Update the project.json file to <yourname>Ex03.

__ a. Open project.json.

__ b. Edit the value of the name property to “<yourname> | <yourname>Ex03”.

__ c. Save and close the file.

__ 9. Set the deployment target to your IBM BlueMix <yourname>Ex03 application.

__ a. From the menu bar, select Build and Deploy.

__ b. Select the Simple deployment setting.

__ c. Examine the Deploy To field. You must change this setting from the <yourname>Ex02 IBM BlueMix application to the <yourname>Ex03 application.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-8 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 89: vy1021xstud

Student ExercisesV9.0

EXempty

__ d. Select Configure.

__ e. In the Link to application field, change the setting to <yourname>Ex03.

__ f. Click Submit.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-9

Page 90: vy1021xstud

Student Exercises

__ 10. Deploy the application to the <yourname>Ex03 IBM BlueMix application project.

__ a. Select Git Repository from the sidebar.

__ b. Commit the changes to the repository.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-10 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 91: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. Select Force Push All to deploy the entire application to your IBM BlueMix <yourname>Ex03 application space.

__ 11. Test the <yourname>Ex03 application on IBM BlueMix.

__ a. Open the IBM BlueMix dashboard.

__ b. Open the <yourname>Ex03 application.

__ c. Confirm that the application is running.

__ d. Select the routes link.

__ e. Verify that the application returns the current weather observation at San Francisco International Airport.

Part 2: Pass parameters to a Node module function

The application returns the current weather reading from San Francisco International Airport. Make the weather module more general in scope by passing input parameters into the current function.

__ 1. Modify /weather/lib/weather-request.js to accept an object as an input parameter.

__ a. Open /weather/lib/weather-request.js in a text editor.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-11

Page 92: vy1021xstud

Student Exercises

__ b. Change the anonymous function declaration for exports.current to accept a parameter with the name of param.

__ c. Modify the options.path property to build the HTTP request path in the call to the National Weather Service web service.

exports.current = function ( param, resultCallback ) { var options = { host: 'w1.weather.gov', path: '/xml/current_obs/' + param.location + '.xml' }; ...}

__ d. Save /weather/lib/weather-request.js.

__ 2. Modify the weather-caller.js application to pass a location code to the weather.current function call.

__ a. Open weather-caller.js in a text editor.

__ b. Add a variable, param.

__ c. Assign an object to param, with the property location = ‘KSFO’.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-12 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 93: vy1021xstud

Student ExercisesV9.0

EXempty

__ d. Call weather.current with the location variable as the first parameter.

var weather = require('./weather');var param = { location: 'KSFO' };

var server = http.createServer( function(request, response) { weather.current( param, function(temp_f) { ... });});

__ e. Save weather-caller.js.

__ 3. Commit the changes to the IBM DevOps Git repository.

__ 4. Push the changes to your IBM BlueMix <yourname>Ex03 application.

__ 5. Verify that IBM BlueMix successfully restarted the <yourname>Ex03 application.

__ 6. Test the <yourname>Ex03 application.

__ a. In the <yourname>Ex03 application summary page, select the Routes link.

__ b. Verify that your web browser opens the link at http://<yourname>ex03.mybluemix.net.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-13

Page 94: vy1021xstud

Student Exercises

__ c. Confirm that the application prints the current weather conditions for San Francisco International Airport.

The current weather reading is 63.0 degrees Fahrenheit

Part 3: Propagating errors to callback functions

As an asynchronous framework, node.js makes extensive use of callback functions to return values back to the calling function.

The node.js modules in the SDK use a convention of passing the error object as the first parameter in a callback function:

function ( error, parameter, ... ) { ... }

With this convention, the calling function always knows to check the first parameter for any error messages. If the error parameter is null, then the function processes the remaining parameters from the call.

__ 1. In weather-caller.js, add error as the first parameter in the callback function.

__ a. Open weather-caller.js in a text editor.

__ b. In the weather.current function call, add error as the first parameter to the anonymous callback function.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-14 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

ahmed
Sticky Note
Page 95: vy1021xstud

Student ExercisesV9.0

EXempty

__ c. In the callback function, print the contents of the error object if it is not null.

weather.current( param, function(error, temp_f) { if (error) { response.writeHead( 500, { 'Content-Type': 'text/plain' }); response.write(error); response.end(); return; }

__ d. Save weather-caller.js.

__ 2. In /weather/lib/weather-request.js, change the request.on(‘error’) event handler to pass the error object to the callback function.

__ a. Open /weather/lib/weather-request.js in a text editor.

__ b. In the weather.current function declaration, locate the weatherResponse.on(‘end’) event handler.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-15

Page 96: vy1021xstud

Student Exercises

__ c. In the anonymous function for the ‘end’ event, call the resultCallback function with null as the first parameter.

weatherResponse.on('end', function() { var body = buffer; var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g); if ( null != matches && matches.length > 0 ) { body = matches[0] .replace(/\<temp_f\>/, "") .replace(/\<\/temp_f\>/,""); } resultCallback( null, body );});

__ d. Add an event listener for the ‘error’ event. Call the resultCallback function with the contents of the error message.

var weatherRequest = http.request( options, weatherCallback );weatherRequest.on('error', function(e) { resultCallback(e.message);});weatherRequest.end();

__ e. Save /weather/lib/weather-request.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-16 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 97: vy1021xstud

Student ExercisesV9.0

EXempty

__ 3. Create a test for the error handler in the callback function.

__ a. In the /weather/lib/weather-request.js script, modify the web address of the options.host property to ‘’ (empty string).

var options = { host: '', path: '/xml/current_obs/' + param.location + '.xml'};

__ b. Save /weather/lib/weather-request.js.

__ 4. Commit the changes to the IBM DevOps Git repository.

__ 5. Push the changes to your IBM BlueMix <yourname>Ex03 application.

__ 6. Verify that IBM BlueMix successfully restarted the <yourname>Ex03 application.

__ 7. Test the <yourname>Ex03 application.

__ a. In the <yourname>Ex03 application summary page, select the Routes link.

__ b. Verify that your web browser opens the link at http://<yourname>ex03.mybluemix.net.

__ c. Confirm that the application displays a ‘connection refused’ error message.

connect ECONNREFUSED

__ 8. Correct the error in the application.

__ a. Change the options.host property back to ‘w1.weather.gov’.

__ b. Save /weather/lib/weather-request.js.

__ 9. Commit the changes to the IBM DevOps Git repository.

__ 10. Push the changes to your IBM BlueMix <yourname>Ex03 application.

__ 11. Verify that IBM BlueMix successfully restarted the <yourname>Ex03 application.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-17

Page 98: vy1021xstud

Student Exercises

__ 12. Test the <yourname>Ex03 application.

__ a. Confirm that the application successfully retrieves the weather reading.

Part 4: Defining a third-party package in the package manifest

The default Node framework includes only a minimal set of features. However, a large community of developers add to the Node framework through third-party libraries. The Node Package Manager (npm) manages Node packages and their dependencies.

In this section, modify the code that parses out the weather observation data. Use the xml2js library to convert the XML weather condition data to a JavaScript object.

__ 1. Add the xml2js Node package to the package manifest.

__ a. Open package.json.

__ b. Add the dependencies property, with a value of { "xml2js": "*" }.

{ "name": "Exercise03App", "version": "0.0.1", "description": "A nodejs app for Bluemix", "dependencies": { "xml2js": "*" }}

__ c. Save package.json.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-18 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 99: vy1021xstud

Student ExercisesV9.0

EXempty

Note

The IBM SDK for Node.js run time engine retrieves a copy of the xml2js package. It also retrieves all packages that xml2js depends on to run.

__ 2. Modify the weatherResponse.on(‘end’) event handler to parse out the weather reading with the xml2js Node package.

__ a. Open /weather/lib/weather-request.js in a text editor.

__ b. Add a require statement to import the parseString object from the xml2js module.

var parseString = require('xml2js').parseString;

__ c. Locate the weatherResponse.on('end') event handler in the code.

__ d. Parse the buffer variable with the xml2js parseString function.

__ e. Print the contents of the parsed string to the result callback function.

weatherResponse.on('end', function() { parseString( buffer, function (error, result) { if (error) { resultCallback(error.message); return; } resultCallback( null, result ); });});

__ f. Save /weather/lib/weather-request.js.

__ 3. Print the contents of the parsed variable to the HTTP response message.

__ a. Open weather-caller.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-19

Page 100: vy1021xstud

Student Exercises

__ b. In the line following response.writeHead(...), print the contents of the temp_f variable with the JSON.stringify function.

response.writeHead( 200, { 'Content-Type': 'text/plain'});response.write('The current weather reading is ' + JSON.stringify(temp_f) + ' degrees Fahrenheit');response.end();

__ c. Save weather-caller.js.

__ 4. Commit the changes to the IBM DevOps Git repository.

__ 5. Push the changes to your IBM BlueMix <yourname>Ex03 application.

__ 6. Verify that IBM BlueMix successfully restarted the <yourname>Ex03 application.

__ 7. Test the <yourname>Ex03 application.

__ a. Confirm that the application prints the entire weather observation as a JavaScript object.

{ current_observation: { '$': { version: '1.0', 'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:noNamespaceSchemaLocation': 'http://www.weather.gov/view/current_observation.xsd' }, ... weather: [ 'Fair' ], temperature_string: [ '83.0 F (28.3 C)' ], temp_f: [ '83.0' ], temp_c: [ '28.3' ], ...

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-20 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 101: vy1021xstud

Student ExercisesV9.0

EXempty

__ 8. Complete the implementation of the response.on(‘end’) event handler by extracting the temperature reading in degrees Fahrenheit from the buffer variable.

__ a. Open /weather/lib/weather-request.js in a text editor.

__ b. Write a callback handler to extract the <temp_f> XML element within the <current_observation> element.

weatherResponse.on('end', function() { parseString( buffer, function (error, result) { if (error) { resultCallback( error.message ); return; } resultCallback( null, result.current_observation.temp_f[0] ); });});

__ c. Save /weather/lib/weather-request.js.

__ 9. Modify weather-caller.js to print the value of the temp_f variable without using the JSON.stringify() function.

__ a. Open weather-caller.js.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-21

Page 102: vy1021xstud

Student Exercises

__ b. In the line following response.writeHead(...), print the contents of the temp_f variable without using the JSON.stringify function.

response.writeHead( 200, { 'Content-Type': 'text/plain'});response.write('The current weather reading is ' + temp_f + ' degrees Fahrenheit');response.end();

__ c. Save weather-caller.js.

__ 10. Commit the changes to the IBM DevOps Git repository.

__ 11. Push the changes to your IBM BlueMix <yourname>Ex03 application.

__ 12. Verify that IBM BlueMix successfully restarted the <yourname>Ex03 application.

__ 13. Test the <yourname>Ex03 application.

__ a. Confirm that the application prints the current weather conditions for San Francisco International Airport.

The current weather reading is 65.0 degrees Fahrenheit

Part 5: The Express web application framework

By default, the Node framework does not provide any classes to build web applications: you must program at a network socket level and intercept HTTP requests manually.

The Express web application framework is one of the most popular building blocks for web applications. The third-party module implements an ‘app’ class that you map to a web resource path.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-22 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 103: vy1021xstud

Student ExercisesV9.0

EXempty

In this section, create a REST web service that returns the current temperature reading at the specified location. Use the Express web application framework to build a web application that handles the web service requests.

__ 1. Create a Node package named temperature.

__ a. In the <yourname>Ex03 IBM DevOps project, create a directory that is named temperature.

__ b. Open a text editor.

__ c. Define a Node package manifest with the following details:

- Name: temperature

- Version: 1.0.0

- Description: Retrieve current weather conditions at a United States airport

- Main: app.js

{ "name": "temperature", "version": "1.0.0", "description": "Retrieve current weather conditions in the United States", "main": "app.js"}

__ d. Save the file as package.json in the /temperature directory.

__ 2. Add the Express web framework Node module to the package manifest.

__ a. Open package.json from the <yourname>Ex03 root directory.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-23

Page 104: vy1021xstud

Student Exercises

__ b. Add the Express Node module in the dependencies list.

{ "name": "Exercise03App", "version": "0.0.1", "description": "A nodejs app for Bluemix", "dependencies": { "xml2js": "*", "express": "*" }}

__ c. Save package.json.

__ 3. Implement the /temperature/<code> REST web service. The parameter <code> is an ICAO airport code.

__ a. Create a file with the name /temperature/app.js.

__ b. Open /temperature/app.js in a text editor.

__ c. Map the variable port to the IBM BlueMix application port number.

__ d. Import the weather.current property from the weather Node module.

__ e. Import the express Node module.

__ f. Create an instance of an express web application and assign it to a variable, app.

var port = (process.env.VCAP_APP_PORT || 8080);var current = require('../weather').current;var express = require('express');var app = express();

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-24 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 105: vy1021xstud

Student ExercisesV9.0

EXempty

__ g. Create an event handler for the HTTP GET method on the resource at /resource/<code>, where <code> represents an ICAO airport code.

app.get('/temperature/:code', function(req, res) {

});

__ h. In the anonymous function for the app.get(‘/temperature/:code’) event, call the weather.current method to retrieve the current weather reading.

app.get('/temperature/:code', function(req, res) { var param = { location: req.params.code }; current( param, function(error, temp_f) { if (error) { res.send(error); return; } res.send("The current weather reading is " + temp_f + " degrees Fahrenheit"); });});

Information

The line app.get('/temperature/:code', ...) creates an HTTP GET method listener in the app Express web application object. In this case, a GET method call to http://<yourname>ex03.mybluemix.net/temperature/KSFO starts the event listener and sets the code parameter in the URL resource path to ‘KSFO’.

To access the value of the code parameter in the event listener function, refer to req.params.code.

Note

The implementation for the /temperature/<code> event handler has the same structure as the callback handler code in the weather-caller.js application.

__ 4. Create an instance of an Express application that listens to port 8080.

__ a. Create a variable that is named server.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-25

Page 106: vy1021xstud

Student Exercises

__ b. Call app.listen on port 8080. Assign the result of the call to the server variable.

var server = app.listen(port);

__ c. Save /temperature/app.js.

__ 5. Update the manifest.yml file to start node temperature.

__ a. Open manifest.yml.

__ b. Change the command field to node temperature.

__ c. Save manifest.yml.

__ 6. Commit the changes to the IBM DevOps Git repository.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-26 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 107: vy1021xstud

Student ExercisesV9.0

EXempty

__ 7. Push the changes to your IBM BlueMix <yourname>Ex03 application.

__ 8. Verify that IBM BlueMix successfully restarted the <yourname>Ex03 application.

__ 9. Test the temperature Node application.

__ d. In a web browser, open http://<yourname>ex03.mybluemix.net/temperature/KSFO/

__ e. Confirm that the server responds with the current weather in San Francisco.

The current weather reading is 66.0 degrees Fahrenheit

__ 10. Close the web browser.

End of exercise

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-27

Page 108: vy1021xstud

Student Exercises

Solution

Part 1:

In the first part of this exercise, you forked a copy of the exercise 2 application as a starting point for exercise 3.

Part 2:

In the first iteration of the application, you added an input parameter, param, to the weather.current function.

The solution for weather-caller.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var weather = require('./weather');var param = { location: 'KSFO' };

var server = http.createServer( function(request, response) { weather.current( param, function(temp_f) { response.writeHead( 200, { 'Content-Type': 'text/plain' }); response.write('The current weather reading is ' + temp_f + ' degrees Fahrenheit'); response.end(); } );});server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-28 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 109: vy1021xstud

Student ExercisesV9.0

EXempty

Sample code for /weather/lib/weather-request.js:

var http = require('http');

exports.current = function ( param, resultCallback ) { var options = { host: 'w1.weather.gov', path: '/xml/current_obs/' + param.location + '.xml' }; var weatherCallback = function(weatherResponse) { var buffer = ''; weatherResponse.on('data', function(chunk){ buffer += chunk; }); weatherResponse.on('end', function() { var body = buffer; var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g); if ( null != matches || matches.length > 0 ) { body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/, ""); } resultCallback(body); }); }); }; var weatherRequest = http.request( options, weatherCallback ); weatherRequest.end(); };

Part 3:

In the second iteration of the application, you added an error object, error, as the first parameter in the callback function. Placing the error return parameter first makes it easy for the calling function to check whether the call completed successfully.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-29

Page 110: vy1021xstud

Student Exercises

Sample code for weather-caller.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var weather = require('./weather');var param = { location: 'KSFO' };

var server = http.createServer( function(request, response) { weather.current( param, function(error, temp_f) { if (error) { response.writeHead( 500, { 'Content-Type': 'text/plain' }); response.write(error); response.end(); return; } response.writeHead( 200, { 'Content-Type': 'text/plain' }); response.write('The current weather reading is ' + temp_f + ' degrees Fahrenheit'); response.end(); } );});

server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-30 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 111: vy1021xstud

Student ExercisesV9.0

EXempty

Sample code for /weather/lib/weather-request.js:

var http = require('http');

exports.current = function ( param, resultCallback ) { var options = { host: 'w1.weather.gov', path: '/xml/current_obs/' + param.location + '.xml' }; var weatherCallback = function(weatherResponse) { var buffer = ''; weatherResponse.on('data', function(chunk){ buffer += chunk; }); weatherResponse.on('end', function() { var body = buffer; var matches = buffer.match(/\<temp_f\>.+\<\/temp_f\>/g); if ( null != matches || matches.length > 0 ) { body = matches[0].replace(/\<temp_f\>/, "").replace(/\<\/temp_f\>/, ""); } resultCallback(null, body); }); }); };

var weatherRequest = http.request( options, weatherCallback ); weatherRequest.on('error', function(e) { resultCallback(e.message); }); weatherRequest.end(); };

Part 4:

In the third iteration of the application, you modified the weatherResponse.on(‘end’) event handler function to parse the XML web service response as a JavaScript object. The solution requires the xml2js Node module.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-31

Page 112: vy1021xstud

Student Exercises

Sample markup for package.json:

{ "name": "Exercise03App", "version": "0.0.1", "description": "A nodejs app for Bluemix", "dependencies": { "xml2js": "*" }}

Sample code for weather-caller.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var weather = require('./weather');var param = { location: 'KSFO' };

var server = http.createServer( function(request, response) { weather.current( param, function(error, temp_f) { if (error) { response.writeHead( 500, { 'Content-Type': 'text/plain' }); response.write(error); response.end(); return; } response.writeHead( 200, { 'Content-Type': 'text/plain' }); response.write('The current weather reading is ' + JSON.stringify(temp_f) + ' degrees Fahrenheit'); response.end(); } );});server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-32 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 113: vy1021xstud

Student ExercisesV9.0

EXempty

Sample code for /weather/lib/weather-request.js:

var http = require('http');var parseString = require('xml2js').parseString;

exports.current = function ( param, resultCallback ) { var options = { host: 'w1.weather.gov', path: '/xml/current_obs/' + param.location + '.xml' }; var weatherCallback = function(weatherResponse) { var buffer = ''; weatherResponse.on('data', function(chunk){ buffer += chunk; }); weatherResponse.on('end', function() { parseString( buffer, function (error, result) { if (error) { resultCallback(error.message); return; } resultCallback( null, result.current_observation.temp_f[0] ); }); }); }; var weatherRequest = http.request( options, weatherCallback ); weatherRequest.on('error', function(e) { resultCallback(e.message); }); weatherRequest.end();};

Part 5:

In the fourth iteration of the application, you built a REST web service to proxy the weather.current function. You installed the Express web application framework, and built a web application that listens to requests on the /temperature/<code> relative path. The parameter <code> represents a valid ICAO airport code.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-33

Page 114: vy1021xstud

Student Exercises

Sample markup for package.json:

{ "name": "Exercise03App", "version": "0.0.1", "description": "A nodejs app for Bluemix", "dependencies": { "xml2js": "*", "express": "*" }}

Sample code for weather-caller.js:

var host = (process.env.VCAP_APP_HOST || 'localhost');var port = (process.env.VCAP_APP_PORT || 8080);

var http = require('http');var weather = require('./weather');var param = { location: 'KSFO' };

var server = http.createServer( function(request, response) { weather.current( param, function(error, temp_f) { if (error) { response.writeHead( 500, { 'Content-Type': 'text/plain' }); response.write(error); response.end(); return; } response.writeHead( 200, { 'Content-Type': 'text/plain' }); response.write('The current weather reading is ' + temp_f + ' degrees Fahrenheit'); response.end(); } );});

server.listen(port, host);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-34 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 115: vy1021xstud

Student ExercisesV9.0

EXempty

Sample markup for /temperature/package.json:

{ "name": "temperature", "version": "1.0.0", "description": "Retrieve current weather conditions in the United States", "main": "app.js"}

Sample code for /temperature/app.js:

var port = (process.env.VCAP_APP_PORT || 8080);

var current = require('../weather').current;var express = require('express');var app = express();

app.get('/temperature/:code', function(req, res) { var param = { location: req.params.code }; current( param, function(error, temp_f) { if (error) { res.send(error); return; } res.send("The current weather reading is " + temp_f + " degrees Fahrenheit"); });});

var server = app.listen(port);

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 2015 Exercise 3. Node packages 3-35

Page 116: vy1021xstud

Student Exercises

Exercise review and wrap-up

The first and second parts of the exercise that is focused on improving the custom module with parameters.

In the third part, you added an error parameter in the callback function to propagate details about runtime errors. The convention is to set the first parameter as the error object. The callback function can quickly check whether the return condition is normal or in error by inspecting this first parameter.

In the fourth part, you installed the third-party xml2js Node package to parse and extract an XML element from a web service response message.

In the fifth part, you created an app object from the express Node package. With the app object, you created a REST web service that listens to HTTP requests to the /temperature web resource path.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-36 IBM SDK for Node.js with BlueMix © Copyright IBM Corp. 2015

Page 117: vy1021xstud

V9.0

backpg

Back page
Page 118: vy1021xstud