Category: code

node.js, the morning after

Follow up post to Getting started with node.js covering the basic node app setup (package.json), npm package manager and the connect and express frameworks.

package.json

This file, located on the root of every node project, describes the basic configuration of your app. Mainly in contains metadata describing the app itself. It also details the package dependencies needed for the project.

{
    "name": "myApp",
    "author": "omarrr",
    "description": "my first node app",
    "version": "0.0.1",
    "dependencies": {
        "connect": "2.3.6",
        "express": "3.0.0beta5"
        },
    "engine": "0.8.1"
}

where “engine” describes the version of node this app is running under.

npm

npm (node package manager) comes pre-bundled with node, it installs packages and manages dependencies

npm is to node what rvm is to Ruby.

npm install [package]

Install the dependencies in the local node_modules folder. npm defaults to always install all packages locally to your current project. You can overwrite this behavior with –global (but it’s probably a good idea not to 🙂

Basic usage

npm install

Will read the package.json file in your app dir and install all its dependencies

npm install package

Will install the package (registered with npm) in your local folder

Connect

Selfdescribed as a “middleware framework for node” (or rather node’s HTTP server), Connect it’s build to easily plugin other middleware and comes itself bundled with a selection of them.

Connect is to node what Rack is to Ruby.

You can install connect by simply running:

$ npm install connect

This will create –if needed– a subfolder in your app folder called “node_modules” where connect can be found (and it’s dependencies under another “node_modules”).

Express

Express is a “fast, unopinionated, minimalist web framework for node”. Express sits on top of Connect to extend it, as Connect sits on top of node’s http.

Express is to node what Sinatra is to Ruby.

You can install express by simply running:

$ npm install express

This will also store the package and its dependencies under the “node_modules” folder.

Creating a fresh Express app

Express can also easyly generate an app skelleton for new express+node projects.

To do this, express must be installed globally:

$ npm install -g express

Once express is globally available it can create the app

$ express myApp

This will create a new folder named “myApp” and create a new node server app that utilizes the Express framework.

Next we need to install all the new project dependencies (listed on the newly created ./myApp/package.json)

$ cd myApp
$ npm install

Now we can run the server

$ node app.js

Getting started with Node.js

Easy as pie install of node.js.

Although Node.js is frequently mentioned as a backend alternative to Ruby on Rails it is neither a language nor a framework. Node is an asynchronous I/O library build on V8 (Google’s open source JavaScript engine). Express.js is a framework built on top of node.js and it’s a better comparison to RoR than node itself.

From Node’s site:

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Installing node (& npm)

Donwload (on Mac get PKM) from http://nodejs.org/#download & double click easy installer 🙂

Testing node

Write a hello world example: ‘hi.js’ (from nodejs)

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Execute

$ node hi.js
Server running at http://127.0.0.1:1337/

Goto http://127.0.0.1:1337/ to check out the results

No markup whatsoever. Inspecting the source code of the page will get simply:

Hello World

Done and done.

REPL

REPL (Read-Eval-Print-Loop) is an interactive shell for node that can be invocated by simply calling node with no app.js to execute. It works just like the debug console in Chrome.

$ node

> 2+3
5
> console.log('hi');
hi
undefined
> ["Hello","Word"].join();
'Hello,Word'
> 

What’s next

Testing express.js, a framework over node, installing brunch, an app assembler and scafolding tool build on top of node, integrating node backend with a front-end MV* framework such as backbone.js, etc, etc, etc…

Book review: Responsive Web Design

‘Responsive Web Design’ is a perfectly succinct and to the point introduction to the topic. It covers both the philosophy behind responsive design, the design principles to make it happen and the actual code to put it all together.

The key learning of this book can be sumarized by the following quote:

So what does it take to create a responsive design? Speaking purely in terms of front-end layout, it takes three core ingredients:

  • A flexible, grid-based layout,
  • Flexible images and media, and
  • Media queries, a module from the CSS3 specification.

Topics

The book covers multiple topics: scalable typography (w/ CSS’s em unit), the math behind adapting a grid-based layout to be flexible, fluid images, how to approach media queries and what are the most useful breakpoints, introduction to device vs display units and the viewport, the “mobile first” philosophy,…

Summary

  • Level: intermediate
  • Who is this book for: mid to senior level developers inexperienced with responsive design/development.
  • Rating: ★★★★ (4/5)

CORS: HTML5 approach to crossdomain policies

Traditionally web browsers restrict loading content to the same origin server. This means that you can’t load content from another domain different than your own. There’s been several ways to solve this problem and HTML5 introduces a new one.

Current support

JS

JS developers have used a workaround consisting in using JSONP (JSON with Padding). Since the same domain restriction don’t apply to dynamically loaded Javascript code, JSONP solves the crossdoamin issue by wrapping the JSON response in a JS function call. This approach assumes the server is ready to deliver JSONP data. JSONP is quite common and jQuery supports it natively.

Flash

This crossdomain policy behavior is well known in Flash as well and developers have been getting around this restricction (also imposed in the Flash player) with the –now famous– crossdomain.xml policy file.

All these approaches require the foreign server to implement a solution on their end (host the crossdomain file or implement JSONP).

HTML5

One of html5 new features allows for a different workaround to crossdomain restrictions that doesn’t involve changing the format of the response but rather the header of it. This means that we can get away without JSONP and utilize JSON or any other format prefered by our app.

CORS

This new feature is called CORS (Cross Origin Resource Sharing) and its intended to prevent crossdomain scripting attacks while still enabling sites to load content from external servers.

It works in two simple steps:

STEP 1: HTTP Request

Besides setting who the host of our request is (http://api.foo.com) we also set who the requester is:

Origin: http://api.origin.com

This Origin header is set by the browser and can’t be controlled by the user, and it’s send along with the full HTTP Request header:

GET /cors HTTP/1.1
Origin: http://api.origin.com
Host: api.foo.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: ...

STEP 2: HTTP Response

If the server accepts crossdomain requests its response will include (besides the requested content) who the response is intended for (http://api.origin.com). All the new HTML5 headers for CORS are prefixed with “Access-Control-“.

Access-Control-Allow-Origin: http://api.origin.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8

SUPPORT

CORS is an HTML5 feature and, therefore, it’s not yet fully implemented across all browsers. Particularly, it’s not supported yet on Opera (desktop or mobile) and supported only partially in IE8 and 9 (using the XDomainRequest object but with some crazy restrictions).

The good news is that jQuery already implements CORS requests (jQuery.support.cors) natively for all browsers that can support it. Additionally there are some plugins in development for IE8 and IE9.

You can check the full support for CORS for more details.

CONCLUSION

Leaving Opera aside and old versions of IE (6 and 7), CORS are pretty well supported and can be reliably used. If you own the infrastructure you can more easily get over the biggest hurdle which is implementing Access-Control headers on the external server (although this will become more and more common, it still isn’t).

Because CORS eliminates the need for JSONP, code can be simpliffied and different response formats can be used again: plain HTML, XML, JSON, etc.

RESOURCES

You can read the w3c definition of CORS or the more readable tutorial at HTML5Rocks.

Introduction to version control with Git and GitHub

In the last year I’ve moved more and more towards Git and since I’ve started using Github I don’t want to go back to old SVN. Git is fast and reliable version control system, and Github is the perfect tool for version control, doing code reviews and managing feature development and hot fixes.

Git

The first reason that made Git so attractive was managing more than one paralel paths of development at once (eg. feature development that needs to happen in paralel with the deployment of hotfixes). With SVN all work not related to the hotfix would have to wait to be committed to the server, or very careful measures would have to be taken to avoid code rollovers. The concept of branches is integral to the way Git works and makes it extremely simple to switch development paths and manage complicated deployments. Also, unlike SVN, Git is fast.

Experimenting

Git branches allow to really quickly archive the current state of the project, change context and start experimenting. If the experiment goes awry it’s a breeze to get back to the original state, if it’s a success it can become the new development branch. Great for big refactoring efforts, experimental features, etc.

Branches also facilitate colaboration among many developers and some successful branching models have been set up to assist big groups to cooperate successfully. We follow this model (or slight variations of it) in many of our projects.

Server-less commits

Cloning a Git repo actually clones the whole project not just the files of the current state of the app, which means that you have a perfect copy and are free of using the server repo. Git is great for offline development since developers can commit files locally, repeatedly, without a server and finally push their work to the repo once online (with the full history of commits).

Github

Github is the perfect companion to Git. Since I have more and more adopted the cloud paradigm. One big advantage of Github is not having to physically clone a repo in order to be able to review code, check the history of a branch, review pull requests, etc. Finally Github is free for Open Source projects which makes it really attractive as a starting point for many.

Link to code

Something I really enjoy about Github is being able to link to sections of code. As simple as this might seem there never has been an easy way to do this.

Pull requests

Instead of blindly merging new code into the repository, developers can submit a pull request, a request to merge their code into the main branch (or trunk, or master) that can be reviewed, commented on and approved. Github can display the pull requests, conversations and resolutions. Pull requests are technically a Git feature, but the way Github handles them makes it pretty awesome to use.

Git Blame

Last feature that I really enjoy is blaming. Blaming allows anyone to determine the author of each line of code in a file. This is another feature that belongs to Git (also to SVN), that is greatly enhanced thanks to Github’s UI.

Resources

The Git Community Book: Freely available online and maintained by the community.

Book. This book has been built by dozens of people in the Git community, and is meant to help you learn how to use Git as quickly and easily as possible.

Pro Git: Published by Apress, the book is free online.

Here you can find the full content of the book, a blog with tips and updates about Git and the book and open source projects related to Git or referenced in the book.