Create Your First Application - Node - Js and Windows Azure
Create Your First Application - Node - Js and Windows Azure
Summary: Create your first application using Node.js and Windows Azure. Implement a simple Hello World application in Node.js and deploy the application to a Windows Azure Web Site. Learn how to use the Windows Azure PowerShell cmdlets to create a Node.js application, test it in the Windows Azure Emulator, and then deploy it as a Windows Azure Cloud Service. Implement a Node.js application using WebMatrix, and then deploy it to a Windows Azure web site. Implement a task list application using Node.js and MongoDB.
Category: Quick Step-by-Step Applies to: Windows Azure, Node.js Source: Windows Azure Developer Center (link to source content) E-book publication date: June 2012
Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other marks are property of their respective owners. The example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred. This book expresses the authors views and opinions. The information contained in this book is provided without any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.
Contents
Create and deploy a Node.js application to a Windows Azure Web Site.................................................. 5 Set up the Windows Azure environment ........................................................................................................... 5 Create a Windows Azure account ..................................................................................................................... 5 Enable Windows Azure Web Sites .................................................................................................................... 6 Create a Windows Azure Web Site and enable Git publishing.................................................................. 7 Install developer tools ............................................................................................................................................ 11 Build and test your application locally ............................................................................................................. 12 Publish your application ........................................................................................................................................ 13 Publish changes to your application................................................................................................................. 15 Revert to a previous deployment....................................................................................................................... 16 Next steps ................................................................................................................................................................... 17 Additional Resources .............................................................................................................................................. 17 Node.js Cloud Service................................................................................................................................................. 18 Setting Up the Development Environment .................................................................................................... 18 Creating a New Node Application ..................................................................................................................... 19 Running Your Application Locally in the Emulator...................................................................................... 23 Deploying the Application to Windows Azure.............................................................................................. 24 Creating a Windows Azure Account ............................................................................................................. 24 Downloading the Windows Azure Publishing Settings ......................................................................... 25 Publishing the Application................................................................................................................................ 26 Stopping and Deleting Your Application ........................................................................................................ 28 Create and deploy a Node.js application to a Windows Azure Web Site using WebMatrix ........... 30 Set up the Windows Azure environment ........................................................................................................ 31 Create a Windows Azure account .................................................................................................................. 31 Enable Windows Azure Web Sites ................................................................................................................. 31 Create a Windows Azure Web Site .................................................................................................................... 33 Import the web site into WebMatrix and apply the Express template ................................................ 34 Publish your application to Windows Azure .................................................................................................. 37 Modify and republish your application............................................................................................................ 40 Next Steps ................................................................................................................................................................... 42 Node.js Web Application with Storage on MongoDB ................................................................................... 43 Prerequisites ............................................................................................................................................................... 45 Preparation ................................................................................................................................................................. 45 Create a virtual machine and install MongoDB ........................................................................................ 45 Sign up for the Windows Azure Web Sites preview feature ................................................................ 45 Enable Windows Azure Web Sites ................................................................................................................. 46 Install modules and generate scaffolding....................................................................................................... 47 Install express and generate scaffolding ..................................................................................................... 48 Install additional modules ................................................................................................................................. 49
Using MongoDB in a node application............................................................................................................ 50 Create the model.................................................................................................................................................. 50 Create the controller ........................................................................................................................................... 50 Modify app.js ......................................................................................................................................................... 52 Modify the index view ........................................................................................................................................ 52 Run your application locally ................................................................................................................................. 53 Deploy your application to Windows Azure .................................................................................................. 56 Install the Windows Azure command-line tool for Mac and Linux ................................................... 57 Import publishing settings................................................................................................................................ 57 Create a Windows Azure Web Site ................................................................................................................ 58 Publish the application....................................................................................................................................... 59 Next steps ................................................................................................................................................................... 60 Additional resources ............................................................................................................................................... 60 Node.js Web Application using the Windows Azure SQL Database ........................................................ 61 Prerequisites ............................................................................................................................................................... 62 Enable the Windows Azure Web Site feature................................................................................................ 62 Create a web site with database......................................................................................................................... 63 Get SQL Database connection information.................................................................................................... 71 Design the task table .............................................................................................................................................. 72 Install modules and generate scaffolding....................................................................................................... 75 Install express and generate scaffolding ..................................................................................................... 75 Install additional modules ................................................................................................................................. 77 Use SQL Database in a node application ........................................................................................................ 78 Modify the controller .......................................................................................................................................... 78 Modify app.js ......................................................................................................................................................... 79 Modify the index view ........................................................................................................................................ 80 Modify the global layout ................................................................................................................................... 81 Create configuration file .................................................................................................................................... 82 Run your application locally ................................................................................................................................. 82 Deploy your application to Windows Azure .................................................................................................. 84 Publish the application....................................................................................................................................... 84 Switch to an environment variable ................................................................................................................ 84 Next steps ................................................................................................................................................................... 86 Additional resources ............................................................................................................................................... 86
How to create a Windows Azure Web Site using the Windows Azure Developer Portal How to publish and re-publish your application to Windows Azure using Git
By following this tutorial, you will build a simple Hello World web application in Node.js. The application will be hosted in a Windows Azure Web Site when deployed. A screenshot of the completed application is below:
3. Click WEB SITE, then QUICK CREATE. Enter a value for URL and select the datacenter for your web site in the REGION dropdown. Click the checkmark at the bottom of the dialog.
4. Once the web site status changes to Running, click on the name of the web site to access the Dashboard
6. To enable Git publishing, you must provide a user name and password. If you have previously enabled publishing for a Windows Azure Web Site, you will not be prompted for the user name or password. Instead, a Git repository will be created using the user name and password you previously specified. Make a note of the user name and password, as they will be used for Git publishing to all Windows Azure Web Sites you create.
7. Once the Git repository is ready, you will be presented with instructions on the Git commands to use in order to setup a local repository and then push the files to Windows Azure.
10
Note Save the instructions returned by the Push my local files to Windows Azure link, as they will be used in the following sections.
11
Note If you are performing this tutorial on Windows, you can set up your machine with Windows Azure SDK for Node.js that includes Node.js.
12
5. To stop the application, switch to the Terminal window and hold down the CTRL and C keys on your keyboard.
13
4. Push your changes to Windows Azure using the following command: git push azure master You will be prompted for the password you created earlier and will see the following output:
If you navigate to the deployments tab of your Windows Azure Web Site within the management portal, you will see your first deployment in the deployment history:
14
5. Browse to http://[your web site url]/ to begin using the application. You can find your web site url on the "Dashboard" tab of your Windows Azure Web Site within the management portal.
15
3. Browse to http://[your web site url]/ and note that the updates have been applied.
16
3. Once the deployment status changes to Active Deployment, view the web site in your browser and note that it has reverted to the selected deployment.
Next steps
While the steps in this article use the Windows Azure Portal to create a web site, you can also use the Windows Azure Command-Line Tools for Mac and Linux to perform the same operations.
Additional Resources
Windows Azure PowerShell Windows Azure Command-Line Tools for Mac and Linux
17
By following this tutorial, you will build a simple Hello World web application. The application will be hosted in an instance of a web role that, when running in Windows Azure, is itself hosted in a dedicated virtual machine (VM). A screenshot of the completed application is below:
3. Click Install in the installer window and proceed with the installation:
Once the installation is complete, you have everything necessary to start developing. The following components are installed: Node.js IISNode NPM for Windows Windows Azure Compute & Storage Emulators Windows Azure PowerShell
1. On the Start menu, click All Programs, Windows Azure, right-click Windows Azure PowerShell, and then select Run As Administrator. Opening your Windows PowerShell environment this way ensures that all of the Node command-line tools are available. Running with elevated privileges avoids extra prompts when working with the Windows Azure Emulator.
2. Create a new node directory on your C drive, and change to the c:\node directory:
3. Enter the following cmdlet to create a new solution: PS C:\node> New-AzureServiceProject tasklist You will see the following response:
The New-AzureServiceProject cmdlet generates a basic structure for creating a new Windows Azure Node application which will be published to a Cloud Service. It contains configuration files necessary for publishing to Windows Azure. The cmdlet also changes your working directory to the directory for the service. 20
Enter the following command to see a listing of the files that were generated: PS C:\node\tasklist> ls
ServiceConfiguration.Cloud.cscfg, ServiceConfiguration.Local.cscfg and ServiceDefinition.csdef are Windows Azure-specific files necessary for publishing your application. For more information about these files, see Overview of Creating a Hosted Service for Windows Azure. deploymentSettings.json stores local settings that are used by the Windows Azure PowerShell deployment cmdlets.
4. Enter the following command to add a new web role using the AddAzureNodeWebRole cmdlet: PS C:\node\tasklist> Add-AzureNodeWebRole You will see the following response:
The Add-AzureNodeWebRolecmdlet creates a new directory for your application and generates additional files that will be needed when your application is published. In Windows Azure, roles define components that can run in the Windows Azure execution environment. A web role is customized for web application programming. By default if you do not provide a role name, one will be created for you i.e. WebRole1. You can provide a name as the first parameter to AddAzureNodeWebRole to override i.e. Add-AzureNodeWebRole MyRole
21
Enter the following commands to change to the newly generated directory and view its contents: PS C:\node\tasklist> cd WebRole1 PS C:\node\tasklist\WebRole1> ls
5. Open the server.js file in Notepad. Alternatively, you can open the server.js file in your favorite text editor. PS C:\node\tasklist\WebRole1> notepad server.js This file contains the following starter code that the tools have generated. This code is almost identical to the Hello World sample on the nodejs.org website, except: The port has been changed to allow IIS to handle HTTP traffic on behalf of the application. IIS Node.js integration provides Node.js applications with a number of benefits when running on-premise or in Windows Azure, including: process management, scalability on multi-core servers, autoupdate, side-by-side with other languages, etc. Console logging has been removed.
22
23
2. To stop the compute emulator, use the Stop-AzureEmulator command: PS C:\node\tasklist\WebRole1> Stop-AzureEmulator
2. Your account is now created. You are ready to deploy your application to Windows Azure! 24
2. Log into the Management Portal. This takes you to the page to download your Windows Azure publishing settings. 3. Save the profile to a file location you can easily access:
4. In the Windows Azure PowerShell window, use the following cmdlet to configure the Windows PowerShell for Node.js cmdlets to use the Windows Azure publishing profile you downloaded: PS C:\node\tasklist\WebRole1> ImportAzurePublishSettingsFile [path to file] After importing the publish settings, consider deleting the downloaded .publishSettings as the file contains information that can be used by others to access your account.
25
PS C:\node\tasklist\WebRole1> Publish-AzureServiceProject ServiceName TaskListContoso Location "North Central US Launch Be sure to use a unique name, otherwise the publish process will fail. After publishing succeeds, you will see the following response:
The Publish-AzureServiceProject cmdlet performs the following steps: 1. Creates a package that will be deployed to Windows Azure. The package contains all the files in your node.js application folder. 2. Creates a new storage account if one does not exist. The Windows Azure storage account is used in the next section of the tutorial for storing and accessing data. 3. Creates a new hosted service if one does not already exist. A hosted serviceis the container in which your application is hosted when it is deployed to Windows Azure. For more information, see Overview of Creating a Hosted Service for Windows Azure. 4. Publishes the deployment package to Windows Azure.
26
It can take 57 minutes for the application to deploy. Since this is the first time you are publishing, Windows Azure provisions a virtual machine (VM), performs security hardening, creates a web role on the VM to host your application, deploys your code to that web role, and finally configures the load balancer and networking so you application is available to the public. After the deployment is complete, the following response appears.
The browser also opens to the URL for your service and display a web page that calls your service.
Your application is now running on Windows Azure! The hosted service contains the web role you created earlier. You can easily scale your application by changing the number of instances allocated to each role in the ServiceConfiguration.Cloud.cscfg file. You may want to use only one instance when deploying for development and test purposes, but multiple instances when deploying a production application. 27
2. To delete the service, call the following cmdlet: PS C:\node\tasklist\WebRole1> Remove-AzureService When prompted, enter Y to delete the service. Deleting the service may take several minutes. After the service has been deleted you receive a message indicating that the service was deleted.
Note Deleting the service does not delete the storage account that was created when the service was initially published, and you will continue to be billed for storage used. Since storage accounts can be used by multiple deployments, be sure that no other deployed service is using the storage account before you delete it. For more information on deleting a storage account, see How to Delete a Storage Account from a Windows 28
Azure Subscription.
29
Create and deploy a Node.js application to a Windows Azure Web Site using WebMatrix
This tutorial shows you how to use WebMatrix to develop and deploy a Node.js application to a Windows Azure Website. WebMatrix is a free web development tool from Microsoft that includes everything you need for website development. WebMatrix includes several features that make it easy to use Node.js including code completion, pre-built templates, and editor support for Jade, LESS, and CoffeeScript. Learn more about WebMatrix for Windows Azure. Upon completing this guide, you will have a node web site running in Windows Azure. You will learn: How to create a web site from the Windows Azure Portal. How to develop a node application using WebMatrix. How to publish and re-publish your application to Windows Azure using WebMatrix.
By following this tutorial, you will build a simple node web application. The application will be hosted in a Windows Azure Web Site. A screenshot of the running application is below:
30
32
3. Click WEB SITE, then QUICK CREATE. Enter a value for URL and select the datacenter for your web site in the REGION dropdown. Click the checkmark at the bottom of the dialog.
4. Once the web site is created, the portal will display all the web sites associated with your subscription. Verify that the web site you just created has a Status of Running and then click the web site name to view the Dashboard for this web site.
33
Import the web site into WebMatrix and apply the Express template
1. From the Dashboard, click the WebMatrix icon at the bottom of the page to open the web site in WebMatrix 2.
2. If WebMatrix 2 is not installed, Web Platform Installer 4.0 will install Microsoft WebMatrix 2 and all necessary prerequisites. WebMatrix will launch and display a dialog indicating Empty Site Detected. Click Yes, install from the Template Gallery to select a built-in template.
34
3. In the Site from Template dialog, select Node and then select Express Site. Finally, click Next. If you are missing any prerequisites for the Express Site template, you will be prompted to install them.
35
4. After WebMatrix finishes building the web site, the WebMatrix IDE is displayed.
36
37
2. Click Continue. When publishing is complete, the URL for the web site on Windows Azure is displayed at the bottom of the WebMatrix IDE
38
39
2. Change the second line to the following: p Welcome to #{title} with WebMatrix on Windows Azure! 3. Click the save icon, and then click the publish icon.
40
4. Click Continue in the Publish Preview dialog and wait for the update to be published.
5. When publishing has completed, use the link returned when the publish process is complete to see the updated site.
41
Next Steps
You've seen how to create and deploy a web site from WebMatrix to Windows Azure. To learn more about WebMatrix, check out these resources: WebMatrix for Windows Azure WebMatrix website
Publishing a Windows Azure Web site using Git
42
By following this tutorial, you will build a simple web-based task-management application that allows creating, retrieving and completing tasks. The tasks are stored in MongoDB. The project files for this tutorial will be stored in a directory named tasklist and the completed application will look similar to the following:
43
Note This tutorial makes reference to the tasklist folder. The full path to this folder is omitted, as path semantics differ between operating systems. You should create this folder in a location that is easy for you to access on your local file system, such as ~/node/tasklist or c:\node\tasklist Note Many of the steps below mention using the command-line. For these steps, use the command-line for your operating system, such as Windows PowerShell (Windows) or Bash (Unix Shell). On OS X systems you can access the command-line through the Terminal application.
44
Prerequisites
Before following the instructions in this article, you should ensure that you have the following installed: node recent version Git
Preparation
In this section you will learn how to create a virtual machine in Windows Azure and install MongoDB, set up your development environment, and install the MongoDB C# driver.
After you have created the virtual machine in Windows Azure and installed MongoDB, be sure to remember the DNS name of the virtual machine ("testlinuxvm.cloudapp.net", for example) and the external port for MongoDB that you specified in the endpoint. You will need this information later in the tutorial.
45
46
47
Note The '-g' parameter used when installing the express module installs it globally. This is done so that we can access the express command to generate web site scaffolding without having to type in additional path information.
3. To create the scaffolding which will be used for this application, use the express command: express The output of this command should appear similar to the following: create : . create : ./package.json create : ./app.js create : ./public create : ./public/javascripts create : ./public/images create : ./public/stylesheets create : ./public/stylesheets/style.css create : ./routes create : ./routes/index.js create : ./views create : ./views/layout.jade 48
create : ./views/index.jade
dont forget to install dependencies: $ cd . && npm install After this command completes, you should have several new directories and files in the tasklist directory.
This installs all of the default modules that Express needs. 2. Next, enter the following command to install the Mongoose module locally as well as to save an entry for it to the package.json file: npm install mongoose --save The output of this command should appear similar to the following: mongoose@2.6.5 ./node_modules/mongoose hooks@0.2.1 49
mongodb@1.0.2 Note You can safely ignore any message about installing the C++ bson parser.
module.exports = TaskList; function TaskList(connection) { mongoose.connect(connection); } 3. Continue adding to the tasklist.js file by adding the methods used to showTasks, addTask, and completeTasks: TaskList.prototype = { showTasks: function(req, res) { task.find({itemCompleted: false}, function foundTasks(err, items) { res.render('index',{title: 'My ToDo List ', tasks: items}) }); }, addTask: function(req,res) { var item = req.body.item; newTask = new task(); newTask.itemName = item.name; newTask.itemCategory = item.category; newTask.save(function savedTask(err){ if(err) { throw err; } }); res.redirect('home'); }, completeTask: function(req,res) { var completedTasks = req.body; for(taskId in completedTasks) { if(completedTasks[taskId]=='true') { var conditions = { _id: taskId }; var updates = { itemCompleted: completedTasks[taskId] }; task.update(conditions, updates, function updatedTask(err) { if(err) { throw err; } }); 51
Modify app.js
1. In the tasklist directory, open the app.js file in a text editor. This file was created earlier by running the express command. 2. Replace the content after the //Routes comment with the following code. This will initialize TaskList with the connection string for the MongoDB server and add the functions defined in tasklist.js as routes: var TaskList = require('./routes/tasklist'); var taskList = new TaskList('mongodb://mongodbserver/tasks'); app.get('/', taskList.showTasks.bind(taskList)); app.post('/addtask', taskList.addTask.bind(taskList)); app.post('/completetask', taskList.completeTask.bind(taskList));
app.listen(process.env.port || 3000); Note You must replace the connection string above with the connection string for the MongoDB server you created earlier. For example, mongodb://mymongodb.cloudapp.net/tasks 3. Save the app.js file.
table(border="1") tr td Name td Category td Date td Complete each task in tasks tr td #{task.itemName} td #{task.itemCategory} - var day = task.itemDate.getDate(); - var month = task.itemDate.getMonth() + 1; - var year = task.itemDate.getFullYear(); td #{month + "/" + day + "/" + year} td input(type="checkbox", name="#{task._id}", value="#{!task.itemCompleted}", checked=task.itemCompleted) input(type="submit", value="Update tasks") hr form(action="/addtask", 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") input(type="submit", value="Add item") 3. Save and close index.jade file.
53
4. Use the provided fields for Item Name and Item Category to enter information, and then click Add item.
54
5. The page should update to display the item in the ToDo List table.
55
6. To complete a task, simply check the checkbox in the Complete column, and then click Update tasks. While there is no visual change after clicking Update tasks, the document entry in MongoDB has now been marked as completed. 7. To stop the node process, go to the command-line and press the CTRL and C keys.
Install the Windows Azure command-line tool for Mac and Linux
To install the command-line tools, use the following command: sudo npm install azure g Note If you have already installed the Windows Azure SDK for Node.js from the Windows Azure Developer Center, then the command-line tools should already be installed. For more information, see Windows Azure command-line tool for Mac and Linux. Note While the command-line tools were created primarily for Mac and Linux users, they are based on Node.js and should work on any system capable of running Node.
The file download should begin automatically; if it does not, you can click the link at the beginning of the page to manually download the file. 57
2. After the file download has completed, use the following command to import the settings: azure account import <path-to-file> Specify the path and file name of the publishing settings file you downloaded in the previous step. Once the command completes, you should see output similar to the following: info: info: info: Executing command account import Found subscription: subscriptionname Setting default subscription to: subscriptionname
warn: The '/Users/user1/.azure/publishSettings.xml' file contains sensitive information. warn: Remember to delete it now that it has been imported. info: info: Account publish settings imported successfully account iomport command OK
3. Once the import has completed, you should delete the publish settings file as it is no longer needed and contains sensitive information regarding your Windows Azure subscription.
58
Once this command has completed, you will see output similar to the following. Note that the line beginning with Created website at contains the URL for the web site. info: info: info: info: info: Executing command site create Using location southcentraluswebspace Executing `git init` Creating default web.config file Creating a new web site
info: Created website at mongodbtasklist.azurewebsites.net info: info: Initializing repository Repository initialized
info: Executing `git remote add azure http://username@mongodbtasklist.azurewebsites.net/mongodbta sklist.git` info: site create command OK Note If this is the first Windows Azure Web Site for your subscription, you will be instructed to use the portal to create the web site. For more information, see Create and deploy a Node.js application to Windows Azure Web Sites.
Total 17 (delta 0), reused 0 (delta 0) remote: New deployment received. remote: Updating branch 'master'. remote: Preparing deployment for commit id 'ef276f3042'. remote: Preparing files for deployment. remote: Running NPM. ... remote: Deploying Web.config to enable Node.js activation. remote: Deployment successful. To https://username@mongodbtasklist.azurewebsites.net/MongoDBT asklist.git * [new branch] master -> master 4. Once the push operation has completed, browse to the web site by using the azure site browse command to view your application.
Next steps
While the steps in this article describe using MongoDB to store information, you can also use the Windows Azure Table Service. See Node.js Web Application with the Windows Azure Table Service for more information.
Additional resources
Windows Azure command-line tool for Mac and Linux Create and deploy a Node.js application to Windows Azure Web Sites Publishing to Windows Azure Web Sites with Git
60
By following this tutorial, you will build a simple web-based task-management application that allows creating, retrieving and completing tasks. The tasks are stored in SQL Database. The project files for this tutorial will be stored in a directory named tasklist and the completed application will look similar to the following:
61
Note The Microsoft Driver for node.js for SQL Server used in this tutorial is currently available as a preview release, and relies on run-time components that are only available on the Microsoft Windows and Windows Azure operating systems. Note This tutorial makes reference to the tasklist folder. The full path to this folder is omitted, as path semantics differ between operating systems. You should create this folder in a location that is easy for you to access on your local file system, such as ~/node/tasklist or c:\node\tasklist Note Many of the steps below mention using the command-line. For these steps, use the command-line for your operating system, such as cmd.exe (Windows) or bash (UNIX shell). On OS X systems you can access the command-line through the terminal application.
Prerequisites
Before following the instructions in this article, you should ensure that you have the following installed: node version 0.6.14 or higher Git Microsoft SQL Server Native Client libraries - available as part of the Microsoft SQL Server 2012 Feature Pack A text editor A web browser
63
Enter a value for URL, select Create a New SQL Database from the DATABASE dropdown, and select the data center for your web site in the REGION dropdown. Click the arrow at the bottom of the dialog. 64
4. Enter a value for the NAME of your database, select the EDITION (WEB or BUSINESS), select the MAX SIZE for your database, choose the COLLATION, and select NEW SQL Database server. Click the arrow at the bottom of the dialog.
65
5. Enter an administrator name and password (and confirm the password), choose the region in which your new SQL Database server will be created, and check the Allow Windows Azure Services to access the server box.
66
When the web site has been created you will see the text Creation of Web Site [SITENAME] completed successfully. Now, you can enable Git publishing. 6. Click the name of the web site displayed in the list of web sites to open the web sites Quick Start dashboard.
67
7. At the bottom of the Quick Start page, click Set up Git publishing.
68
8. To enable Git publishing, you must provide a user name and password. Make a note of the user name and password you create. (If you have set up a Git repository before, this step will be skipped.)
69
9. When your repository is ready, you will see instructions for pushing your application files to the repository. Make note of these instructions - they will be needed later.
70
71
3. From the ODBC section of the resulting dialog, make note of the connection string as this will be used later.
2. Login using the login name and password you selected when creating the database server earlier.
72
3. From the bottom left of the page, select Design and then select New Table.
73
4. Enter 'tasks' as the Table Name and check Is Identity? for the ID column.
74
5. Change Column1 to name and Column2 to category. Add two new columns by clicking the Add column button. The first new column should be named created and have a type of date. The second new column should be named completed and have a type of bit. Both new columns should be marked as Is Required?.
6. Click the Save button to save your changes to the table. You can now close the SQL Database management page.
2. Enter the following command to install express. npm install express g Note When using the '-g' parameter on some operating systems, you may receive an error of error: eperm, chmod '/usr/local/bin/express' and a request to try running the account as an administrator. if this occurs, use the sudo command to run npm at a higher privilege level. The output of this command should appear similar to the following: express@2.5.9 /usr/local/lib/node_modules/express mime@1.2.4 qs@0.4.2 mkdirp@0.3.0 connect@1.8.7 Note The '-g' parameter used when installing the express module installs it globally. This is done so that we can access the express command to generate web site scaffolding without having to type in additional path information. 3. To create the scaffolding which will be used for this application, use the express command: express The output of this command should appear similar to the following: create : . create : ./package.json create : ./app.js create : ./public create : ./public/javascripts create : ./public/images create : ./public/stylesheets create : ./public/stylesheets/style.css create : ./routes create : ./routes/index.js create : ./views create : ./views/layout.jade create : ./views/index.jade 76
dont forget to install dependencies: $ cd . && npm install After this command completes, you should have several new directories and files in the tasklist directory.
connect@1.8.7 jade@0.26.0 ./node_modules/jade commander@0.5.2 mkdirp@0.3.0 This installs all of the default modules that Express needs. 2. Next, use the following command to add the nconf module. This module will be used by the application to read the database connection string from a configuration file. npm install nconf save 3. Next, download the binary version of the Microsoft Driver for Node.JS for SQL Server from the download center. 4. Extract the archive to the tasklist\node_modules directory. 5. Run the node-sqlserver-install.cmd file in the tasklist\node_modules directory. This will create a node-sqlserver subdirectory under node_modules and move the driver files into this new directory structure. 6. Delete the node-sqlserver-install.cmd file, as it is no longer needed.
77
nconf.env() .file({ file: 'config.json' }); var conn = nconf.get("SQL_CONN"); 3. Continue adding to the index.js file by adding the index and updateItem methods. The index method returns all uncompleted tasks from the database, while updateItem will mark selected tasks as completed. exports.index = function(req, res) { var select = "select * from tasks where completed = 0"; sql.query(conn, select, function(err, items) { if(err) throw err; res.render('index', { title: 'My ToDo List ', tasks: items }); }); };
78
var insert = "insert into tasks (name, category, created, completed) values (?, ?, GETDATE(), 0)"; sql.query(conn, insert, [item.name, item.category], function(err) { if(err) throw err; res.redirect('home'); }); } else { var completed = req.body.completed; if(!completed.forEach) completed = [completed]; var update = "update tasks set completed = 1 where id in (" + completed.join(",") + ")"; sql.query(conn, update, function(err) { if(err) throw err; res.redirect('home'); }); } } 4. Save the index.js file.
Modify app.js
1. In the tasklist directory, open the app.js file in a text editor. This file was created earlier by running the express command. 2. Replace the content after the //Routes comment with the following code. This will add a new route to the updateItem method you added previously in the index.js file and listen on the port specified in process.env.PORT. The port value will be used once the application is deployed to Windows Azure. // Routes
form(action="/", method="post") table(class="table table-striped table-bordered") thead tr td Name td Category td Date td Complete tbody each task in tasks tr td #{task.name} td #{task.category} td #{task.created} td input(type="checkbox", name="completed", value="#{task.ID}", checked=task.completed == 1) button(type="submit") Update tasks hr 80
form(action="/", method="post", class="well") label Item Name: input(name="item[name]", type="textbox") label Item Category: input(name="item[category]", type="textbox") br button(type="submit", class="btn") Add Item 3. Save and close index.jade file.
82
4. Use the provided fields for Item Name and Item Category to enter information, and then click Add item. 5. The page should update to display the item in the ToDo List.
6. To complete a task, simply check the checkbox in the Complete column, and then click Update tasks.
83
7. To stop the node process, go to the command-line and press the CTRL and C keys.
84
2. Click CONFIGURE and then find the app settings section of the page.
3. In the app settings section, enter SQL_CONN in the KEY field, and the ODBC connection string in the VALUE field. Finally, click the checkmark.
85
4. Finally, click the SAVE icon at the bottom of the page to commit this change to the run-time environment.
5. From the command-line, change directories to the tasklist directory and enter the following command to remove the config.json file: git rm config.json git commit -m "Removing config file" 6. Perform the following command to deploy the changes to Windows Azure: git push azure master Once the changes have been deployed to Windows Azure, your web application should continue to work as it is now reading the connection string from the app settings entry. To verify this, change the value for the SQL_CONN entry in app settings to an invalid value. Once you have saved this value, the web site should fail due to the invalid connection string.
Next steps
Node.js Web Application with MongoDB Node.js Web Application with Table Storage
Additional resources
Windows Azure command-line tool for Mac and Linux
86