Ember With Node


Introduction

So since I’ve been working with Ember.js at work almost full time for the last couple of months. I’ve really enjoyed the experience. I’m finally feeling that productive push after the learning curve. I’m also starting to realize why so many have gone to JS. The JS community is so awesome, everywhere I go I find happy people willing to help out complete strangers. So thanks everyone!

I wanted to share with you a way to get Ember working in Node.js. At my work it’s pretty easy, we use Brunch with a Ember Reloaded Skeleton and use something other than Node.js to host our rest api. Which is a great option if you are using something other than Node.js or Rails for your Ember site.

But what if you want to use Node.js and Ember? One of the things I found was lots of different configurations and build tools but the one that I thought the easiest was Ember Tools. It provides a nice easy command line interface for building out your Ember site. Although it currently says it’s been rewritten I went ahead with it anyways.

One of the key configuration options is it allows you to specify where the build path is for your Ember site. Inside your root project a ember.json file can contain this:

{
  "jsPath": "lib/public/javascripts",
  "modules": "cjs"
}

That jsPath option is important. Now in node.js I’ve found if you structure your app like a npm module it works easy, and if you want later you can package up your entire web application as a module. Probably not great for production apps but maybe a fun little side project.

Here is an example app directory structure so you can see how my folder structure is setup:

.
├── LICENCE
├── README.md
├── bin
│   └── app
├── config
│   └── database.js
├── ember.json
├── lib
│   ├── api.js
│   ├── public
│   │   ├── css
│   │   │   └── app.css
│   │   ├── images
│   │   │   └── logo.png
│   │   ├── index.html
│   │   ├── javascripts
│   │   │   ├── application.js
│   │   │   ├── config
│   │   │   │   ├── app.js
│   │   │   │   ├── routes.js
│   │   │   │   └── store.js
│   │   │   ├── controllers
│   │   │   │   ├── ApplicationController.js
│   │   │   │   ├── IndexController.js
│   │   │   ├── models
│   │   │   │   └── User.js
│   │   │   ├── routes
│   │   │   │   ├── ApplicationRoute.js
│   │   │   │   ├── IndexRoute.js
│   │   │   ├── templates
│   │   │   │   ├── application.hbs
│   │   │   │   ├── index.hbs
│   │   │   │   ├── partials
│   │   │   │   │   └── header.hbs
│   │   │   ├── vendor
│   │   │   │   ├── ember.js
│   │   │   │   ├── handlebars.js
│   │   │   │   └── jquery.js
│   │   │   └── views
│   │   │       └── IndexView.js
│   ├── site.js
│   └── main.js
├── node_modules
├── package.json
├── test
│   └── api_test.js
│   └── site_test.js

As you can see this directory structure has my Ember site inside lib/public/javascripts and my main Node app is a small little Express application which resides inside the main lib/ folder.

The express configurations are all inside main.js.

// setup =======================================================================
var express    = require('express');
var app        = express();

//express.js configurations=====================================================
app.configure(function() {
  app.use(express.json());
  app.use(express.logger('dev'));
  app.use(express.methodOverride());
  app.use(express.static(__dirname + '/public'));
});

app.set("view options", {layout: false});
app.engine('html', cons.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

// routes ======================================================================
require('./site.js')(app);
require('./api.js')(app);

// listen (start app) =========================================================
console.log("The application is running on port 5170");
app.listen(5170);

Express is very nice, it’s got very good documentation and is really easy to setup. One of the important configurations is setting up the public folder to serve your Ember site.

app.use(express.static(__dirname + '/public'));

This tells Express where your static public folder is. Also another important configuration is loading your routes. These routes act as your REST API for the Ember site.

// routes ======================================================================
require('./site.js')(app);
require('./api.js')(app);

An example of what goes in the api.js file for your routes. (keep in mind the db configurations are in another file config/database.js) If you want to see how to do this with a similiar setup you can look at another app of mine called Snozzberry


module.exports = function(app) {
  //url: /users
  app.get('users', function(request, response) {
    db.collection('users', function(err, collection) {
      collection.find().toArray(function(err, items) {
        response.send(items);
      });
    });
  });

  //url: /users/:id
  app.get('users/:id', function(request, response) {
    var id = request.params.id
    db.collection('users', function(err, collection) {
      collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
        response.send(item)
      });
    });
  });
};

Now once that is in place the bin/app file which is just a script, you can use that with Node to start your REST API. In a console window, you just type

$ node bin/app
The application is running on port 5170

That bin/app file looks like this:

#!/usr/bin/env node

// setup =======================================================================
"use strict";
var path = require('path');
var fs   = require('fs');
var lib  = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');

// main entry point for app ====================================================
require(lib+'/main.js');

You can now start your web browser. Go to http://localhost:5170 and because you have a index.html file in your public/ folder, your Ember site should now launch.

The next trick lets Ember Tools automatically reload the application.js (which is the compiled version) build every time a edit is made inside your Ember site.

You have to open another console window, go to the project root directory and type: e

$ ember build -w

Pretty sweet! If you run into any problems with ember tools while it’s watching for changes. Make sure you have the newest version of Node installed. That might fix it.

Conclusion

Well thats my version of running Ember with a Node.js REST API. There are lots of different ways to doing it. If you need any help or have any questions please email me or hit me up on twitter.

Keep in mind the other interesting part is it lets you easily package up your web application into a npm module if you decide you want to do that.

The End