Build your first Node.js website, Part 3

29 July 2014
PDF (293 KB)
Share:

Sign up for IBM Bluemix™ This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

This is the third part of a three-part article that introduces you to Node.js development step-by-step, with no software installation required. In Part 1 and Part 2, you used IBM DevOps Services and IBM Bluemix to bring up a web server and a simple HTML front end, and to get data flowing from the server to the browser. All that's left is to persist the data into a database.

Bluemix gives you ready access to great database services, with no installation or management required. For storing a counter, my many choices included multiple relational databases and NoSQL options such as MongoDB, Cloudant, and Redis.

The Redis service's lifecycle is independent of the application's, so data stored in the service persists across application restarts.

This part starts with a new DevOps Services project, so it is not necessary to complete the exercises in Part 1 and Part 2 before proceeding.

The sample application stores data into a separate Redis service managed by Bluemix. This service's lifecycle is independent of the application's, so data stored in the service persists across application restarts.

To access a Bluemix service, a fair amount of setup is required in the code. You'll use a starter project with all the Redis service setup in place. The new application flow looks like this:

Diagram of the current application flow

READ:Getting started with Redis service

What you'll need

 

Step 1: Create and deploy your copy of the HTML-database application

 
  1. Log in to Bluemix from your web browser.
  2. In a separate browser tab, log in to DevOps Services.
  3. Click this article's Get the code button above.
  4. In DevOps Services, click the EDIT CODE button and then click the FORK button on the menu to create your own copy of the code to work with, saving it with whatever project name you choose.
  5. Take a quick look at the relevant files:
    • In package.json, notice the additional dependencies for Redis: "redis": "*".
    • In manifest.yml, see the specifications for creating the Redis service:
        services:
          redis-5a659:
            label: redis
            provider: core
            version: '2.6'
            plan: 100
    • In app.js, search for redis to see all the changes that were made to interface to the Redis service.
  6. Deploy the application manually using the same process you used for the previous two parts of this article.
  7. Click the NodeJS_Simple_3 link in the Manual Deployment Information area of the root folder page to open the application in a new browser tab: Screenshot of the manual deployment information with link to root folder page
    In the running application, you can see two user counts that both start at 1: the user count in the Node.js server (as configured in Part 2) and a new count that's stored in the database.
  8. Refresh the browser page and watch the counts increment with each refresh. Now — after the first deployment — the user count in the server and the user count in the database remain identical.

Step 2: Observe database persistence across restarts

 
  1. Return to the manual deployment information in DevOps Services, highlight your deployment, and stop your application by clicking the solid black square: Screenshot of the manual deployment information with stop button
  2. Highlight your deployment again and start the application by clicking the solid right-pointing triangle: Screenshot of the manual deployment information with start button

    Click to see larger image

  3. Browse back to the running application. Notice that the user count in the Node.js application is reset to 1 but that the count from the database has incremented from the number that the page displayed before you stopped and restarted the application. This happens because the Redis service has a separate lifecycle from the Node.js application.

Step 3: Work with the Redis service on Bluemix

 

You use the Bluemix dashboard to work directly with Bluemix services:

  1. Highlight your deployment in the DevOps Services manual deployment information and click the Manage link. This action opens the Bluemix dashboard, where you can work with the application and the Redis service: Screenshot of the Bluemix dashboard
  2. Click the gear-shaped button near the top right, and then click Delete App.
  3. In the Are you sure... dialog box, select the check box to delete the Redis service (redis-5a659) and click OK. By deleting the service along with the application, you delete the database counter that was persisted across application restarts.
  4. Back in the manual deployment information in DevOps Services, use the cloud-shaped button to redeploy the application. Because you deleted the Redis service, this redeployment creates a new instance of the service.
  5. Browse to the running application and observe that the user count stored in the Redis database is also reset to 1.

Step 4: Add data to the database

 

Now you'll update the code to store a counter that increments by two into the Redis service, and display that counter on the HTML page. Because calls to the Redis service are asynchronous, you must insert the new calls into a nested structure to ensure proper ordering. (Another option is to add explicit async libraries — a topic that's outside of this article's scope.)

  1. Open app.js and find the client.incrby line. This statement increments a DBuserCountBy1 variable in Redis and returns the updated value in the replyBy1 variable.
  2. Add a line to increment a database variable, DBuserCount2, by two and return the value as replyBy2:
    client.incrby("DBuserCountBy2", 2, function (err, replyBy2);

    To ensure that the calls to Redis are synchronized, this statement must be nested inside the increment of the DBuserCountBy1:
    client.incrby("DBuserCountBy1", 1, function (err, replyBy1) { 
       client.incrby("DBuserCountBy2", 2, function (err, replyBy2) {

    Be sure to add the closing }); also.
  3. Update the res.render statement to pass the DBuserCountby2 that's returned in the replyBy2 variable from the Redis function call:
    res.render('index', {userCount: userCount, DBuserCountBy1: replyBy1, DBuserCountBy2: replyBy2});

    The app.get section of your code should now look like this:
    app.get('/', function(req, res) {
      userCount = userCount + 1;
      // Increment the value in the database and render the results
      client.incrby("DBuserCountBy1", 1, function (err, replyBy1) {
       client.incrby("DBuserCountBy2", 2, function (err, replyBy2) {
        res.render('index', {userCount: userCount, DBuserCountBy1: replyBy1, DBuserCountBy2: replyBy2});
        });
      });
    });
  4. Update the index.ejs HTML page to render to DbuserCountBy2:
    <p>The stored user count by two in my redis database is <%= DBuserCountBy2 %></p>.
  5. Redeploy the application and verify that all the counts are behaving as expected.

Conclusion

 

In this three-part article, you worked step-by-step through bringing up a Node.js server, adding a web front end with both static pages and dynamic content from the server, and then storing the dynamic data in a database. You saw how the lifecycle of the Redis database service is independent of the lifecycle of the application, enabling the user count to persist as the application is stopped and started. The entire example is done with just a web browser accessing IBM DevOps Services and Bluemix — no installation required.

Acknowledgments

No children were harmed in the writing of this article, though several were challenged to expand from users of technology to creators of their own technology. My thanks to my novice helpers: my son Tucker, and Carolyn Norton and her son, Patrick. And my thanks to Mike McKay and Patrick Mueller, my local Node.js gurus.


RELATED TOPICS:Node.jsRedis

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Cloud computing
ArticleID=978439
ArticleTitle=Build your first Node.js website, Part 3
publish-date=07292014