After getting started with the basic syntax and some frequently used functions, I needed to learn to write some code.

I enjoyed this nice intro to functions.

myfunction <- function(arg1, arg2, ... ) {

We can put functions (or any code) in a text file and load it from the R command line:


where mycode.R is in the same directory as where I’m running R or a full path to the script.

But then I got stuck in how to transform my data table. As much as I wanted to iterate using loops, I felt that was a very un-R-like solution. I found some good patterns in @xieyihui‘s gory loops post.

If you need to make a string, you can use paste like Ruby’s join method:

> words  words
[1] "one"   "two"   "three"

> paste(words)
[1] "one"   "two"   "three"

> paste(words, collapse="")
[1] "onetwothree"

> paste(words, collapse=",")
[1] "one,two,three"

> paste(words, collapse=", ")
[1] "one, two, three"

Sails.js is a Node.js MVC framework. Rails developers will find the components quite similar, but I think Sails has done a really good job of leveraging libraries and frameworks that it integrates. In addition to Node, it sits on top of Express, which handles HTTP requests. In fact every request object, is simply an Express request. Sails also nicely integrates

Install on OSX

brew install node
npm install sails -g
sails -v

Make a Project

sails new testProject
cd testProject
sails lift

In your browser, go to: http://localhost:1337/ and there are some pointers to the docs and hints about what to do next.


sails generate api user
sails lift

Now in the browser http://localhost:1337/user returns a JSON representation of our list of users, which is an empty array at this point.

By default, your project is configured with a dynamic schema using the default disk databas, which lets us experiment by creating models using the browser:

The default routes are configured in config/blueprints.js, so you can turnoff these “shortcut” routes if you want to only have the more standard REST-ful syntax generated for your APIs. If you are fond of it from Rails, you can also tell Sails to pluralize names in the same config file.

Now if you go to: http://localhost:1337/user

You can see your users:

    "name": "Tim",
    "createdAt": "2014-12-21T18:20:19.382Z",
    "updatedAt": "2014-12-21T18:20:19.382Z",
    "id": 1
    "name": "Judy",
    "createdAt": "2014-12-21T18:20:26.269Z",
    "updatedAt": "2014-12-21T18:20:26.269Z",
    "id": 2
    "name": "Lee",
    "createdAt": "2014-12-21T18:20:29.338Z",
    "updatedAt": "2014-12-21T18:20:29.338Z",
    "id": 3
    "name": "Maggie",
    "createdAt": "2014-12-21T18:20:32.879Z",
    "updatedAt": "2014-12-21T18:20:32.879Z",
    "id": 4

Check Out Sockets

Open Javascript console in your browser, and you should see:

  \___/  `io.socket` connected successfully.

Try this at the console to see the list of users:

io.socket.get('/user', {}, function (users) {console.log(users)})

To listen for changes to any user model:

  io.socket.on('user', function messageReceived(event) {
    console.log('New comet message received :: ', event);

Open another browser window, and create a user:


then you’ll see the notification in your first browser window

New comet message received ::
Object {model: "user", verb: "create", data: Object, id: 5}

The documentation is pretty good, but a lot of has changed for the recent 0.10 update, and their intro video is a couple of revisions behind. To get up to speed on the changes in the new release, I updated what that intro would be in the new syntax on github ultrasaurus/sails-new, which includes the above tutorial and a few other details.

It has been surprisingly hard to find a very simple tutorial to get started with Express, along with some common helpful tools, including tests!

Here’s a little tutorial for Node.js v0.10 and Express 4. I’m learning Express, since I’m working on an app in SailsJS, so I will pick options that mirror choices made by the SailsJS framework.

Install Express

Express is a popular simple web app framework for Node (similar to Sinatra for Ruby), and is easily instally with the fabulous Node Package Manager, npm. I find the generators to be handy (at least for learning) and don’t ship with Express anymore, so you need to install them separately.

npm install -g express
npm install -g express-generator

Create an Express App

Let’s create an app named ‘test-app’ — this will create a new directory of that name with all the app files in it.

express test-app -e

The -e option tells express-generator to use ejs. (From the Express guide: Jade is the default. Express-generator supports only a few template engines, whereas Express itself supports virtually any template engine built for node. For the complete list, see express --help

It shows you all the files it creates and even gives a hint about next steps:

cd test-app
npm install

npm install will download all of the dependencies specified in our “package.json” file and put them in the the node_modules directory. This directory will get big fast, so we probably want to add to .gitignore.

Run the App!

Start the server

npm start

Then go to http://localhost:3000/ and see:
Browser with URL http://localhost:3000 shows Express in large letters, smaller letters below display "Welcome to Express"

Stop the server with ctrl-C.

Take a moment to review the contents of the generated package.json, the npm docs are a good reference for the defaults. All of the dependencies that we have right now are ones that express decided we should have. Max Ogden has some nice docs about Node modules.

Add a “devDependency” section to package.json:

  "devDependencies": {
    "mocha": "*",
    "chai": "*",
    "supertest": "*",
    "supervisor": "*"

We’re adding a set of tools that are installed with npm but only used for development and testing.

Don’t forget to add a comma or we’ll get a scary looking error:

npm ERR! install Couldn't read dependencies
npm ERR! Failed to parse json
npm ERR! Unexpected string

Also in “package.json,” change

  "scripts": {
    "start": "node ./bin/www"


  "scripts": {
    "start": "supervisor ./bin/www",
    "test": "./node_modules/.bin/mocha"

the install the new packages with:

npm install

We’ve just added a set of development tools for rapid iteration and testing. The scripts section lets us create shortcuts for the npm command.

Supervisor Allows Fast Experimentation

Supervisor makes it so you can edit files and just refresh the page to see the change. Now that we have edited the npm ‘start’ script to use supervisor, we can:

npm start

We can view the main index page, by going to http://localhost:3000. Then without stopping the server, let’s edit


so the H1 text says “Hello!” instead of Express. We can refresh the page to see the update.

Mocha, Chai and Supertest for Testing

Mocha will serially run a set of tests and report failures nicely. It supports a number of different assertion libraries. Chai is a single assertion library that supports the popular variants: assert, expect and should.

You’ll need to create a test directory, empty for now. Let’s make sure we’re set up right:

mkdir test
npm test

We should see:

  0 passing (2ms)

create the file


with a test

var request = require('supertest')
  , express = require('express');
var app = require('../app');
describe('Index Page', function() {
  it("renders successfully", function(done) {
    request(app).get('/').expect(200, done);    

run the test with

npm test

and it passes!

Adding New Behavior Test First

We can add expectations to our test. Let’s plan to add the text “Hello World to the index page. Supertest supports simple regex syntax for comparing text. The super test API cleverly supports concise testing by assuming a number as the first param is a status code, but a regex or a string wants to compare to the body.

  it("renders successfully", function(done) {
      .expect(/Hello World/, done);    

This will fail

  1) Index Page renders successfully:
     Error: expected body '\n\n  \n    Express\n    \n  \n  \n    <h1>Hello!</h1>\n    

Welcome to Express

\n \n\n' to match /Hello World/

Now we can edit the page in


and run the test again with

npm test

to see it pass!

  Index Page
GET / 200 10ms - 211b
    ✓ renders successfully 

  1 passing (34ms)