Monday, June 11, 2012

Building HelloSun, Step 6: Speech Bubbles

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 5 T.O.C.

I'm not very happy with this scrolling "chat" part of the web page, which so far looks like this:

I'd much prefer each person's comment to appear in a speech bubble, as I've sketched on this post-it note:

prototyping with newfangled css layout and rounded corners

Borrowing liberally from Pure CSS speech bubbles, I tweaked this local html file:

<style type="text/css">

.bubble-content {
  margin:4px 0 0 0;
  background:#f3961c; /* for browsers without gradient support */
  /* css3 */
  background:-webkit-gradient(linear, 0 0, 0 100%, from(#f9d835), to(#f3961c));
  background:-moz-linear-gradient(#f9d835, #f3961c);
  background:-o-linear-gradient(#f9d835, #f3961c);
  background:linear-gradient(#f9d835, #f3961c);
  font-family: Arial;
  font-size: 12px;

.bubble-citation {
  margin:0 0 8px 0;

.whom {
  margin: -8px 0 0 14px;
  font-family: Arial;
  font-size: 12px;

.quote-tail {

.quote-tail2 {

  <div class="bubble-content">
    This is some bubble content I could just go on and on and on
    and maybe I will because, really, you know, I have an awful
    lot to say because I'm just very verbose.
  <div class="bubble-citation">
    <div class="quote-tail"></div>
    <div class="quote-tail2"></div>
    <div class="whom">Tommy</div>

  <div class="bubble-content">
    This is some more bubble content.
  <div class="bubble-citation">
    <div class="quote-tail"></div>
    <div class="quote-tail2"></div>
    <div class="whom">Sally</div>

In a modern browser the HTML above produces this page

That looks enough like the bubble quotes I drew on the post-it note that I'll use it. (I may come to regret relying so much on the latest CSS, when I get around to testing in different browsers--but since the primary clients I'm considering will be the most popular smartphones, and they all support this level of CSS, I won't worry about this issue yet.)

change the chat insertion code to use these newfangled css bubble quotes

By adding the css classes from the local html prototype file into the "chatty.css" file, and changing the "appendMsg()" function in "chatty.js to this:

function appendMsg(msg) {
    $('#msgs').append(function() {
        var div, html;
        div = $('<div>');
        html = '<div class="bubble-content">' +
                    simple_html_escape(msg.message) +
                '</div>\r\n' +
                '<div class="quote-tail"></div>\r\n' +
                    '<div class="quote-tail2"></div>\r\n' +
                    '<div class="whom">' +
                        simple_html_escape(msg.username) +
                    '</div>\r\n' +
        return div;
    $('#msgs')[0].scrollTop = $('#msgs')[0].scrollHeight;

the server now displays the chats within speech bubbles.

let's look better on an iPhone

The primary client for HelloSun is expected to be mobile clients. A couple of small adjustments can be made to make this code look better on iphones. The primary change is adding a "meta" tag to the layout of all files in this line added to layout.jade:

  meta(name="viewport",content="width=device-width; initial-scale=1; maximum-scale=1")

check for blank inputs

The next little change for today's code is to prevent users from submitting if they haven't entered either a name or a message, because if those fields are blank it looks silly on the client displays. That's done with a simple function to remove space from the beginning and end of fields (the "trim()" method found at Javascript Trim LTrim and RTrim Functions), and a simple check in the "sendMsg()" function of chatty.js to verify that the fields are not blank.

always scroll for new messages

The final change for today's code is to automatically scroll to the bottom of the page when a new message comes. This ensures that users are always seeing the latest messages from other users. This line in "chatty.js" function "appendMsg()" replaces the old style to work with the new type of page. (It's not particularly elegant, but it works.)

  window.scrollTo(0, document.body.scrollHeight);

the new look

With all of today's changes, the chat program now looks something like this:

...and that's good enough for today.

Getting the code

Today's code is labeled v0001.0005 and is available in these formats:
HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 5 T.O.C.

Saturday, June 9, 2012

Building HelloSun, Step 5: Clean Code is Happy Code

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 4 T.O.C. Step 6 ⇒

So far the HelloSun code has been very sloppy, and sloppy code is bug-prone code. So today we won't add any new functionality, but will just clean up some areas of sloppiness. These are all small changes, but they'll make me feel better (I'm a bit anal-retentive that way).

use a lint tool

lint tools look for obvious problems in source code. I don't see any valid reason not to use them. I'm using JSLint, but there are alternatives.

This early in coding, JSLint recommended a few minor changes (all of which I accepted, in one case using jQuery's "each" call to avoid using "hasOwnProperty"), but found only one real bug: (the variable "i" was not declared in "chatty.jade", so would have overwritten any global "i" and would also have been inefficient).

At the top of all the JavaScript files are now lines similar to the following, which are hints to the JSLint tool I'm using.

  /*jslint white:false plusplus:false nomen:false */
  /*globals $, io */

I won't be submitting any more javascript code before running lint on it.

use a minimized version of jQuery

jQuery is nearly a standard in client-side Javascript now, and is used in the node-simple-chat example code we plagiarized in Step 4. To save a little download time I've changed to jQuery download in chatty.jade from




move server-side javascript into its own "chatty.js" file

"chatty.jade" contained a few dozen lines of javascript code embedded in the html file. I prefer to move this javascript code to its own "javascript/chatty.js" file because it 1) let's me run lint against the code, 2) treats the javascript as its own resource, and 3) is easier for me to read.

don't alter Array.prototype

The node-simple-chat example code we plagiarized in Step 4 used a trick of altering JavaScript's "Array.prototype" simply to add an "inject" method used once. I find it very bothersome to be altering a built-in Javascript object (can we be sure it's writable? can we be sure no other user of the Javascript global is not using a similar function, or is not iterating over an expected list?).

So I changed "Array.prototype.inject" in "chatserver.js" to a simple "inject_message" function.

prevent users from injecting malicious html code

This is the only serious problem we're fixing today.

Whenever you're allowing user-generated as your source for output, you're providing a big hole for malicious user to cause problems. In our chat program so far, we take whatever text the user enters for their name or their message, and display this text directly in the browser of all users.

Imagine that a user enters the message "I like &lt;font color="green">&lt;i>green italics&lt;/i>&lt;font>." This would immediately show up in every users window as:
myame: I like green italics.
You might think this innocent use of html codes is kind of cool. But if a user weren't so innocent, they might be inserting code to links, or uncouth images, or even malicious script that would be executed within every user's browser.
This would allow any user of your service to deliver malicious functionality to every other user of your service. Yikes!
A very simple solution is just to escape a few special characters ("&lt;", ">", and "&") so that if they're part of user input that we are injecting into html, they will not be seen as raw html characters. This is done with the "simple_html_escape" function added to chatty.js:

  function simple_html_escape(s)
      return s.replace(/&/g,'&amp;')

"simple_html_escape()" is then added to "function appendMsg()" wherever the user-generated strings are display in the output page.

Getting the code

Today's code is labeled v0001.0004 and is available in these formats:
HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 4 T.O.C. Step 6 ⇒

Friday, June 8, 2012

Building HelloSun, Step 4: Real-Time Chat

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 3 T.O.C. Step 5 ⇒

HelloSun is going to be a kind of chat app, so for the next step let's make a very very very basic real-time basic chat page. It seems that the first thing anyone does when doing a node server is a chat app, so there are a whole lot of examples to borrow from.

For the first chat page I’ll steal liberally from the example at, making only minimal changes to make it work with Heroku and with the jade template language (for no other reason than I’m looking for excuses to learn more about Heroku and jade).

choosing for real-time(ish) push

A real-time chat app is one where as soon as somebody enters a message, everyone else on the chat sees it right away. In the traditional browser model, the browser client is not updated until the browser pulls data from the server (e.g. through a page refresh), but in this use it makes more sense to think of the browser pushing data to the client when it's available. Over the years many tricks have been developed to make it seem like the server can push data (many documented at Wikipedia Push Technology), and even more options are available as WebSockets become standardized.

The existing push technologies are a big bag of kludgy tricks that vary depending on the capabilities of the exact browser being used, and so I'm very glad that someone has bundled up a library of code to manage all of these differences once and for all, in a library called The the javascript library provides a single simple interface to direct communication between the client and the server, hiding whatever different methods are used to pull off the trick. (Thank you very much, Guillermo Rauch!) Another nice feature of is that the API for the client and for the server are nearly identical (which is the "client" and which is the "server" doesn't matter any more). has just two primary methods that we care the most about:
  • emit() sends a message to the other end of the connection
  • on() receives an event (usually a message from the other end of the connection)
Installing is under rapid development, but I believe I've found one that works stably on Heroku. To use this version of add this dependency line to your "package.json" file:

  "": "0.9.6"

then run “npm install -d" to cause the latest version of to be installed.

chatserver.js - server-side chat code

The server side of this chat server is in the new file "chatserver.js" (see Getting the code below, or view chatserver.js). "chatserver.js" is almost directly taken from the "chat.js" file at the node-simple-chat project we're plagiarizing. The primary change is in these lines:

  io.configure(function () { io.set("transports", ["xhr-polling"]);
  io.set("polling duration", 10); });

which are taken from Heroku's advice at Using Socket.IO with Node.js on Heroku to prevent from trying tricks that Heroku doesn't support.

This "chatserver.js" code, after connecting with the client, simply receives JSON strings labelled as "msg" (we could have picked any label, so long as it matches label the client sends), and appends that to the list of messages, and broadcasts the message to all connected clients. Pretty straightforward.  (I'm not a fan of the "Array.prototype.inject" trick in this code, but plagiarizers don't have much right to complain.)

To load "chatserver.js", the file "app.js" (see Getting the code below, or view app.js) gets this line added at the end:

  var chatserver_io = require('./chatserver').start(app);

chatty.jade - client-side chat code

The client side of the chat server is in the new file "views/chatty.jade" (see Getting the code below, or view views/chatty.jade)  "chatty.jade" is almost directly taken from the "chat.html" file at the node-simple-chat project we're plagiarizing, only changed to support the jade templating library.

"chatty.jade" is straightforward. It collects input, sends it to the server (with socket.emit('msg',...)), and displays in the chat window any chat messages it received from the server (with socket.on('msg')).

Warning: including '' in the web page contains magic

In my opinion, the creators of "" were just a tiny bit too clever in integrating with node.js, because the way it gets included seems to much like magic.  In "chatty.jade" is included with this single line:


which jade turns into this line in the client html file:

  &lt;script src="/">&lt;/script>

But if you look on the server under the directory where you expect javascript files to be loaded, which is in "/public/javascripts", there is no "" file there.  So how does "" get loaded in the client if the file doesn't exist on the server? That's where the magic comes in:

When is initialized on the server (require('').listen(app) in chatserver.js) the adds a lot of code, much of which alters the server socket code. Part of that alteration is to specifically manage a request for the file "", at which point the server-side code puts together an appropriate file and delivers that to the client.  Magic!


Here's a summary of all the changes made in this version (see Getting the code below for full source):

  • add chatserver.js (plagiarized) to use, and initialize from apps.js
  • create chatty.jade and chatty.css (plagiarized) to be a page for the chatty client, and make express render aware of it through changes to routes/index.js and app.js
  • change layout.js to support block in templates, and alter views/index.jade and apps.js to turn that on

Test and Deploy:

If you run this new code locally (# foreman start) and check http://localhost:3000/, or push this code to the live server (commit with git, then # heroku restart web.1), you should see a new chat window looking much like this:

Now you have a chat-window, live on the web, that anyone can join at any time (from any browser?).  Whoopee!

Getting the code

Today's code is labeled v0001.0003 and is available in these formats:
HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 3 T.O.C. Step 5 ⇒

Thursday, June 7, 2012

Building HelloSun

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.

The latest version of this application is always running at  The code is also available on github.

Building HelloSun, Step 3: Being Express-y

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 2 T.O.C. Step 4 ⇒

In Step 2: Hello Node & Heroku, the Heroku setup and default were a bit too basic. We're going to want to make something slightly more complicated than a simple "Hello World!" page. We'll eventually want multiple pages, with multiple HTML pages and related atrtibutes (CSS, Javasript, and images). We don't want to write any more code than necessary, so we'll want to use some existing framework where most of that grunt-work code has already been written. For this project we'll use Express.

Why choose Express?

I put very little thought into choosing Express as my framework. A version of Express was part of the default Heroku install, and a cursory review of discussions about the topic make it look like Express is currently the most active and popular. So I'll start there. If Express turns out to be terrible... well, there's no better way to find out that it sucks than to try it out for myself.

In other words, I'm using Express because everyone else is using it. (And, yes, if all my friends are jumping off a cliff then I'm jumping off with them.)

(Re)Installing Express

Even though the Heroku install used Express by default, it didn't use Express in a standard "Expressy" way. So we'll do some quick changes to convert the default Heroku install into something that looks normal for default Express users. (Let's try not to reinvent anything fancy yet, and stick to the defaults.)

From within our application's directory (which we've been calling "~/hellosunx444") let's generate a default express app as defined at with this command:

  # cd ~/hellosunx444
  # node_modules/express/bin/express .

This command will add a lot of default directories that Express depends on (e.g. "views", "public"), will add some dependencies on Jade (the default Express template engine--we like starting with defaults), and a new "app.js" file.

This install will also have altered "package.json" in small ways, some of which we want to fix, so that "package.json" now looks like this:

      "name": "hellosun"
    , "version": "0.0.1"
    , "private": true
    , "dependencies": {
        "express": "2.5.8"
      , "jade": ">= 0.0.1"
      , "pg": "0.5.4"

As we'll do after every change to "package.json", run this command so all our packages are updated:

  # npm install -d

Adjusting default Express files to run on Heroku

A couple of changes to the Heroku files will get us back on track to have a standard Express layout be running on Heroku.

Express' default starting file is “app.js”, while the original heroku sample ran as “web.js”. You want Heroku to be using this “app.js” instead of the old “web.js” so edit the file “Procfile” to be

  web: node app.js

We only want one change from the previous "web.js" file, and that is part that adjusts the port to be running on for the Heroku environment. When running locally we can specify the port, but in the heroku environment heroku will be selecting that port for us (it's background system will have some kind of gateway and port 80, but that will be redirecting to some port of its choosing). In "web.js" that line was:

  var port = process.env.PORT || 3000;

In the “app.js” file created by Express the same can be done by replacing:



  app.listen(process.env.PORT || 3000);

If we test this code locally (# foreman start) and check http://localhost:3000/, or push this code to the live server (# heroku restart web.1), then check we see it’s running the new Express code.

Go ahead and delete the "web.js" file; it is no longer needed. (I don't like to keep files around that aren't being used--that's just confusing.)

Create the first HelloSun Express application

The default home file that Express created is in “routes/index.js” (more on how this resolves later). Change "title" to “HelloSun” to match our program.

After pushing to the server (# heroku restart web.1), we have an Express app named “HelloSun” that runs on Heroku. Yea!

Getting the code

Today's code is labeled v0001.0002 and is available in these formats:
HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 2 T.O.C. Step 4 ⇒

Tuesday, June 5, 2012

Building HelloSun, Step 2: Hello Node & Heroku

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 1 T.O.C. Step 3 ⇒

In Step 1: Planning, part of the goal was to “use the latest & simplest techniques and tools, and zero upfront costs.”

The “simplest techniques” goal leads me to choose a Platform as a Service (PaaS) solution. With PaaS, the service provider handles most of the infrastructure involved in handling a web server. I simply must write the code that’s unique to my particular application. There is an Ever-Growing List of PaaS Companies to choose from.

The “zero upfront costs” goal narrows down the list to those that offer a free option. Many of them offer free getting-started options, either for a limited time or for a limited amount of CPU and bandwidth.

The “latest techniques and tools” goal makes me want to chose Node.js as the server technology. Node.js is a javascript-based server that, because it almost totally event-driven and non-blocking, leads to efficiency, meaning: this model should allow me to support the most clients possible before having to move to a paid service. I almost went with Ruby, simply as an excuse to learn a new language, but it’s not quite “the latest thing” anymore, I had trouble installing it locally (more on that later), and I hear some disappointing things about its throughput. (I also am persuaded to choose Node.js because of a personal long history behind Javascript, as well as recent fun creating the CrappyNet bad-networking RESTful stress tester.)

I chose Heroku as my PaaS for this project because it supports Node.js and has a nice free option: the equivalent of one server process (enough for Node.js to handle many clients) along with a small free database options (enough for a sunrise-limited window of chats, if that even needs to be part of a database), and because of these additional considerations:
  • Documentation – Heroku’s documentation seems concise and mostly correct.
  • Local Development and Testing – With the Heroku stack I can easily run the app on my local computer very close to how it will run on the server. Thing globally, develop and test locally.
  • Easy Deployment – After testing locally, deploying to Heroku is as easy as a git push.
  • Easy to Switch (no Heroku lock-in) – Because there is nothing special or proprietary to Heroku or the stack I’m using, I can easily stop using Heroku at any time and switch to many other PaaS or, if this service is doing spectacularly well, I can easily move to my own servers at any time.
Get git

git version control is required for working with Heroku. Introducing git is outside the scope of this post, but if you’re doing anything in software these days you need to become familiar with it, so you may as well start at the Official git website.

Install Node locally

Using the Node Installer is super simple. Just download from  I do not recommend getting the latest version of Node from their github repository because those versions are too new to match what is running on Heroku.

After installing node I can run “node --version" at the command line and see that I have “v0.6.18”.  This is close to what is on Heroku and hopefully will work fine.

Get a Heroku Account

Sign Up for an account at

Install the Heroku Toolbelt Locally

The Heroku documentation is very straightforward at In particular, I followed the steps at Getting Started with Node.js on Heroku/Cedar.

In Local Workstation Setup you’ll install the Heroku Toolbelt, which is what will let you run all the necessary Heroku tools from the command line on your local computer.

Write and test your first App

Heroku’s Write Your App instructions worked almost perfectly for me, except that the version of “express” in their example did not match the default I found with the heroku install, and I had a new name for my app. So my version of package.json is:

    "name": "hellosun", // your name, e.g. "hellosunx444"
    "version": "0.0.1",
    "dependencies": {
      "express": "2.5.8"

    "engines": {

      "node": "0.6.x",
      "npm":  "1.1.x"


After following the next set of the instruction at at Getting Started with Node.js on Heroku/Cedar (create web.js, “npm install”, create .gitignore, create Procfile) you should be able to run the code locally with this command:
$ foreman start
Test this with a browser at http://localhost:5000/. If that shows “Hello World!” then you’ve got a local node server running the web.js code. Congratulations!

Deploy your first App to the World Wide Web

Heroku’s Getting Started/Deploy instructions worked fine for me. They are:
$ git init
$ git add .
$ git commit -m "init"
$ heroku create hellosunx444 --stack cedar
$ git push heroku master
$ heroku ps:scale web=1
$ heroku config:add NODE_ENV=production
Testing your first App to the World Wide Web

Browse to and if you now see “Hello World!” then your application is now deployed to heroku. Congratulations!

Changing code and restarting

In step 3 through step X, we’ll be changing this code a lot. So let’s quickly cover how to change the code to “Hello Squirrel!” and redeploy:
  1. Edit web.js to change “Hello World!” to “Hello Squirrel!”
  2. Test locally with “foreman start” and verify that http://localhost:5000/ displays “Hello Squirrel!”
  3. Use git to push your change to web.js to the heroku git server (using your favorite git tools or commands, such as “$ git commit –a”, “$ git push”.
  4. Restart the heroku server with your new code: “$ heroku restart web.1”
  5. Verify that now shows “Hello Squirrel!”
Getting the code

Today’s code is labeled v0001.0001 and is available in these formats:
HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
⇐ Step 1 T.O.C. Step 3 ⇒

Monday, June 4, 2012

Building HelloSun, Step 1: Planning

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
T.O.C. Step 2 ⇒


Much has changed since I wrote my first computer software in the late 1970s. Back then, if you’d told people you wanted to spend a couple of weeks creating a program that would instantaneously connect everyone in the world in a live experience, and that you intended to do it single handedly and for zero cost, they would have called you nuts.

But now, in 2012, using the latest tools and languages, this should be a piece of cake. In this X-part series I intend to see if that’s true, and to document each step of the process.


Use the latest & simplest techniques and tools, and zero upfront costs, to create a social networking app. And to document how it’s done.

What is “HelloSun” (and why)?

First, I want to tackle something that contains most components of modern social software, but that is not too complex. “Chat” embodies a smallest-common-denominator component of social software, and does not introduce any radically new ideas.

Second, I want something with a limited storage need, because I haven’t yet figured out how to stick to my “zero cost” goal if very much storage is involved (even though storage is very very cheap, anything beyond a fixed size is not yet free).

Third, I want to explore the concept of the value of limitations. It seems that most applications or websites that catch on do so because they do so very little (at least initially), and that their virality is inversely proportional to their complexity. (Would Twitter have caught on if it allowed for long diatribes? Would Instagram have caught on if it didn’t have so few options? Would Facebook have ever reached the size it is now if it had started out as complicated-to-use as it is now?) So I want to create something that does as little as possible.

To achieve the above goals I’m planning the “HelloSun” application. For most of the day (23+ hours of each day) HelloSun will do absolutely nothing. But during a few minutes before and after sunrise (whenever sunrise is for each user’s location), it will be a simple chat app shared by anyone in the world who is also experiencing sunrise. Then, for the rest of each day, it goes back to doing nothing, and the mornings chats are all gone forever (poof).

HelloSun will be a brief chat window at the start of each day. That’s all!


I don’t know exactly what the plan is, since I haven’t started yet, but on day 1 here’s what I expect to do:
  1. Choose a PaaS (Platform as a service) provider that offers a free getting-started plan (probably Heroku).
  2. Choose a framework for writing server code (probably NodeJS because that seems to have all the latest buzz around it).
  3. Write a very basic web page (i.e. “hello world”).
  4. Write a basic chat server as a web page.
  5. Tie the server into a local (small) database of users (maybe) and chat info.
  6. Make the service use location information to only work at sunrise.
  7. Make the web-based chat server look pretty on multiple browser sizes (from desktop to mobile).
  8. Choose some framework for creating mobile apps (probably PhoneGap with Build).
  9. Create App version of HelloSun and get into the app stores (for iOS? Android? Etc…?)
  10. ?
  11. Profit
(Thanks to "The Underpants Gnomes" for the final phases of this business plan.)

HelloSun: A guide to creating a social networking empire, from scratch, for free, circa 2012.
T.O.C. Step 2 ⇒