CoffeeScript Application Development

By Ian Young
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Running a CoffeeScript Program

About this book

JavaScript is becoming one of the key languages in web development. It is now more important than ever across a growing list of platforms. CoffeeScript puts the fun back into JavaScript programming with elegant syntax and powerful features.

CoffeeScript Application Development will give you an in-depth look at the CoffeeScript language, all while building a working web application. Along the way, you'll see all the great features CoffeeScript has to offer, and learn how to use them to deal with real problems like sprawling codebases, incomplete data, and asynchronous web requests.

Through the course of this book you will learn the CoffeeScript syntax and see it demonstrated with simple examples. As you go, you'll put your new skills into practice by building a web application, piece by piece. You'll start with standard language features such as loops, functions, and string manipulation. Then, we’ll delve into advanced features like classes and inheritance. Learn advanced idioms to deal with common occurrences like external web requests, and hone your technique for development tasks like debugging and refactoring.

CoffeeScript Application Development will teach you not only how to write CoffeeScript, but also how to build solid applications that run smoothly and are a pleasure to maintain.

Publication date:
August 2013
Publisher
Packt
Pages
258
ISBN
9781782162667

 

Chapter 1. Running a CoffeeScript Program

The very first thing we need to do in order to start using CoffeeScript is to install CoffeeScript itself. This will give us access to the CoffeeScript compiler, which we'll use to compile our beautiful CoffeeScript code into JavaScript that can be run in a browser (or other JavaScript environment). By the end of this chapter we'll be completely set up and ready to work.

There are a couple of steps involved in installing CoffeeScript. I know you're impatient to dive right into this great new language—who can blame you? But we'll have to stick it out through a little bit of system configuration. If we do so, we'll be rewarded with a stable CoffeeScript setup that works flawlessly and doesn't take any more of our attention.

In this chapter we will:

  • Install the software that you need to run CoffeeScript code

  • Learn how to use the software to run CoffeeScript, both from the command line and in a browser

  • Use our new abilities to write a simple web application using CoffeeScript

 

Installing Node.js


To run CoffeeScript, first you'll need to install Node.js. Don't worry! If you don't want to learn Node.js, you won't need to. We just need to have the platform installed because the CoffeeScript compiler uses it.

Tip

If you get stuck at any point while installing or using Node.js, the IRC channel is a great place to look for help. You can use your IRC client of choice to connect to the #node.js room in irc.freenode.net, or you can connect through a web browser by visiting http://webchat.freenode.net/?channels=node.js.

Node.js (or simply Node) is a platform for running JavaScript at a low level, using the powerful and fast V8 engine. It's primarily used for web development, allowing developers to write the server side components of web applications in JavaScript. Node's most notable innovation is that it's highly non-blocking. Any system call that needs to wait for a result (such as network requests and disk reads) uses a callback, so Node can service another request while it waits for an operation to finish. This way of thinking meshes nicely with web applications which do a lot of network interaction, and it provides a lot of bang for your hardware buck. While we'll be using CoffeeScript to build a client side application, it works great with Node as well. We'll show you more about that in Chapter 11, CoffeeScript on the Server. The CoffeeScript compiler is written entirely in CoffeeScript and runs on Node. If you're curious, you can find the annotated CoffeeScript source on http://coffeescript.org/.

Installing Node.js on OS X

The Node project provides several options for installation on Mac OS X. The simplest method is the universal installer. If you don't already use a package management system for your development tools, you should use the installer. If you use Homebrew or MacPorts to manage your system and would like to install Node through those, follow the instructions for your package manager instead.

Tip

If for some reason none of these methods work for you, see the Compiling Node.js manually section. However, this is more difficult and not recommended unless you really need it.

Using the installer

The Node project provides a universal installer for Mac OS X. Visit http://nodejs.org/download/, and look for Macintosh Installer.

Download that file and double-click on it. Follow the prompts to install Node on your system.

Using Homebrew

Homebrew is a popular package management system for OS X. It maintains installed packages in a completely separate directory from the OS X system files, and offers easy package management from the command line. Homebrew offers an easy-to-use formula system to create new package definitions, and as a result offers a very large collection of user-contributed recipes.

Note

Early versions of the Node package on Homebrew suffered from numerous bugs. Recent versions have received far fewer complaints and should be acceptable for our needs. Still, if you encounter serious problems using Node from Homebrew, consider uninstalling it and using the universal installer instead.

To install Node using Homebrew, simply use the command-line installer as follows:

brew install node

Tip

For help with Homebrew, visit the official site at http://mxcl.github.com/homebrew/.

Using Macports

MacPorts is another package management system for OS X. Like Homebrew, it maintains installed packages separately from the OS X system files. MacPorts is an older project, and is modeled on the BSD ports system. While it has been waning in popularity in recent years, it still has a large user base.

To install Node using MacPorts, simply use the command-line installer as follows:

sudo port install nodejs

Tip

For help with MacPorts, visit the official site at https://www.macports.org/.

Installing Node.js on Windows

There are several convenient installation options for Node on Windows. The method recommended for most people is to use the installer. If you cannot install software on your machine, or for other reasons wish to isolate Node, you can use the standalone executable instead. Finally, if you are already using the third-party package manager Chocolatey to manage packages on your machine, you may install Node through that system.

 

Using the installer


The Node project provides an install file for Windows systems. Visit http://nodejs.org/download/, and look for Windows Installer:

Download that file and double-click on it. Follow the prompts to install Node on your system.

Using the standalone executable

The Node project provides a node.exe file that you may download and call without installing anything on your system. Visit http://nodejs.org/download/, and look for Windows Binary.

Download that file and put it in a directory you'll remember. Now you can call the file from the command line using the full path, as follows:

"C:\Documents and Settings\Ian\Software\node" -v

To save yourself some typing, you'll probably want to add that directory to your path. Once you do that, you can just call node without the full path.

Tip

If you don't know how to add directories to your path, you can find instructions at http://www.computerhope.com/issues/ch000549.htm.

Using Chocolatey

Chocolatey is a package management system for Windows based on NuGet and Powershell. It is modeled on package managers for other systems, but is designed to deal with the Windows environment. It provides simple installation of many developer tools and libraries.

To install Node using Chocolatey, simply use the command-line installer:

cinst nodejs.install

Tip

For help with Chocolatey, visit the official site at http://chocolatey.org/.

Installing Node.js on Linux

The easiest way to install Node on Linux is to use the package manager for your particular distribution. Most distributions offer a Node package, which will save the trouble of building it manually. If your distribution does not offer a Node package, see the Compiling Node.js manually section at the end of this chapter.

Using a graphical package manager

If you have a graphical utility to manage your system, such as Ubuntu Software Center or Synaptic, you can use that. Open the program and search for "nodejs". You will see a result similar to the following screenshot. Choose Install and wait until it informs you that it is finished.

Using the command line

If you don't have a graphical utility, that's not a cause for alarm. Many distributions still use a command line tool to manage packages. Start by opening up a terminal. The exact commands to install Node depend on your package manager. Here are some of the more common options.

Tip

If you can't find your distribution listed here, try the Node.js wiki at https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager.

Linux Mint/Ubuntu 12.04 (Precise Pangolin)

Ubuntu, Mint, and other distributions based on Debian unstable can use the venerable apt-get command-line tool to install Node.

sudo apt-get install nodejs
Debian Sid/Ubuntu 12.10 (Quantal Quetzal)

Systems using cutting-edge Debian packages can install Node with apt-get as stated earlier. However, you may also want to install the nodejs-legacy package, which provides the node executable. If you do not install this extra package, you will need to invoke Node on the command line with nodejs instead of node (this change was introduced to deal with a conflict between two different packages that both provide a node executable).

sudo apt-get install nodejs nodejs-legacy
Arch Linux

Arch Linux offers an official Node package, which may be installed using the pacman command-line tool:

sudo pacman -S nodejs
Fedora

Node is available in Fedora 18 and later versions. Install it through the package manager:

sudo yum install npm

If you are using an older Fedora release, see the following section.

Compiling Node.js manually

If you cannot install Node using one of the methods listed earlier, you may be able to compile it from source. This will work on most UNIX-like systems (including Mac OSX, Linux, and BSD). You may need some perseverance—compiling software from source often involves a few hiccups along the way. Remember, if you get stuck, a search engine is your best friend.

Tip

For more information and solutions to some common problems, visit the Node wiki page on installation at https://github.com/joyent/node/wiki/Installation.

First let's install the dependencies we'll need to build Node. These include a C++ compiler, the make build tool, and Python (which is used in the build process).

sudo apt-get install python g++ make

Tip

The exact method you use to install the dependencies will vary based on your operating system. The commands shown should work for Debian based systems, including Ubuntu and Linux Mint. OS X users will need to install Xcode, and then install the Command Line Tools through Xcode.

Now we need to download the Node source code. Visit http://nodejs.org/download/ and choose Source Code. Save it to somewhere you can remember, say ~/Downloads.

Let's visit the directory where you saved the file and unpack it. Note that the filename will have a version number in it that may be different from what is printed on the screenshot and in the command-line instructions.

cd ~/Downloads
tar xzvf node-v0.8.15.tar.gz
cd node-v0.8.15/

Now we'll prepare, build, and install Node. Be patient—these commands can take a while to complete!

./configure
sudo make install

Tip

These commands may throw errors if they don't find everything they need on your system. Read the error messages carefully. If you can't figure it out on your own, try searching online with the text of the error messages. Often you will find an existing post with a solution to the problem you are encountering.

Skipping the Node installation step

On certain systems, it may be possible to install CoffeeScript as a system package, rather than installing Node first as we are doing. For example, older versions of Homebrew offered a coffeescript package, and Ubuntu provides a CoffeeScript package that can be installed through apt.

However, these packages may be buggy or out-of-date, and you may find it difficult to control which version of the CoffeeScript package you are using. You will be at the mercy of a package maintainer (who may not even be actively updating the package any more). I strongly encourage you to follow the process detailed in the earlier sections of this chapter . Once you have installed Node, it will be very easy to manage your CoffeeScript installation, and you'll be glad you took this route.

 

Testing our Node installation


Let's make sure your Node installation is working properly. Check the version number with node -v. We will be shown a version number, as follows:

node -v
v0.8.15

Now let's open up the Node console. This is an interactive tool that lets you run JavaScript right from your command line! It can be very helpful if you want to try out small ideas in code and receive immediate feedback. We'll see later that CoffeeScript provides an equivalent console.

Run this:

node

You will be presented with a prompt. Try entering some JavaScript code, and hit Enter to execute.

> "Hello, world!"
'Hello, world!'
> var x = 3 + 7
undefined
> x / 2
5

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Testing npm

We'll also check if npm is installed. npm is the Node package manager. It is a set of utilities for installing and managing tools and libraries written for Node. It is backed by https://npmjs.org/, the official online repository for Node packages. Almost any public code written for Node will be published in the repository and can be installed seamlessly with a single npm command.

If you have version 0.6.3 or above of Node, it comes with npm automatically. If you are still in the Node console, hit Ctrl + D to close it and return to your regular command line.

npm -v

If you see a version number, you have npm and can continue on to the next step.

Tip

If you don't have npm installed, the best way to get it is to upgrade to a recent version of Node following the instructions stated earlier. If you really cannot upgrade your version of Node, follow the installation instructions at https://github.com/isaacs/npm/.

 

Installing CoffeeScript


Hang in there! We're almost done. Now that we have installed Node, it's easy to install CoffeeScript.

npm install -g coffee-script

Tip

If this command fails with a permissions error (which is sometimes reported as an EACCES error), you may need to run it with sudo, as follows:

sudo npm install -g coffee-script

This depends on the permissions of your Node installation, and varies between different systems.

Now you should be able to see a version number when you run the following command:

coffee -v

If so, congratulations! You've installed CoffeeScript!

Tip

If you have trouble installing or using CoffeeScript, the IRC channel is a great place to look for help. You can use your IRC client of choice to connect to the #coffeescript room in irc.freenode.net, or you can connect through a web browser by visiting at http://webchat.freenode.net/?channels=coffeescript.

 

Our very first CoffeeScript code


Let's open up a CoffeeScript console. We saw earlier that Node provides a console to interactively run JavaScript code. You guessed it, the CoffeeScript console works the same way, but with CoffeeScript!

coffee
coffee> subject = "World"
'World'
coffee> "Hello, #{subject}!"
'Hello, World!'

Don't worry about the syntax for now. We'll get to that soon. When you're finished, hit Ctrl + D to close the console, and take a moment to bask in the glow of a properly configured development environment.

 

Compiling from a CoffeeScript file


Now that you've tried out the CoffeeScript console, let's try compiling a file. The console is great for trying out ideas and rapidly getting feedback from your code, but you'll do most of your work in CoffeeScript files, which you then compile to JavaScript.

Let's start with a very simple CoffeeScript file. CoffeeScript conventionally uses the .coffee extension, so let's name our file setup.coffee.

alert "Welcome!"

Note

The first thing that might jump out at you in this code is the lack of parentheses. In CoffeeScript parentheses are optional when calling a function, unless the function takes no arguments, or they are needed to resolve ambiguity.

Now let's compile this file to JavaScript. Run this from your terminal, in the same directory that holds setup.coffee:

coffee -c setup.coffee

The -c option tells the coffee executable that instead of opening a console, you wish to compile a file. You should now have a file in the same directory named setup.js. This is the result of your compilation. Open it, and you'll see JavaScript code. You might be able to guess what it will look like:

alert("Welcome!");

The CoffeeScript compiler usually creates very readable output (probably more readable than the output of a few programmers you know!). This is a great feature, because it means that if at any time you want to check the compiler's work, or debug, or explore how the compiler achieves something, you can simply open the compiled file in your favorite text editor and read through it. We'll make use of this throughout the book, especially in the next chapter. Be careful though—any changes you make to the JavaScript file will be overwritten the next time you compile. Treat the JavaScript output as read-only.

Tip

While working through the examples, you may see output from your compiler that is slightly different from that printed here. Different versions of CoffeeScript will produce subtle variations in output. These differences are usually superficial, so don't be alarmed. If you compare the two side by side, you will usually be able to find the difference and see that the rest of the code is unchanged.

 

CoffeeScript support in the editor


Let's add support for CoffeeScript to your favorite text editor. This step is optional, but I heartily recommend it. At a minimum, these plugins will provide syntax highlighting for CoffeeScript files, which I find very helpful. In addition, most plugins integrate with the editor to allow you to run or compile CoffeeScript snippets without leaving the editor. You don't need these features, but you may find them convenient.

Tip

We'll discuss CoffeeScript support in some of the most popular editors, but there are plugins available for many more. A full list is available on the CoffeeScript wiki at https://github.com/jashkenas/coffee-script/wiki/Text-editor-plugins/.

Follow the instructions to install CoffeeScript in your editor of choice. After installing, restart your editor and try it out by opening setup.coffee. You will see some simple syntax highlighting on the code we just wrote to indicate that the plugin is working correctly.

Support in TextMate

Jeremy Ashkenas, the creator of CoffeeScript, has written a TextMate bundle that provides syntax highlighting, snippets, and inline compilation. Visit the project homepage at https://github.com/jashkenas/coffee-script-tmbundle and follow the installation instructions.

Support in Sublime Text 2

Sublime Text users have several choices available for CoffeeScript support.

One option is to use parts of the TextMate bundle. To use this, create a CoffeeScript directory in Sublime Text's plugin directory (on OS X, this is found at ~/Library/Application Support/Sublime Text 2). Then, download the bundle, extract Syntaxes/CoffeeScript.tmLanguage and Preferences/CoffeeScript.tmPreferences and place these files in the new directory. To simplify the process, you can download these two files directly using the following URLs:

The other option is to use the native Sublime Text plugin for CoffeeScript. This offers more features and is built specifically for Sublime Text. Visit the project homepage at http://xavura.github.io/CoffeeScript-Sublime-Plugin/ and follow the installation instructions.

Support in Vim

A Vim script is available that provides syntax highlighting as well as a :CoffeeCompile command to compile CoffeeScript on the fly. Visit the project homepage at https://github.com/kchmck/vim-coffee-script/ and follow the installation instructions.

Tip

The official repository for this plugin may be abandoned by the original maintainer, and there are several annoying bugs that have gone unfixed. You may wish to install a patched version from one of the several active forks of the project instead, such as https://github.com/CITguy/vim-coffee-script/. Follow the provided installation instructions, but be sure to download files from GitHub and not vim.org. Substitute the fork you are using whenever the instructions specify kchmck/vim-coffee-script.

Support in Emacs

There is an Emacs Major Mode named coffee-mode that provides syntax highlighting, menu support, and on-the-fly compiling. Install it from the Emacs package archive, or visit the project homepage at https://github.com/defunkt/coffee-mode for more information.

 

Starting our web application


Now that we know how to compile a CoffeeScript file, let's use it in a web page! We'll create a simple web page that uses CoffeeScript to read a configuration object and insert text into the page. This page will be used by the owner of a small pet shop. We'll insert the owner's name dynamically, so it can be easily changed if needed. First let's create a simple index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>The Pet Shop</title>
      </head>
  <body>
    <h1>Welcome to <span id="owner_name"></span>'s Pet Shop</h1>
    <script src="setup.js"></script>
  </body>
</html>

You'll notice that we have a script tag pointing to our JavaScript file, just like normal. The web application doesn't need to know anything about our CoffeeScript files. It will run the compiled JavaScript output, happily ignorant of the original source.

Note

It is possible to make your browser aware of CoffeeScript, and make it run CoffeeScript code directly. However, this is an advanced technique and not really necessary to get you started, so throughout the book we will always compile to JavaScript and run that. If you'd like to learn more about this technique, see Chapter 10, Using CoffeeScript in more places.

Let's get rid of that annoying alert in setup.coffee, and update it with a configuration object and some code to insert the owner's name into the page heading. You probably know how you would write this in JavaScript. It's similar in CoffeeScript, so see if you can follow along:

shop = {
  owner: { name: "Ian" }
}
nameElement = document.getElementById("owner_name")
nameElement.innerHTML = shop.owner.name

Now we'll run the compiler again so that it updates the JavaScript. This time, we'll pass it the whole directory as an argument instead of our single file. This will compile any CoffeeScript files it finds in the directory, which will come in handy later, when we have more than one CoffeeScript file.

coffee -c .

Our setup.js has been updated, so load index.html in a web page, and it should say Welcome to Ian's Pet Shop.

One more thing

Let's make one small addition to our web application. We should update the title of the window with the owner's name as well. Before we edit our CoffeeScript file, it's time to learn a very helpful feature of the coffee command-line tool. Passing it the -w option when compiling will tell the tool to watch the source files or directory, and recompile them any time the files change. This saves you the trouble of going back to the command line and performing the compilation again every time you save a file. Start the compiler:

coffee -w -c .

Tip

For a full reference of options available from the command line tool, visit http://coffeescript.org/#usage or run coffee --help.

Now edit setup.coffee to add a line at the end:

shop = {
  owner: { name: "Ian" }
}
nameElement = document.getElementById("owner_name")
nameElement.innerHTML = shop.owner.name
document.title = shop.owner.name + "'s Pet Shop"

When you save the file, setup.js will be updated automatically. Reload the page, and you should now see the new name in the title bar. Cool, huh?

Tip

If you'd like to take this a step further, you could try out a tool like LiveReload. It watches your code and not only recompiles when it sees a change, but also reloads the page in your browser! Learn more at http://livereload.com/.

 

Summary


This chapter wasn't all fun and games, but it was worth it. We installed CoffeeScript and got everything configured properly. We also tried out some command-line tools to see how CoffeeScript development works, and to whet our appetites for more. We:

  • Walked through the steps of installing Node.js (the platform that CoffeeScript uses to run)

  • Installed CoffeeScript itself

  • Tried out the CoffeeScript console, and learned to compile files with the command-line tool

  • Built a very simple web page, and learned how to use the command-line tool to automatically recompile when we change our CoffeeScript files

Now we're all set up and ready to dive into the language itself, which is exactly what we'll do in the next chapter! We'll start by learning the basic syntax of CoffeeScript, and we'll get to see how it works and how it is related to JavaScript. We'll learn about variables, functions, loops, data structures, and more, and we'll get to play around with a lot of code samples. I hope you've got your command line ready!

About the Author

  • Ian Young

    Ian Young wrote his very first program on a TI-89 scientific calculator—an infinite loop that printed an insulting message to one of his friends. As one might expect, things could only improve from there. Ian graduated from Grinnell College with a degree in Computer Science, and since then has been working as a web developer for small tech companies; first in Minneapolis and now in San Diego. He loves web technology, small teams, frequent iteration, testing, beautiful ideas, free speech, free beer, and any tool that reduces cognitive overhead.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now