Build your first Node.js website, Part 2

29 July 2014
PDF (195 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 second part of a three-part article that introduces you to Node.js development step-by-step, with no software installation required.

Part 1's "Hello World"-plus application was a great starting point. You used IBM DevOps Services and IBM Bluemix to bring up a Node.js server, and you coded some simple server-side JavaScript to count the requests to your server. Here in Part 2, you'll add formatted HTML pages to your site and then pass the data from the server for display on the home HTML page.

To add a web front end to Node.js, the most common technique is to use the Express web application framework. With Express, you have several choices for formatting web pages, including Jade, Handlebars, and EJS. To stay in my comfort zone, I chose EJS, which uses plain old HTML.

The app.js file includes all the Express setup.

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

I found a good Express EJS starting sample, stripped it down to the bare minimum, and then extended it to pass data and serve static web pages. You'll start with my version and learn how to display data from the Node.js application in an HTML page and how to serve up static HTML content. In Part 3, you'll use a Redis database to persist data for the website.

The application's modified flow now looks like this:

Diagram of the current application flow

READ:Getting Started with IBM Bluemix and IBM DevOps Services using Node.js

READ:My First Website CoderDojo HTML project

What you'll need

 

Step 1: Create and deploy your copy of the HTML 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.

    Now you have the directory structures and file setup for Express. The app.js file includes all the Express setup:

    var app = express();
    app.set('port', process.env.PORT || 3000);
    app.set('view engine', 'ejs');
    
    app.use(morgan('dev'));
    app.use(express.static(path.join(__dirname, 'public')));

    The package.json file is also updated to add dependencies for Express and EJS:

    "dependencies": {
        "express": "*",
        "ejs": "*",
        "morgan": "*"
      }
    }
  5. Deploy the application manually using the same process you used for the app in Part 1.
  6. Click the NodeJS_Simple_2 link in the Manual Deployment Information area of the root folder page to open the formatted HMTL page in a new browser tab.
  7. Refresh the page and watch the counter increment with each refresh.

Step 2: Change the HTML index page and redeploy

 

In app.js, the Express setup specifies app.set('views', path.join(__dirname, 'views'));. This statement tells the application to look in the views directory for the initial page to render.

Now you'll make some minor changes to the HTML index page:

  1. Back in the DevOps Services IDE, open the views folder and click index.ejs to edit the HTML.
  2. Edit the text in the <title> and <h1> tags to replace Ruth with your own name.
  3. Select manifest.yml to ensure that DevOps Services finds the manifest file when you deploy.
  4. Deploy your application and click the link in the manual deployment information to open the application. Verify that the changes are displayed.

Step 3: Pass server-side content to the HTML page

 

It's time to learn a little of the Express EJS magic. To display data from your Node.js application onto an HTML page, you must pass the data to the web page using this syntax:

res.render('index', {userCount: userCount})

index is the name of the initial HTML page displayed. Inside the {} are the names of the variables to pass in, along with their values.

Make these changes to the application:

  1. Back in the DevOps Services IDE, select app.js. Add a new userbytwo variable and initialize it:
    var userbytwo = 0;
  2. Increment userbytwo:
    userbytwo = userbytwo + 2;
  3. Update the render command to add userbytwo as a variable to pass to the HTML page for display:
    res.render('index', {userCount: userCount, userbytwo: userbytwo});

    Your app.get code block should now look like this:
    var userCount = 0;
    var userbytwo = 0; /* added var definition for userbytwo here */
    
    app.get('/', function(req, res){
      userCount = userCount + 1;
      /* add statement to increment userbytwo by two here */
      userbytwo = userbytwo + 2;
      res.render('index', {userCount: userCount, userbytwo: userbytwo});
     /* updated this line */
    });

Step 4: Display variables on an HTML page

 

Naturally, the HTML page also needs some special syntax to retrieve and display the passed variables:

  1. Return to the views folder and select index.ejs.
  2. Copy the <p> line that displays userCount and paste it immediately below the existing line. In the new line, change userCount to userbytwo to display both variables:
    <p>The user count in my nodejs application is: <%= userCount %></p>
    <p>The user by two count in my nodejs application is: <%= userbytwo %></p>
  3. Select manifest.yml and deploy your application. Use the manual deployment information link to open the application, and see your changes in the HTML page.

Step 5: Add linked HTML pages

 

Now you'll add a few links to your website's index page. Linking to additional pages isn't hard, but you must ensure that the directory structures are set up correctly to find your pages.

In the Express setup in app.js, the app.use(express.static(path.join(__dirname, 'public'))); statement tells the application to look in the public directory for HTML content. To get you started, the public folder contains two HTML pages, with images and stylesheets subdirectories.

  1. Open the views folder, select indexwithlinks.ejs, and copy lines 9-15.
  2. Open index.ejs, paste the copied content after line 12, and save. You can see that the copied lines link to sports.html and aboutme.html.
  3. Open the public directory and locate aboutme.html and sports.html.
  4. Make any changes you'd like to aboutme.html and sports.html. You can even upload your own picture into the images directory and link to it.
  5. Deploy your application. In the application, follow the links to verify that they go to content in the public directory.

Conclusion to Part 2

 

Here in the second part of this three-part article, you created a multipage website with dynamic, server-side data displayed from your Node.js application. As in Part 1, the entire example was done with just a web browser accessing DevOps Services and Bluemix — no installation required.

Now you're ready to move on to Part 3 and store the data in a database.


RELATED TOPICS:Node.jsJavaScript

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=978436
ArticleTitle=Build your first Node.js website, Part 2
publish-date=07292014