Using heroku for Sencha Touch demo site

I needed to put a demo Sencha Touch app to showcase some of features of the framework. I wanted to put this somewhere that I could easily put up and take down if required. Currently I have no domain space that was suitable so decided to use Heroku for the job mainly to see what steps were required to get such a thing working with node.js.

The solution was quick and easy to implement.

Firstly I created a node.js script  to do the serving of the page. The script was not all that different from the example in this tutorial, which used the node-static npm

var static = require('node-static'),
  http = require('http'),
  util = require('util');
var webroot = './sencha',
  port = process.env.PORT || 5000;

var file = new(static.Server)(webroot, {
  cache: 600,
  headers: { 'X-Powered-By': 'node-static' }
});
http.createServer(function(req, res) {
  req.addListener('end', function() {
    file.serve(req, res, function(err, result) {
      if (err) {
        console.error('Error serving %s - %s', req.url, err.message);
        if (err.status === 404 || err.status === 500) {
          file.serveFile(util.format('/%d.html', err.status), err.status, {}, req, res);
        } else {
          res.writeHead(err.status, err.headers);
          res.end();
        }
      } else {
        console.log('%s - %s', req.url, res.message);
      }
    });
  });
}).listen(port);
console.log('node-static running at http://localhost:%d', port);

I knew this script was very basic but as I didn’t have much time to do this (literally an evening), and it worked I decided to go with it.

I put all the sencha code into a sub folder called “sencha” and saved the javascript above as server.js. I then tested running it locally by using command “node server.js”. Browsing to http://localhost:5000 brings up ./sencha/index.html, which in turn should load up the sencha app. It seems node-static, like any web server, defaults to index.html in the absence of any specific request.

This all worked fine so to get the app on heroku. I had to add a Procfile and a package.json file. The Procfile just had one line; web: node server.js. The package.json file contained the node-static npm version:

{
  "name": "static",
  "version": "0.0.1",
  "dependencies": {
    "node-static": "0.6.4"
  }
}

You must have the correct version for any npm’s used or heroku will crash when deploying. To make sure you have this, execute the following locally:npm list. This will list all npms saved and their versions.

Once you have everything in place you can deploy to Heroku using their instructions: https://devcenter.heroku.com/articles/nodejs

Advertisements