demo script - node.js on windows azure - western …rvitolo06/watk/demos/nodejsonwindowsazure... ·...

37
Demo Script Node.js on Windows Azure Version: 1.0.0 Last updated: 3/6/2022

Upload: lykiet

Post on 29-May-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

Demo ScriptNode.js on Windows AzureVersion: 1.0.0

Last updated: 5/8/2023

CONTENTS

OVERVIEW................................................................................................................................................. 3Key Messages......................................................................................................................................... 3

Key Technologies.................................................................................................................................... 3

Time Estimates........................................................................................................................................ 4

SETUP AND CONFIGURATION................................................................................................................. 4

DEMO FLOW.............................................................................................................................................. 4

OPENING STATEMENT............................................................................................................................. 5

STEP-BY-STEP WALKTHROUGH.............................................................................................................6Segment #1: Creating & Publishing a simple Node.js application to the Cloud.......................................6

Segment #2: Adding Table Storage functionality to the application.......................................................22

SUMMARY................................................................................................................................................ 36

KNOWN ISSUES...................................................................................................................................... 36

Overview

Node.js is a server-side JavaScript environment that uses an asynchronous event-driven model. It is based on Google's V8 JavaScript engine plus several built-in libraries.

This document provides step-by-step instructions to create and publish to the cloud a simple Node.js application, using the Windows Azure SDK for Node.js. You will also learn how easy is to add support in your Node.js application to access a Windows Azure Table Storage.

Note: In order to run through this complete demo, you must have network connectivity and a Windows Azure account.

Key Messages

In this demo you will see the followingkea features:

1. Create a simple Windows Azure project with a Node.js WebRole using the Windows Azure Powershell for Node.js and publish it to the cloud.

2. Update your Node.js application to support Windows Azure Storage.3. a

Key Technologies

This demo uses the following technologies:

1. Node.js

2. Node Package Manager

3. Windows Azure SDK for NodeJS

4. Windows Azure NodeJS PowerShell Cmdlets

5.

Time Estimates

Estimated time to complete the demo: 20 min6.

Setup and Configuration

This demo does not have any advanced configuration requirements. Make sure you have checked all the dependencies for this demo and have a developer account for Windows Azure.

Demo Flow

The following diagram illustrates the high-level flow for this demo and the steps involved:

Figure 1Demo Flow

Opening Statement

In the next minutes, we will build and deploy a simple Node.JS application using the latest Windows Azure tools and SDK for Node.js. First, we will create a new web application from scratch and deploy it into Windows Azure. In the second part of the demo, we will add support to access a Windows Azure Table Storage using Node.js.

This demo covers the following subjects:

1. How to create a node.js Windows Azure application using PowerShell cmdlets.

2. How to launch the application using the local Windows Azure Emulator

3. How to deploy the application to Windows Azure.

4. How to install common node.js modules to access a Windows Azure Table Storage.

5. How to add support to your application to consume a Windows Azure Table Storage.6.

Step-by-Step Walkthrough

This demo is composed of the following segments:

Creating & Publishing a simple Node.js application to the Cloud

Adding Table Storage functionality to the application7.

Segment #1: Creating & Publishing a simple Node.js application to the Cloud

Action Script Screenshot

1. Start Windows Azure PowerShell for Node.js as Administrator.

2. In the Windows Azure Powershell console, type New-AzureService HelloWorld and press Enter.

3. Add a WebRole to the project. For this, type Add-AzureNodeWebRole and press Enter.

First, we are going to create our Windows Azure project.

Next, we will add a web role to the cloud project.

4. Type cd .\WebRole1.

5. Open the Windows Azure Project folder to see its content. To do this, type explorer C:\HelloWorld and press Enter.

Let’s examine what we have done so far.

You can see that using only the PowerShell cmdlets we created all the necessary Windows Azure files and folders.

We don’t have to use Visual Studio for our Node.js project.

6. Examine the content of the server.js file, type notepad server.js and press Enter.

This file creates a new web server object that accepts connections and listens to the specified port and hostname.

7. Switch back to the PowerShell window.

8. Run the application using the Windows Azure Emulator. For this, type Start-AzureEmulator -launch

Before we create something interesting with node.js, let’s see the default project.

We can run the application using the local Windows Azure Emulator.

Later in this demo, we will add more features to this application, like adding new views and support to Windows Azure Table Storage.

9. Switch back to the PowerShell window.

10. Install the Express and uuid modules, by typing npm install express node-uuid and pressing Enter.

Now that we have our cloud project setup with a node.js web role we will start writing our simple application.

We are going to use a few popular node.js modules to build our app:

The first package, express, is a popular web framework.

The second package, uuid, generates unique strings.

We will use Node Package Manager to install those packages.

11. To create the application’s structure, type &

Next, we will use the express scaffolding to create the structure

"$Env:ProgramFiles\nodejs\node” .\node_modules\express\bin\express.

12. To confirm the operation, type Y and press Enter.

of the application.

13. Replace the default server.js file with the app.js file. To do this, type copy app.js server.js.

14. Install additional dependencies by typing npm install.

Copy the app.js file to server.js

Last we need to run npm install to download additional dependencies that were defined in the package.json file.

15. Open the server.js file by typing notepad server.js in the PowerShell console.

16. Replace the app.listen(3000) line with the following code:

javascriptapp.listen(3000);app.listen(process.env.port);

17. Save and close the file.

This configures Node to listen on the environment PORT value provided by Windows Azure when published to the cloud.

18. Run the application locally. Type start http://localhost:81.

Let’s test the application in the local emulator.

As the application is already running in the emulator, we just need to browse to the application’s URL in order to see the changes in the server.js file.

The changes were automatically picked up by the emulator.

19. Open the Index view. To do this, type start notepad views/index.jade in the PowerShell console.

20. Modify the title by appending “in Windows Azure”.

21. Save and close the file.

Now I’m going to show you how to modify the index view to display the message Welcome to Express in Windows Azure

Notice the .jade extension. This is because Express uses Jade as the default template engine.

Jade does not require any tags, just uses leading words that are later rendered to html.

We’ll learn more about jade as we build out the application.

22. Refresh your browser to see the If we refresh out browser, we will see the changes we’ve just made to

changes. the Index view.

23. Add a new view to the application. For this, type start notepad views/home.jade and press Enter.

24. Select Yes to create the new file.

25. Add the following text to the empty file, then save and close it.

jadeh1= titlep Welcome to #{title} in Windows Azure

Let’s add a Home view to the application.

As this view doesn’t exist yet, notepad we’ll ask us if we want to create the file.

For now, the view will just have a static placeholder.

26. Back in the PowerShell console, open the server.js file by typing start notepad server.js.

27. Add the following code after the app.get line:

javascriptapp.get('/home', function(req, res){

res.render('home', { title: 'Home' });});

28. Save and close the file.

In order to handle the home requests, we have to modify the server.js file, by adding a route entry for “/home”.

The app.get call tells Node.js to handle HTTP GET requests:

The first parameter of the function call specifies the URL to be handled. In this case, ‘/home’.

Next, a callback is provided for handling the actual request. The first parameter is the incoming request, while the second parameter is the response.

In the callback, we’re instructing Express to render the Home view (notice that .jade extension is not required). Additionally, we’re passing in ‘Home’ as the title.

29. Browse to the Home view. Type start http://localhost:81/home.

Now let’s browse to the new Home view we’ve just added.

30. Switch back to the Windows Azure PowerShell window, type Get-AzurePublishSettings and press ENTER.

31. In the Windows Azure Management Portal prompted site, log in with your Windows Azure account.

32. Save the publish-settings file locally (e.g., c:\HelloWorld\my.publishSettings).

In order to deploy the application to Windows Azure, we need to log in with our account and download a Windows Azure publishing profile.

33. In the Windows PowerShell window, call the Import-AzurePublishSettings command with the location of the publish-settings file downloaded in the previous step. For example, Import-AzurePublishSettings c:\HelloWorld\my.publishSettings.

Next, we need to import the downloaded profile in our computer. This will authorize our machine to publish deployment packages to Windows Azure using Windows PowerShell commands.

34. Increase the number of instances of the Web Role. To do this, in the Windows PowerShell console, paste the following code and press Enter.

PowerShellSet-AzureInstances WebRole1 2

Now, we’ll increase the number of instances of the Web Role.

Just by running this line, you’ll be able to increase the number of instances of your Web Roles and Worker Roles without opening the ServiceConfiguration file.

35. Publish the application to the cloud. To do this, paste the following command replacing the placeholders with your new hosted service settings.

PowerShellPublish-AzureService –name {YOUR-HOSTED-SERVICE-NAME} –location {YOUR-HOSTED-SERVICE-LOCATION} -launch

Note: As this command will create a new Hosted Service and storage account, make sure that the name you choose is unique across all the services in Windows Azure.

Lastly, we need to use the Publish –AzureService command, with the hosted service settings in order to publish our application to the cloud. For example, Publish-AzureService –name helloworldnodejs –location "South Central US” -launch

name specifies the DNS prefix of the service. We need to make sure it’s unique.

location specifies the region where the service will be published. . Examples of the available regions include: “North Central US”, “Anywhere US, “, “Anywhere Asia”, etc.

By using launch we’re instructing the command to open the browser with our application once the publish process is completed.

The Publish-AzureService cmdlet performs the following steps

Creates a package that will be deployed to Windows Azure. The package contains all the files in your node.js application folder.

Creates a new storage account if one does not exist, that will be used later in the demo.

Creates a new hosted service.

Publishes the deployment package to Windows Azure

After the deployment is complete, you will see the response in the Powershell window.

36. Highlight that the application is now running in Azure instead of the emulator and show it in the browser.

Notice that the browser is displaying the application, which is now hosted in Windows Azure.

Segment #2: Adding Table Storage functionality to the application

Action Script Screenshot

1. If not already open, start Windows Azure PowerShell for Node.js as Administrator.

2. Change the currently directory to the WebRole1 folder within the project you created in the previous segment. To do this, type cd .\HelloWorld\WebRole1 and press Enter.

3. Open the web.cloud.config file. Type start notepad web.cloud.config and press

Now we will update our simple application to a web-based task-management application that creates and retrieves tasks stored in a Windows Azure Table Storage.

You will notice how easy is to upgrade a Node.js Web Application using Windows Azure Node SDK to support Windows Azure Table Storage.

First, we need to configure the web.cloud.config file with our

Enter.

4. Insert the following code under the <configuration> element, replacing the [STORAGE ACCOUNT] and [STORAGE ACCESS KEY] placeholders with your storage account information.

XML<appSettings>

<add key="AZURE_STORAGE_ACCOUNT" value="[STORAGE ACCOUNT]"/>

<add key="AZURE_STORAGE_ACCESS_KEY" value="[STORAGE ACCESS KEY]"/></appSettings>

storage account name and access key. These settings will be used when publishing to Windows Azure.

However, when running the application locally, the SDK will use the local configuration settings file and local storage instead.

5. Save and close the file.

6. Switch back to the Windows Azure PowerShell window.

7. In order to connect your application with the Windows Azure Table Storage, import the azure module to the application. To do this, type npm install azure and press Enter.

We’ll now import the azure module to the application in order to connect it with Windows Azure Table Storage using the npm install command.

8. Type start notepad server.js and press Enter to open the server.js file.

9. Paste the code below after the line that ends with express.createServer()

javascriptvar Home = require('./home');var azure = require('azure');var uuid = require('node-uuid');

Next, we will modify the server.js file.

We need to include the home and azure modules. The home module does not exist yet, but we will create it shortly.

10. Add the following code to create a storage table client after the code you inserted in the previous step.

javascriptvar client = azure.createTableService();

//table creationclient.createTableIfNotExists('tasks', function(error){

if(error){throw error;

}var item = {

name: 'Add readonly task list',

category: 'Site work',

date: '12/01/2011',

RowKey: uuid(),

PartitionKey: 'partition1',

completed: false

};

client.insertEntity('tasks', item, function(){});});

We will add code to create a storage table client passing the storage account and access key information.

The code will create a table named Tasks, if doesn’t exist, and populate it with some default data.

11. Replace the existing code in the route section with the following code.

javascript

app.get('/', routes.index);app.get('/home', function(req, res){ res.render('home', { title: 'Home' }); });

var home = new Home(client);app.get('/', home.showItems.bind(home));app.get('/home', home.showItems.bind(home));

12. Save the file and close it.

Additionally, we need to modify the existing code in the route section. It will create a home controller instance and route all requests to “/” or “/home” to it (we’ll create the home controller later).

Notice that instead of handling the request inline, we are now delegating the command to a Home object. The bind command is necessary to ensure that the references are properly resolved locally (within the home controller).

13. In the Windows Azure PowerShell for Node.js console, type notepad home.js.

14. Click Yes and paste the code shown below.

javascript

var azure=require('azure');module.exports = Home;

function Home (client) {this.client = client;

};

Home.prototype = {showItems: function

(req, res) {var self = this;

this.getItems(false, function (resp, tasklist) {

if (!tasklist) {

tasklist = [];}

self.showResults(res, tasklist);

});},

getItems: function

The next thing to do is to create the home controller to handle all requests for the task list site.

We will implement the javascript module pattern for the controller.

For this, we will use a Home function to bind the Controller with the View.

The Home prototype contains the functions to handle the actual request. It includes the following functions:

showItems, handles the request.

getItems, uses the table client to retrieve open task items from the tasks table.

showResults calls the Express render function to render the page using the home view.

(allItems, callback) {var query =

azure.TableQuery

.select()

.from('tasks');

if (!allItems) { query =

query.where('completed eq ?', 'false');

}

this.client.queryEntities(query, callback);

},

showResults: function (res, tasklist) {

res.render('home', {

title: 'Todo list',

layout: false,

tasklist: tasklist });

},};

15. Save the changes and close the file.

16. Switch back to the Windows Azure PowerShell window, type cd views and press Enter.

17. Open the Home View. To do this, type notepad home.jade.

18. Replace the content with the code shown below and save the file.

jade

htmlhead title Indexbody h1 My ToDo List

form table(border="1") tr td Name td Category td Date td Complete

each item in tasklist tr td #{item.name} td #{item.category} td

As mentioned earlier, we are using the Jade template engine to render the views. This is the default engine for working with Express.

We’re going to add to the application the functionality for reading task items.

We’ll create a table to display the stored tasks with their name, category and date.

In addition, we’ll add a checkbox that will show if the task is completed or not.

#{item.date} td input(type="checkbox", name="completed", value="#{item.RowKey}")

19. Test the application locally. In the Windows Azure Powershell window, type start http://localhost:81 and press Enter.

Note: If the emulator is not running, you’ll need to type Start-AzureEmulator –launch instead.

Let’s check what we have done so far with the application in the emulator.

Your browser will display the following page, showing the task item that was retrieved from Windows Azure storage.

20. In the Windows Azure PowerShell console, type cd .. to go back to the parent folder.

21. Open the server.js file. To do this, type start notepad server.js and press ENTER.

22. Add the highlighted line and save the file.

javascript

...// Routes

var home = new Home(client);app.get('/', home.showItems.bind(home));app.get('/home', home.showItems.bind(home));app.post('/home/newItem', home.newItem.bind(home));

The next thing to do is update the application to support adding new task items.

We will add a line in the server.js file to handle the post calls to the home page.

This way we can bind the controller with the new item post call.

23. Open the home.js file. To do this, type notepad home.js.

24. Add the following line at the beginning of the file.

javascriptvar uuid = require('node-uuid');

25. Paste the highlighted code at the end of the file.

javascriptshowResults:

function (res, tasklist) {

res.render('home', {

title: 'Todo list',

layout: false,

tasklist: tasklist });

},

newItem: function (req, res) {

var self = this;

var createItem = function (resp, tasklist) {

if (!

Next, we’ll modify the home view to add the add new item functionality.

First, we need to include the node-uuid module. We’ll use this module to create unique identifiers.

Now, we’ll add the newItem function. This function performs the following tasks:

Extracts the posted item from the body.

Sets the RowKey and PartitionKey values for the new item. These values are required to insert the item into the Windows Azure table. A UUID is generated for the RowKey value (this is achieved by using the uuid module previously installed).

Inserts the new item into the tasks table by calling the insertEntity function.

Renders the page by calling the getItems

tasklist) {

tasklist = [];}

var count = tasklist.length;

var item = req.body.item;

item.RowKey = uuid();

item.PartitionKey = 'partition1';

item.completed = false;

self.client.insertEntity('tasks', item, function (error) {

if(error){

throw error;}

self.showItems(req, res);

});};

this.getItems(true, createItem);

function.

},};

26. In the Windows Azure PowerShell console, type cd views and press Enter.

27. Type notepad home.jade and press Enter.

28. Add the following code at the end of the file.

jade

form(action="/home/newItem", method="post") table(border="1") tr td Item Name: td input(name="item[name]", type="textbox") tr td Item Category: td input(name="item[category]", type="textbox") tr td Item Date:

Lastly, we will update the home view by adding a new form.

Doing this, we’ll allow users to add items to the table.

Note that in jade, whitespacing and indentation is significant.

td input(name="item[date]", type="textbox") input(type="submit", value="Add item")

29. Publish the updated application to Windows Azure. To do this, in the Windows PowerShell window, type Publish-AzureService -launch and press ENTER.

30. Once the browser shows the application, create a new item. You can use the following values:

- Name: “New Task”

- Item Category: “Node.js”

- Item Date: “12/05/2011”.

31. Click Add item.

Now that the application is completed we will publish it to Windows Azure by updating the deployment of the existing hosted service.

The storage settings and location were previous saved and do not need to be re-entered.

As before, because you specified the –launch option, the browser will open and display your application running in Windows Azure when publishing is completed

We’ll test the final app by adding new items in the Task list.

32.

Summary

In this demo, you learned how to build a new Windows Azure Node.js application from scratch, using the Windows Azure SDK for Node.js. You saw how to run Node applications locally using the Windows Azure compute emulator, and how to publish your application to the cloud. Finally, you experienced how easy is to upgrade your Node.js application to work with a Windows Azure Table Storage.

Known Issues

Please note the following known issues with this demo:

It can sometimes take several minutes to start a Windows Azure application in the cloud. Consequently, you may want to have an example application already deployed and running in the production environment.