Learn IBM Bluemix with a simple Node.js file-upload application

30 June 2014
PDF (222 KB)
 

An introduction to the application lifecycle on Bluemix

06:52

Jay Allen

Software Developer, Software Group, Strategy, jStart Emerging Technologies

@jayallenmn

Jon Johnson

Computer Science Major

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 article gives a quick, hands-on tour of IBM® Bluemix™, the open IBM cloud platform for developing and deploying web and mobile applications. The exercise uses the major components of Bluemix through a small, tight bit of code. You'll build a Node.js application that uploads a file and inserts the file contents into a MySQL database. Then you'll test the app and see how to manage it through Bluemix. Another reason we chose this app is that we're big Node.js fans and take every possible opportunity to learn more about it.

What you need to build a similar app

 

Step 1. Clone the application and prep it for Bluemix

 
  1. Clone the Node MySQL upload application from the IBM jStart GitHub repository:
    git clone https://github.com/ibmjstart/bluemix-node-mysql-upload.git

    All the application logic is contained in app.js. In app.js, we're using some of the nice Node modules that ease web application development (the Express web development framework and the Hogan templating engine for Express), and the MySQL and file system modules to simplify database and file manipulation:
    var http = require('http');
    var path = require('path');
    var express = require('express');
    var hogan = require('hogan-express');
    var mysql = require('mysql');
    var fs = require('fs');
  2. Add the unique pieces of code you need to add to an application to run it in Bluemix. From the application environment, pull VCAP_APP_PORT, VCAP_APP_HOST, and VCAP_SERVICES.

    VCAP_APP_HOST and VCAP_APP_PORT tell the application which port and host Bluemix assigns to your application. VCAP_SERVICES is a JSON object available to your application whenever you bind to a Bluemix service. The credentials section is common to every service and contains all the information you need to connect to that service. For the Bluemix MySQL service, it's the usual database name, port, user ID, and password:

    var port = (process.env.VCAP_APP_PORT || 3000);
    var host = (process.env.VCAP_APP_HOST || 'localhost');
    
    // all environments
    app = express();
    
    // check if application is being run in cloud environment
    if (process.env.VCAP_SERVICES) {
      var services = JSON.parse(process.env.VCAP_SERVICES);
    
      // look for a service starting with 'mysql'
      for (var svcName in services) {
        if (svcName.match(/^mysql/)) {
          var mysqlCreds = services[svcName][0]['credentials'];
          var db = mysql.createConnection({
            host: mysqlCreds.host,
            port: mysqlCreds.port,
            user: mysqlCreds.user,
            password: mysqlCreds.password,
            database: mysqlCreds.name
          });
    
          createTable();
        }
      }
    }

    Three routes are set up, and all use a simple index.html as the view. The post to /upload reads the file, splits it into individual lines, and inserts the lines into the MySQL database.

    // upload file
    app.post('/upload', function (req, res) {
      fs.readFile(req.files.file.path, 'utf8', function (err, data) {
        if (err) return res.json(err);
        // split file into array of non-empty Strings
        var posts = data.split(/\r\n?|\n/).filter(isNotEmpty);
        
        // insert posts into mysql db
        addPosts(posts, function (err, result) {
          if (err) return res.json(err);
          var msg = 'Added ' + result.affectedRows + ' rows.';
    
          // display all posts
          getPosts(function (err, posts) {
            if (err) return res.json(err);
            res.render('index.html', {posts: posts, msg: msg});
          });
        });
      });
    });

    addPosts does the database inserts, and getPosts returns the posts from the database for use in the index.html view:

    function addPosts(posts, cb) {
      var sql = 'INSERT INTO posts (text) VALUES ?';
      
      var values = posts.map(function (post) {
        return [post];
      });
      
      db.query(sql, [values], function (err, result) {
        if (err) return cb(err);
        cb(null, result);
      });
    }
    
    function getPosts(cb) {
      var sql = 'SELECT text FROM posts';
      db.query(sql, function (err, result) {
        if (err) return cb(err);
        cb(null, result);
      });
    }

Step 2. Push the application to Bluemix

 
  1. Install the Cloud Foundry V6 command-line interface for your system if you haven't already done so.
  2. Change to the application's app directory and log into Bluemix from your workstation. The command syntax is cf login -a API_URL. Your login will look like this:
    C:\demo\bluemix-node-mysql-upload\app>cf login -a api.ng.bluemix.net

    You'll be prompted for your username, password, organization, and space.
  3. Once you're logged in, create the MySQL service that the Node application will use. The command syntax is:
    cf create-service SERVICE PLAN SERVICE_INSTANCE

    The service name is mysql, the plan is 100, and the service instance name is mysql-node-upload. So you'll create your MySQL service like this:
    C:\demo\bluemix-node-mysql-upload\app>cf create-service mysql 100 mysql-node-upload
  4. Now comes the fun part. Instead of having to get a server, load the operating system, Node, npm, MySQL, and patch code, and fill out endless change tickets etc., etc., etc., you simply push your application to Bluemix and let Bluemix handle the messy parts.

    We've included manifest.yml file with the application to streamline the process. It sets the application name, memory, number of instances, and the Bluemix MySQL service to use. Choose a different host name so that your resulting URL route doesn't conflict with the demo URL (http://NodeMySQLUploadArticle.mybluemix.net):

    Click to see code listing

    ---
    applications: #Reference http://docs.cloudfoundry.com/docs/using/deploying-apps/manifest.html
    - name: NodeMySQLUpload #Application Name. Unique to the user's Space
      memory: 256M #The maximum memory to allocate to each application instance
      instances: 1 #The number of instances of the application to start
      host: NodeMySQLUploadArticle #Hostname for app routing. Unique to domain ng.bluemix.net.  Change.  
      path: . #Path to the application to be pushed
      command: node app.js #The command to use to start the application
    services: 
    - mysql-node-upload #the already created mysql service

    From the app directory that contains app.js and the manifest.yml file, push your application:
    cf push

    When the application is running, go to http://my-unique-hostname.mybluemix.net (where my-unique-hostname is the host in the manifest file). Upload a text file. It works!
Screen capture shows the MySQL Upload application's UI on Bluemix

Click to see larger image

Step 3. Manage your application from the Bluemix UI

 

Now that the application is running in Bluemix, let's use the Bluemix UI to take a look at its parts. Go to Bluemix and log in. From the Bluemix dashboard, you'll see a tile that summarizes the application. At a glance, you can see the URL and the bound services, and that the application is healthy and running:

Screen capture shows the MySQL Upload application status summary on Bluemix

Click the application tile to go to the application overview page, where you can explore more about your application.

Screen capture shows the MySQL Upload application overview page on Bluemix
  • Visit the runtime page, where you can adjust your application instances and memory, and view overall application health.
  • Check out files and logs, where you can see your deployed application code and look at staging, standard out, and standard error logs.
  • You can also rename the application, change its URL, and stop, start, and delete it.

Conclusion

 

That's it! In short order, you wrote, deployed, ran, and managed an application in IBM Bluemix. Enjoy the rest of your Bluemix exploration.


RELATED TOPICS:Node.jsBluemixMySQL

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=Cloud computing, Web development
ArticleID=963728
ArticleTitle=Learn IBM Bluemix with a simple Node.js file-upload application
publish-date=06302014