Professional Documents
Culture Documents
cover
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:
Express
System z
Power Systems
WebSphere
Power
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.
V9.0
Student Exercises
TOC
Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Exercises description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Exercise 1.
Part 1:
Part 2:
Part 3:
Part 4:
Part 5:
Part 6:
Part 7:
Part 8:
Exercise 2.
Part 1:
Part 2:
Part 3:
Part 4:
Part 5:
Part 6:
Part 7:
Part 8:
Exercise 3.
Part 1:
Part 2:
Part 3:
Part 4:
Part 5:
Contents
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
iii
Student Exercises
iv
V9.0
Student Exercises
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:
Express
System z
Power Systems
WebSphere
Power
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.
Trademarks
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Exercises
vi
V9.0
Student Exercises
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.
Exercises description
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
vii
Student Exercises
viii
V9.0
Student Exercises
EXempty
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.
Copyright IBM Corp. 2015
1-1
Student Exercises
1-2
V9.0
Student Exercises
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.
__ a.
__ b.
Navigate to https://bluemix.net.
__ c.
__ d.
Enter your IBM ID and password for your IBM BlueMix account.
__ e.
__ 2.
Create an application with the IBM SDK for Node.js server run time environment.
__ a.
1-3
Student Exercises
__ b.
__ c.
In the list of application types, select SDK for Node.js from the Runtimes catalog.
__ d.
1-4
V9.0
Student Exercises
- Name: <yourname>Ex01
EXempty
Note
Replace <yourname> with your user name. The value of <yourname> must be unique across all
BlueMix accounts.
__ e.
1-5
Student Exercises
__ 3.
Confirm that the IBM SDK for Node.js run time environment starts successfully in your IBM
BlueMix account.
__ a.
__ 4.
1-6
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.
V9.0
Student Exercises
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.
__ 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.
1-7
Student Exercises
__ e.
__ 6.
1-8
__ a.
In the BlueMix application dashboard, select Edit Code beside the Git URL link.
__ b.
V9.0
Student Exercises
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.
__ a.
In the web IDE (Integrated Development Environment) view, select File > New > File
from the menu.
__ b.
__ 2.
__ a.
__ b.
__ 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);
1-9
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.
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.
__ a.
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.
__ a.
V9.0
Student Exercises
EXempty
__ b.
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.
__ e.
__ f.
To intercept HTTP requests, you must set the server object to listen to HTTP requests on a specific
port.
__ 6.
__ a.
1-11
Student Exercises
__ 7.
Save hellotoday.js.
__ a.
__ 9.
__ a.
__ b.
V9.0
Student Exercises
EXempty
__ c.
__ 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.
__ b.
1-13
Student Exercises
__ c.
__ d.
Save package.json.
V9.0
Student Exercises
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.
__ 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.
1-15
Student Exercises
__ d.
__ 2.
Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.
__ a.
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.
V9.0
Student Exercises
EXempty
__ c.
__ 3.
Confirm that IBM DevOps successfully pushed the changes to the <yourname>Ex01
application on IBM BlueMix.
__ a.
__ b.
__ c.
__ 4.
__ a.
From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.
1-17
Student Exercises
__ b.
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.
__ a.
__ 2.
__ 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();
V9.0
Student Exercises
EXempty
__ 3.
__ 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.
1-19
Student Exercises
__ 6.
Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.
__ 7.
__ 8.
__ a.
From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.
__ b.
__ c.
__ a.
In your <yourname>Ex01 application in the IBM BlueMix web page, select Edit Code.
__ b.
V9.0
Student Exercises
EXempty
__ 2.
Write a JavaScript program that displays the day of the week in the web browser.
__ a.
__ b.
__ 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.
1-21
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.
__ 5.
Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.
__ 6.
__ 7.
__ a.
From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.
__ b.
__ 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.
__ a.
In the IBM DevOps <yourname>Ex01 project, select File > New > Folder from the menu
bar.
__ b.
V9.0
Student Exercises
EXempty
__ c.
__ 2.
Confirm that the IBM DevOps <yourname>Ex01 project includes the today folder.
__ a.
__ b.
Select File > New > File from the menu bar.
__ c.
__ d.
__ e.
1-23
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.
__ a.
__ b.
__ 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.
V9.0
Student Exercises
EXempty
__ a.
__ b.
Select File > New > File from the menu bar.
__ c.
__ 2.
Write a Node application that listens to HTTP requests with the IBM SDK for Node.js
runtime on IBM BlueMix.
__ a.
__ b.
1-25
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.
__ 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.
__ 5.
Save helloclient.js.
__ 6.
__ a.
Open manifest.yml.
V9.0
Student Exercises
EXempty
__ b.
__ 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.
__ 8.
Push the changes to the <yourname>Ex01 application on the IBM BlueMix environment.
__ 9.
From the IBM BlueMix web page for the <yourname>Ex01 application, select Routes.
__ b.
__ 11. Confirm that the web page displays a dynamic greeting according to the day of the week:
1-27
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
V9.0
Student Exercises
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" }
1-29
Student Exercises
V9.0
Student Exercises
EXempty
1-31
Student Exercises
V9.0
Student Exercises
EXempty
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
2-1
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.
__ a.
__ 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 OHare International Airport, Chicago, Illinois:
KLAX Los Angeles International Airport, Los Angeles, California
2-2
V9.0
Student Exercises
EXempty
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.
__ a.
__ b.
Navigate to https://bluemix.net.
__ c.
__ d.
Enter your IBM ID and password for your IBM BlueMix account.
__ e.
__ 2.
Create an application with the IBM SDK for Node.js server run time environment.
__ a.
2-3
Student Exercises
__ b.
__ c.
In the list of application types, select SDK for Node.js from the Runtimes catalog.
__ d.
2-4
V9.0
Student Exercises
- Name: <yourname>Ex02
EXempty
Note
Replace <yourname> with your user name. The value of <yourname> must be unique across all
BlueMix accounts.
__ e.
2-5
Student Exercises
__ 3.
Confirm that the IBM SDK for Node.js run time environment starts successfully in your IBM
BlueMix account.
__ a.
Information
Git is an open source, distributed version control system. The IBM DevOps services hosts Git
repositories for your IBM BlueMix applications.
__ 4.
2-6
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.
V9.0
Student Exercises
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.
2-7
Student Exercises
__ 5.
__ a.
In the BlueMix application dashboard, select Edit Code beside the Git URL link.
__ b.
__ a.
In the IBM DevOps <yourname>Ex02 Git project, select File > New > File from the menu
bar.
__ b.
__ 2.
Develop a Node application that creates a web server for the default IBM BlueMix
application port.
__ a.
2-8
V9.0
Student Exercises
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.
__ d.
__ 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);
2-9
Student Exercises
__ 3.
__ 4.
Save weather-request.js.
__ 5.
__ a.
__ b.
V9.0
Student Exercises
EXempty
__ c.
__ d.
__ 6.
Save manifest.yml.
Create a package.json file to describe the Node module dependencies for the
<yourname>Ex02 application.
__ a.
__ b.
2-11
Student Exercises
__ c.
__ d.
Save package.json.
V9.0
Student Exercises
EXempty
__ 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.
2-13
Student Exercises
__ d.
__ 2.
Push the changes to the <yourname>Ex02 application on the IBM BlueMix environment.
__ a.
__ 3.
__ a.
V9.0
Student Exercises
EXempty
__ b.
__ 4.
__ a.
From the IBM BlueMix web page for the <yourname>Ex02 application, select Routes.
__ b.
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.
__ a.
__ b.
2-15
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.
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.
V9.0
Student Exercises
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();
});
2-17
Student Exercises
__ 3.
V9.0
Student Exercises
EXempty
Commit the changes in the weather-request.js script to the IBM DevOps Git repository.
__ 2.
__ 3.
__ 4.
__ a.
__ b.
<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 #2.4f3600cc.1416962068.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.
2-19
Student Exercises
__ 6.
__ 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.
__ 7.
Commit the changes in the weather-request.js script to the IBM DevOps Git repository.
__ 8.
__ 9.
V9.0
Student Exercises
EXempty
__ b.
__ 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.
2-21
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.
__ 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.
__ 3.
__ 4.
__ 5.
Commit the changes in the weather-request.js script to the IBM DevOps Git repository.
__ 6.
__ 7.
__ 8.
__ a.
V9.0
Student Exercises
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.
__ 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.
__ d.
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.
__ 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 ) {
};
2-23
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;
});
V9.0
Student Exercises
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();
};
2-25
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.
V9.0
Student Exercises
EXempty
__ d.
__ 5.
__ 6.
__ a.
Open manifest.yml.
2-27
Student Exercises
__ b.
__ c.
Save manifest.yml.
__ 7.
__ 8.
V9.0
Student Exercises
EXempty
__ 9.
__ 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.
__ b.
__ c.
__ 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.
2-29
Student Exercises
__ f.
__ g.
Save weather-caller.js.
V9.0
Student Exercises
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.
__ b.
__ c.
__ d.
2-31
Student Exercises
__ e.
__ f.
Save weather-request.js.
V9.0
Student Exercises
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
2-33
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.
V9.0
Student Exercises
EXempty
2-35
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.
V9.0
Student Exercises
EXempty
2-37
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);
V9.0
Student Exercises
EXempty
2-39
Student Exercises
V9.0
Student Exercises
EXempty
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.
3-1
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.
__ 1.
__ a.
__ b.
Navigate to https://bluemix.net.
__ c.
__ d.
Enter your IBM ID and password for your IBM BlueMix account.
__ e.
__ 2.
3-2
Create an application with the IBM SDK for Node.js server run time environment.
__ a.
__ b.
V9.0
Student Exercises
EXempty
__ c.
In the list of application types, select SDK for Node.js from the Runtimes catalog.
__ d.
3-3
Student Exercises
Note
Replace <yourname> with your user name. The value of <yourname> must be unique across all
BlueMix accounts.
__ e.
__ 3.
Confirm that the IBM SDK for Node.js run time environment starts successfully in your IBM
BlueMix account.
__ a.
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.
3-4
__ a.
__ b.
V9.0
Student Exercises
EXempty
__ c.
__ 5.
Select your <yourname>Ex02 project. Recall that <yourname> is the name that you
assigned to your projects.
__ a.
__ b.
__ c.
3-5
Student Exercises
__ d.
__ e.
Click Create.
__ 6.
__ a.
3-6
V9.0
Student Exercises
EXempty
__ b.
__ c.
__ 7.
__ a.
Open package.json.
__ b.
__ c.
3-7
Student Exercises
__ 8.
__ a.
Open project.json.
__ b.
__ c.
__ 9.
3-8
__ a.
__ b.
__ c.
Examine the Deploy To field. You must change this setting from the <yourname>Ex02
IBM BlueMix application to the <yourname>Ex03 application.
V9.0
Student Exercises
EXempty
__ d.
Select Configure.
__ e.
__ f.
Click Submit.
3-9
Student Exercises
__ 10. Deploy the application to the <yourname>Ex03 IBM BlueMix application project.
__ a.
__ b.
V9.0
Student Exercises
EXempty
__ c.
Select Force Push All to deploy the entire application to your IBM BlueMix
<yourname>Ex03 application space.
__ b.
__ c.
__ d.
__ e.
Verify that the application returns the current weather observation at San Francisco
International Airport.
__ a.
3-11
Student Exercises
__ b.
__ 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.
__ 2.
Save /weather/lib/weather-request.js.
__ a.
__ b.
__ c.
V9.0
Student Exercises
EXempty
__ d.
__ e.
Save weather-caller.js.
__ 3.
__ 4.
__ 5.
__ 6.
__ a.
__ b.
3-13
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
__ a.
__ b.
In the weather.current function call, add error as the first parameter to the anonymous
callback function.
V9.0
Student Exercises
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.
__ 2.
Save weather-caller.js.
__ a.
__ b.
3-15
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.
V9.0
Student Exercises
EXempty
__ 3.
__ a.
__ b.
Save /weather/lib/weather-request.js.
__ 4.
__ 5.
__ 6.
__ 7.
__ a.
__ b.
__ c.
__ 8.
__ a.
__ b.
Save /weather/lib/weather-request.js.
__ 9.
3-17
Student Exercises
__ a.
Open package.json.
__ b.
__ c.
Save package.json.
V9.0
Student Exercises
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.
__ b.
Add a require statement to import the parseString object from the xml2js module.
var parseString = require('xml2js').parseString;
__ c.
__ d.
__ 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.
__ 3.
Save /weather/lib/weather-request.js.
Print the contents of the parsed variable to the HTTP response message.
__ a.
Open weather-caller.js.
3-19
Student Exercises
__ b.
__ c.
Save weather-caller.js.
__ 4.
__ 5.
__ 6.
__ 7.
__ 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' ],
...
V9.0
Student Exercises
EXempty
__ 8.
__ a.
__ 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.
__ 9.
Save /weather/lib/weather-request.js.
Modify weather-caller.js to print the value of the temp_f variable without using the
JSON.stringify() function.
__ a.
Open weather-caller.js.
3-21
Student Exercises
__ b.
__ c.
Save weather-caller.js.
Confirm that the application prints the current weather conditions for San Francisco
International Airport.
The current weather reading is 65.0 degrees Fahrenheit
V9.0
Student Exercises
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.
__ a.
__ b.
__ c.
__ d.
__ 2.
Add the Express web framework Node module to the package manifest.
__ a.
3-23
Student Exercises
__ b.
__ c.
__ 3.
Save package.json.
__ a.
__ b.
__ c.
Map the variable port to the IBM BlueMix application port number.
__ d.
__ e.
__ f.
V9.0
Student Exercises
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.
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.
__ a.
3-25
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.
__ 5.
Save /temperature/app.js.
__ a.
Open manifest.yml.
__ b.
__ c.
Save manifest.yml.
__ 6.
V9.0
Student Exercises
EXempty
__ 7.
__ 8.
__ 9.
__ d.
__ e.
Confirm that the server responds with the current weather in San Francisco.
The current weather reading is 66.0 degrees Fahrenheit
End of exercise
3-27
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);
V9.0
Student Exercises
EXempty
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.
3-29
Student Exercises
V9.0
Student Exercises
EXempty
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.
3-31
Student Exercises
V9.0
Student Exercises
EXempty
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.
3-33
Student Exercises
V9.0
Student Exercises
EXempty
3-35
Student Exercises
V9.0
backpg
Back page