node js felix

31
Felix's Node.js Guide About this guide Hi, I am Felix Geisendörfer , an early node.js core contributor and co- founder of transloadit.com . Over the past few months I have given a lot of talks and done a lot of consulting on using node.js. Since I found myself repeating a lot of things over and over, I decided to use some of my recent vacation to start this opinionated and unofficial guide to help people getting started in node.js. Content Node.js Beginner Guide If you are new to node.js, this guide will take you from hello world to deploying your first app. Node.js Style Guide The general JavaScript style I recommend to use with node.js. A lot of this is personal preferences, but hopefully rather consistent. Node.js Community Guide Get to know some of the node.js community and find out where they hang out. Node.js Convincing The Boss Guide Find out where node.js makes sense, and how to get management to see the benefits. More guides are in the works. Feel free to follow the GitHub repository , or have a look at this list of upcoming guides: Node.js Package Guide Learn how to create your own node.js packages and publish them on npm. Node.js Object Oriented Programming Guide My approach to object oriented programming with node.js. Node.js Test Driven Development Guide A beginners guide to test driven development with node.js. Report Issues

Upload: bernardo-oliveira

Post on 06-May-2015

5.191 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Node js felix

Felix's Node.js Guide

About this guide

Hi, I am Felix Geisendörfer, an early node.js core contributor and co-founder of transloadit.com.

Over the past few months I have given a lot of talks and done a lot of consulting on using node.js.

Since I found myself repeating a lot of things over and over, I decided to use some of my recent vacation to start this opinionated and unofficial guide to help people getting started in node.js.

Content

Node.js Beginner Guide If you are new to node.js, this guide will take you from hello world to deploying your first app.

Node.js Style Guide The general JavaScript style I recommend to use with node.js. A lot of this is personal preferences, but hopefully rather consistent.

Node.js Community Guide Get to know some of the node.js community and find out where they hang out.

Node.js Convincing The Boss Guide Find out where node.js makes sense, and how to get management to see the benefits.

More guides are in the works. Feel free to follow the GitHub repository, or have a look at this list of upcoming guides:

Node.js Package Guide Learn how to create your own node.js packages and publish them on npm.

Node.js Object Oriented Programming Guide My approach to object oriented programming with node.js.

Node.js Test Driven Development Guide A beginners guide to test driven development with node.js.

Report Issues

Page 2: Node js felix

If you come across some incorrect information, please open an issue in the issue tracker.

License

I have not decided on a license for this yet. So if you're interested in re-publishing this content in one way or another, please send me an email.

© 2011, Debuggable Limited.

Page 3: Node js felix

« Home / All Guides

Felix's Node.js Beginners Guide • Learning JavaScript

• Hello World Tutorial

o Installation

o The interactive node.js shell

o Your first program

o A hello world http server

• The module system

• Using EventEmitters

• Next Steps

• Debugging node.js apps

o Using console.log()

o Using the node debugger

o Using the WebKit Inspector

• Frameworks

o Express

o fab.js

• Hosting & Deployment

o Quick & Dirty Deployment

o Joyent no.de

There is lots of information about node.js, but given the rapid pace at which it is developing, it can be difficult for beginners to find good, current information on how to get started. This guide aims to provide exactly that, whilst staying updated with the latest stable version of node.js.

This guide has been updated to reflect the latest changes in node 0.4.x, the currently stable branch of node.js.

Learning JavaScript

This guide assumes that you are already familar with JavaScript. If you are not, you should go ahead and read: Eloquent JavaScript, a free online book by Marijn Haverbeke.

Hello World Tutorial

This tutorial guides you through installing node.js, including the creation of a simple hello world http server.

Page 4: Node js felix

Installation

First of all: You should run a *nix operating system in order to use node.js at this point. Linux and OSX are recommended, but you should also be able to use FreeBSD and cygwin (on windows). A full windows port of node.js is in the works, but it is not yet ready for public usage.

The most common way to install node.js is to directly compile it from the downloaded source code. There are also various packages available for different package managers, but since their update frequency varies, I recommend installing from source.

You can get the latest source code from nodejs.org. Use the commands below to download and install v0.4.4:

$ wget http://nodejs.org/dist/node-v0.4.4.tar.gz $ tar -xzf node-v0.4.4.tar.gz $ cd node-v0.4.4.tar.gz $ ./configure $ sudo make install

Node.js itself has no external dependencies except common build tools as well as pythons for the build system itself. On OSX you must install XCode for this to work, and on Ubuntu you probably have to run:

$ apt-get -y install build-essential

The interactive node.js shell

If everything worked, you should be able to invoke the interactive node.js shell like this:

$ node > console.log('Hello World'); Hello World

The interactive shell (also called REPL) is a great place to test simple one liners, and can also be directly embedded into your node.js applications. In order to get out of it, simply press Ctrl + C.

The REPL also comes with many other great features, most importantly tab auto-completion.

Your first program

Writing a node.js program is as simple as creating a new file with a '.js' extension. For example you could create a simple 'hello_world.js' file with the following content:

Page 5: Node js felix

console.log( 'Hello World' );

After you have saved the file, you can execute it from your terminal like so:

$ node hello.js Hello World

A hello world http server

Now printing hello world to a terminal isn't all that exciting. Let's take the next step and write a program that responds to hello world via http. We'll call the file 'hello_http.js' and put the following code into it:

var http = require( 'http' ); var server = http.createServer( function(req, res) { res.writeHead( 200 ); res.end( 'Hello Http' ); }); server.listen( 8080 );

Now lets run this program from the terminal by typing:

$ node hello_http.js

The first thing you'll notice is that this program, unlike our first one, doesn't exit right away. That's because a node program will always run until it's certain that no further events are possible. In this case the open http server is the source of events that will keep things going.

Testing the server is as simple as opening a new browser tab, and navigating to the following url: http://localhost:8080/. As expected, you should see a response that reads: 'Hello Http'.

Alternatively, you could also open up a new terminal and use curl to test your server:

$ curl localhost:8080 Hello Http

Now let's have a closer look at the steps involved in our little program. In the first line, we include the http core module and assign it to a variable called http. You will find more information on this in the next section about the module system.

Next we create a variable called server by calling http.createServer . The argument passed into this call is a closure that is called whenever an http request comes in.

Page 6: Node js felix

Finally we call server.listen(8080) to tell node.js the port on which we want our server to run. If you want to run on port 80, your program needs to be executed as root.

Now when you point your browser to 'localhost:8080', the connection closure is invoked with a req and res object. Thereq is a readable stream that emits 'data' events for each incoming piece of data (like a form submission or file upload). The res object is a writable stream that is used to send data back to the client. In our case we are simply sending a 200 OK header, as well as the body 'Hello Http'.

The module system

In order to structure your program into different files, node.js provides you with a simple module system.

To illustrate the approach, let's create a new file called 'main.js' with the following content:

var hello = require( './hello' ); hello.world();

As you have probably guessed, the require('./hello') is used to import the contents from another JavaScript file. The initial './' indicates that the file is located in the same directory 'main.js'. Also note that you don't have to provide the file extension, as '.js' is assumed by default.

So let's go ahead and create our 'hello.js' file, with the following content:

exports.world = function() { console.log( 'Hello World' ); }

What you notice here, is that we are assigning a property called 'world' to an object called 'exports'. Such an 'exports' object is available in every module, and it is returned whenever the require function is used to include the module. If we now go ahead and run our 'main.js' program, we will see the expected output:

$ node main.js Hello World

At this point it should also be mentioned that many node users are overwriting the exports object directly like so:

Page 7: Node js felix

module.exports = function() { // ... }

As you might have expected, this will directly cause the require function to return the assigned function. This is useful if you're doing object oriented programming, where each file exports the constructor of one class.

The next thing you need to know about the module system is how it deals with require calls that don't include a relative hint about the location of the included file. Take for example:

var http = require( 'http' );

What node.js will do in this case, is to first look if there is a core module named http, and since that's the case, return that directly. But what about non-core modules, such as 'mysql'?

var mysql = require( 'mysql' );

In this case node.js will walk up the directory tree, moving through each parent directory in turn, checking in each to see if there is a folder called 'node_modules'. If such a folder is found, node.js will look into this folder for a file called 'mysql.js'. If no matching file is found and the directory root '/' is reached, node.js will give up and throw an exception.

At this point node.js also considers an additional, mutable list of alternative include directories which are accessible through the require.paths array. However, there is intense debate about removing this feature, so you are probably better off ignoring it.

Last but not least, node.js also lets you create an 'index.js' file, which indicates the main include file for a directory. So if you call require('./foo') , both a 'foo.js' file as well as an 'foo/index.js' file will be considered, this goes for non-relative includes as well.

Using EventEmitters

Node.js implements the observer pattern using a class called EventEmitter. Whenever there is an object that represents the source of several kinds of events, node.js usually makes the underlaying class inherit from EventEmitter.

Using EventEmitter's is pretty straight-forward. You can listen to a specific event by calling the 'on()' function on your object, providing

Page 8: Node js felix

the name of the event, as well as a callback closure as the parameters. For example:

var data = '' ; req .on( 'data' , function(chunk) { data += chunk; }) .on( 'end' , function() { console.log( 'POST data: %s' , data); })

As you can see, the on() function also returns a reference to the object it belongs to, allowing you to chain several of such event listeners.

If you're only interested in the first occurrence of an event, you can use the once() function instead.

Finally, you can remove event listeners by using the removeListener function. Please note that the argument to this function is a reference to the callback you are trying to remove, not the name of the event:

var onData = function(chunk) { console.log(chunk); req.removeListener(onData); } req.on( 'data' , onData);

The example above is essentially identical to the once() function.

Next Steps

Now that you know your node.js basics, you're probably best off by writing a few little programs yourself. The best place to start out is node's api documentation, using it as a source of inspiration for something you want to play with.

Debugging node.js apps

There are many ways to debug your node.js based applications. Personally I prefer to do as little debugging as possible, so I strictly follow the advice of the test driven development guide.

However, if you find yourself in a situation where you need to locate a tricky bug in an existing applications, here are a few approaches that can help.

Page 9: Node js felix

Using console.log()

The easiest way to understand a problem is by inspecting objects using console.log(). You can either directly pass in objects as parameters:

var foo = {bar: 'foobar' }; console.log(foo);

Or you can use its sprintf()-like capabilities to format your debug output:

var foo = {bar: 'foobar' }; console.log( 'Hello %s, this is my object: %j' , 'World' , foo);

Using the node debugger

If console.log() isn't your thing, or you think your problem can be better analyzed using breakpoints, the node's built-in debugger is a great choice. You can invoke the debugger by simply calling:

$ node.js debug my_file.js

Work in progress, please come back later ...

Using the WebKit Inspector

Work in progress, please come back later ...

Frameworks

If you're new to node.js, you might not want to re-invent the wheel when it comes to parsing POST requests, routing urls or rendering views. In this case, you probably want to use one of the popular web frameworks. This section gives you a quick overview over the popular choices, and my opinionated take on them.

Express

At this point express is probably the go-to framework for most node.js developers. It's relatively mature, and includes theconnect (think rack) middleware layer. Included in the package are routing, configuration, a template engine, POST parsing and many other features.

While express is a solid framework, it's currently addressing a much smaller scope than fullstack frameworks like Rails, CakePHP or Django. It's more comparable to Sinatra, and unfortunately doesn't really make a big effort to differentiate itself from its Ruby roots into

Page 10: Node js felix

something that feels natural in JavaScript. Anyhow, short of writing your own framework, it's certainly a great choice at this point.

fab.js

You think you know JavaScript? Think again. Originally inspired by jQuery's chaining, fab.js has taken a very unconventional approach of twisting JavaScript beyond most peoples brain capacity. Each function returns another function, eliminating the need for method names altogether, while giving the resulting code a lisp-esque look & feel.

At this point I don't consider fab.js production-ready, but if you're still exploring the world of node.js, you should absolutely try it out at least once. If nothing else, fab.js shows the world that JavaScript doesn't have to copy Ruby, Python or PHP when it comes to web frameworks, and can go its own unique ways.

Hosting & Deployment

Quick & Dirty Deployment

If you have just written your first node.js application, and you want to get it running as fast as possible, this is how to do it:

1. Copy your program to the server you want to run it on. If you're using git, this probably just means to clone the repository from another server or service like GitHub.

2. Assuming your project contains a 'server.js' file, navigate to the directory containing it, then type:

3. $ screen 4. $ node server.js

This invokes your 'server.js' program inside a so called screen session. Screen is a tool that provides you with a shell that remains its state, even when you close the terminal app you used to login to your server.

So you can now safely close your terminal app, and your 'server.js' will continue running. If you want to monitor it, you can log into your server again, and type:

$ screen -r

This will reconnect you to the backgrounded shell running your program.

However, this approach is only recommended for experimental deployments. If your node applications crashes at some point, screen

Page 11: Node js felix

will not try to restart it, so don't use this method for production applications.

Joyent no.de

Work in progress, please come back later ...

© 2011, Debuggable Limited.

Page 12: Node js felix

« Home / All Guides

Felix's Node.js Style Guide • Tabs vs Spaces • Semicolons • Editors • Trailing whitespace • Line length • Quotes • Braces • Variable declarations • Variable and property names • Class names • Constants • Object / Array creation • Equality operator • Extending prototypes • Conditions • Function length • Return statements • Named closures • Nested Closures • Callbacks • Object.freeze, Object.preventExtensions, Object.seal, with, eval • Getters and setters • EventEmitters • Inheritance / Object oriented programming

There is no official document that governs the style of node.js applications. This guide is my opinionated attempt to bring you a good set of instructions that will allow you to create beautiful and consistent software.

This guide assumes that you are only targeting node.js. If your code also needs to run in the browser or other environments, please ignore some of it.

Please also note that node.js, as well as various packages for it, have their own slightly different styles. So if you're interested in contributing to those, play by their rules.

Tabs vs Spaces

Page 13: Node js felix

Let's start with the religious problems first. Our benevolent dictator has chosen 2 space indention for the node core, so you would do well to follow his choice.

Semicolons

There are rebellious forces that try to steal your semicolons from you. But make no mistake, our traditional culture is stillwell and truly alive. So follow the community, and use those semicolons!

Editors

You can use any editor. However, having support for JS syntax highlighting and executing the currently open file with node.js will come in very handy. While vim may not help you to impress the ladies, it will please our BDFL and your grandpa will also approve.

I'm typing this document in Notes on my iPad, but that's because I'm on a beach in Thailand. It's likely that your own work environment will impact your choice of editor as well.

Trailing whitespace

Just like you brush your teeth after every meal, you clean up any trailing whitespace in your JavaScript files before committing. Otherwise the rotten smell of careless neglect will eventually drive away contributors and/or co-workers.

Line length

Limit your lines to 80 characters. Yes, screens have gotten much bigger over the last few years, but your brain hasn't. Use the additional room for split screen, your editor supports that, right?

Quotes

Use single quotes, unless you are writing JSON.

Right:

var foo = 'bar' ;

Wrong:

var foo = "bar" ;

Page 14: Node js felix

Braces

Your opening braces go on the same line as the statement.

Right:

if ( true) { console.log( 'winning' ); }

Wrong:

if ( true) { console.log( 'losing' ); }

Also, notice the use of whitespace before and after the condition statement.

Variable declarations

Declare one variable per var statement, it makes it easier to re-order the lines. Ignore Crockford on this, and put those declarations wherever they make sense.

Right:

var keys = [ 'foo' , 'bar' ]; var values = [ 23, 42]; var object = {}; while ( items.length) { var key = keys.pop(); object[key] = values.pop(); }

Wrong:

var keys = [ 'foo' , 'bar' ], values = [ 23, 42], object = {}, key; while ( items.length) { key = keys.pop(); object[key] = values.pop(); }

Variable and property names

Page 15: Node js felix

Variables and properties should use lower camel case capitalization. They should also be descriptive. Single character variables and uncommon abbreviations should generally be avoided.

Right:

var adminUser = db.query( 'SELECT * FROM users ...' );

Wrong:

var admin_user = d.query( 'SELECT * FROM users ...' );

Class names

Class names should be capitalized using upper camel case.

Right:

function BankAccount() { }

Wrong:

function bank_Account() { }

Constants

Constants should be declared as regular variables or static class properties, using all uppercase letters.

Node.js / V8 actually supports mozilla's const extension, but unfortunately that cannot be applied to class members, nor is it part of any ECMA standard.

Right:

var SECOND = 1 * 1000 ; function File() { } File.FULL_PERMISSIONS = 0777 ;

Wrong:

const SECOND = 1 * 1000 ; function File() { } File.fullPermissions = 0777 ;

Page 16: Node js felix

Object / Array creation

Use trailing commas and put short declarations on a single line. Only quote keys when your interpreter complains:

Right:

var a = [ 'hello' , 'world' ]; var b = { good: 'code' , 'is generally' : 'pretty' , };

Wrong:

var a = [ 'hello' , 'world' ]; var b = { "good" : 'code' , is generally: 'pretty' };

Equality operator

Programming is not about remembering stupid rules. Use the triple equality operator as it will work just as expected.

Right:

var a = 0; if (a === '' ) { console.log( 'winning' ); }

Wrong:

var a = 0; if (a == '' ) { console.log( 'losing' ); }

Extending prototypes

Do not extend the prototypes of any objects, especially native ones. There is a special place in hell waiting for you if you don't obey this rule.

Right:

var a = []; if (! a.length) {

Page 17: Node js felix

console.log( 'winning' ); }

Wrong:

Array.prototype.empty = function() { return ! this.length; } var a = []; if ( a.empty()) { console.log( 'losing' ); }

Conditions

Any non-trivial conditions should be assigned to a descriptive variable:

Right:

var isAuthorized = ( user.isAdmin() || user.isModerator()); if (isAuthorized) { console.log( 'winning' ); }

Wrong:

if ( user.isAdmin() || user.isModerator()) { console.log( 'losing' ); }

Function length

Keep your functions short. A good function fits on a slide that the people in the last row of a big room can comfortably read. So don't count on them having perfect vision and limit yourself to ~10 lines of code per function.

Return statements

To avoid deep nesting of if-statements, always return a functions value as early as possible.

Right:

function isPercentage(val) { if (val < 0) { return false; } if (val > 100 ) { return false;

Page 18: Node js felix

} return true; }

Wrong:

function isPercentage(val) { if (val >= 0) { if (val < 100 ) { return true; } else { return false; } } else { return false; } }

Or for this particular example it may also be fine to shorten things even further:

function isPercentage(val) { var isInRange = (val >= 0 && val <= 100 ); return isInRange; }

Named closures

Feel free to give your closures a name. It shows that you care about them, and will produce better stack traces:

Right:

req.on( 'end' , function onEnd() { console.log( 'winning' ); });

Wrong:

req.on( 'end' , function() { console.log( 'losing' ); });

Nested Closures

Use closures, but don't nest them. Otherwise your code will become a mess.

Right:

setTimeout( function() { client.connect(afterConnect);

Page 19: Node js felix

}, 1000 ); function afterConnect() { console.log( 'winning' ); }

Wrong:

setTimeout( function() { client.connect( function() { console.log( 'losing' ); }); }, 1000 );

Callbacks

Since node is all about non-blocking I/O, functions generally return their results using callbacks. The convention used by the node core is to reserve the first parameter of any callback for an optional error object.

You should use the same approach for your own callbacks.

Object.freeze, Object.preventExtensions, Object.seal, with, eval

Crazy shit that you will probably never need. Stay away from it.

Getters and setters

Do not use setters, they cause more problems for people who try to use your software than they can solve.

Feel free to use getters that are free from side effects, like providing a length property for a collection class.

EventEmitters

Node.js ships with a simple EventEmitter class that can be included from the 'events' module:

var EventEmitter = require( 'events' ).EventEmitter;

When creating complex classes, it is common to inherit from this EventEmitter class to emit events. This is basically a simple implementation of the Observer pattern.

However, I strongly recommend that you never listen to the events of your own class from within it. It isn't natural for an object to observe

Page 20: Node js felix

itself. It often leads to undesirable exposure to implementation details, and makes your code more difficult to follow.

Inheritance / Object oriented programming

Inheritance and object oriented programming are subjects by themselves. If you're interested in following this popular programming model, please read my Object oriented programming guide.

© 2011, Debuggable Limited.

Page 21: Node js felix

« Home / All Guides

Felix's Node.js Community Guide • IRC

• Google Groups

• Twitter

• Community Members

o Ryan Dahl

o Isaac Schlueter

o Bert Belder

o TJ Holowaychuk

o Tim Caswell

o Felix Geisendörfer

o Mikeal Rogers

o Alexis Sellier

o Jeremy Ashkenas

o Jed Schmidt

o Marak Squires

o Peteris Krumins

o James Halliday

o Your name here

If you have just read the Beginner's Guide, and you are interested in becoming more involved with the node.js community, this guide is for you.

IRC

IRC is a great place to discuss the virtues of vim vs. emacs, as well as getting support and interaction from people within the node.js community.

The official irc channel for node.js is located on chat.freenode.net and named '#node.js' (yes, the dot is part of the name). There are usually ~500 people in there these days.

If you have a question, just go ahead and ask it. Depending on who's awake and paying attention, you often get great replies right away. Otherwise just stick around and wait for an hour or so. After that it's ok to ask your question again, in case you think it went by unnoticed.

Page 22: Node js felix

Oh, and you should always try to find your answer on the web first, but you know that, right?

Google Groups

A lot of discussion around node.js takes place via google group mailing lists. The two official lists are:

nodejs

The 'nodejs' list is meant for general node.js questions and

discussions. So generally that's the one you want to use.

nodejs-dev

If you have found a bug in node.js, or want to get involved in

discussing features & development, feel free to participate in the

'nodejs-dev' mailing list. It's generally less noisy, and most of the

core contributors follow it.

Twitter

Since twitter cuts off tag names when it sees a dot character, many people use the tag '#nodejs' to highlight node.js related content on twitter. You can find the current stream of tweets via twitter's search function:

http://search.twitter.com/search?q=%23nodejs%20OR%20node.js

Since not everybody is tagging their content, the above query also includes results for the term 'node.js' itself.

Community Members

If you are curious about the people driving the node.js development & ecosystem, here is a list of a few people whose names you should know.

Ryan Dahl

Ryan is the creator, maintainer and BDFL of node.js. This means any commits that go into node.js are reviewed by him, and he's the only one who directly pushes to the node repository.

While Ryan will generally try to respond to questions on the mailing list and IRC, he's a very busy guy. So don't be upset if he doesn't answer

Page 23: Node js felix

your direct questions right away, there are usually other people around who can help as well.

Ryan is currently working for Joyent, a company that provides great heroku-style node.js hosting, and is the official corporate sponsor for node.js.

• IRC Nick: ryah • Twitter: @ryah • GitHub: ry • Blog: blog.nodejs.org • Where: San Fransico, USA

Isaac Schlueter

Isaac is the author of npm, the de-facto package manager used by the node.js community. He also works for Joyent and is a big contributor to the node.js core as well. In his spare time he is trying to liberate the JavaScript community fromsemicolon slavery.

• IRC Nick: isaacs • Twitter: @izs • GitHub: isaacs • Blog: blog.izs.me • Where: San Fransico, USA

Bert Belder

Bert is the main developer working on windows support for node, and also one of the biggest overall contributors to the project.

• IRC Nick: piscisaureus • Twitter: @piscisaureus • GitHub: piscisaureus • Where: Netherlands

TJ Holowaychuk

TJ is the author of express, jade and many other popular node.js libraries.

• Twitter: @tjholowaychuk • GitHub: visionmedia • Blog: tjholowaychuk.com • Where: Victoria, BC, Canada

Page 24: Node js felix

Tim Caswell

Tim is the original author of connect, and has been contributing to node.js since the early days. He currently works for HP (formerly Palm), and is also known for the collaborative blog howtonode.org.

• IRC Nick: creationix • Twitter: @creationix • GitHub: creationix • Blog: howtonode.org • Where: San Fransico, USA

Felix Geisendörfer

Yours truly, who is very active in the node.js core development, and works on projects such as formidable, mysql and this very guide. Besides node core development, I'm also the co-founder of a node.js startup providing file uploading & video encoding as a service called transloadit.com.

• IRC Nick: felixge • Twitter: @felixge • GitHub: felixge • Blog: debuggable.com/blog • Where: Berlin, Germany

Mikeal Rogers

Mikeal is the author of request, and is very active in the development of node.js, as well as the community.

• IRC Nick: mikeal • Twitter: @mikeal • GitHub: mikeal • Blog: mikealrogers.com • Where: San Fransico, USA

Alexis Sellier

Alexis is a JavaScript mastermind who is responsible for projects such as less.js, vows and many others.

• IRC Nick: cloudhead • Twitter: @cloudhead • GitHub: cloudhead • Blog: cloudhead.io

Page 25: Node js felix

• Where: Montreal, QC, Canada

Jeremy Ashkenas

Jeremy is the author of CoffeeScript, underscore, backbone, docco and many other popular node.js / JavaScript libraries. He is also running a node.js startup called DocumentCloud.

• IRC Nick: jashkenas • Twitter: @jashkenas • GitHub: jashkenas, documentcloud • Where: New York City, USA

Jed Schmidt

Jed is a japanese translator who moonlights as a JavaScript ninja. His node.js framework fab.js takes a radical new approach to structuring your JS code, and includes all kinds of surprising aspects, exceeding most people's understanding of JavaScript by far.

• IRC Nick: jedschmidt • Twitter: @jedschmidt • GitHub: jed • Blog: jedschmidt.com • Where: Tokyo, Japan

Marak Squires

Marak who goes by the alias Jim Bastard, is mostly known for pumping out dozens of node.js libraries per month, an ability only exceeded by his artful use of profanity and trolling people. Don't get upset if he rubs you the wrong way, he's a nice guy, but you just shouldn't challenge him to a Monkey Island style sword duel.

• IRC Nick: jimbastard • Twitter: @maraksquires • GitHub: marak • Blog: blog.nodejitsu.com • Where: New York City, USA

Peteris Krumins

Some of you may know Peter from his popular blog catomat.net. Together with James Halliday, he has recently started a node.js startup called browserling, which has also led to tons of open source modules from the two of them.

Page 26: Node js felix

• IRC Nick: pkrumins • Twitter: @pkrumins • GitHub: pkrumins • Blog: catomat.net • Where: Riga, Latvia

James Halliday

James is the author of many popular node.js libraries, such as dnode, optimist and browserify. He is also known for drawing cute robots for browserling which he runs with Peteris Krumins.

• IRC Nick: substack • Twitter: @substack • GitHub: substack • Blog: substack.net • Where: Oakland, California, USA

Your name here

This list is by no means exhaustive and for most parts in random order. My goal is to keep this list short enough so it doesn't become a list of all node.js users, but there are probably a few important names that I forgot. So if you would like to see your name here as well, just email me.

© 2011, Debuggable Limited.

Page 27: Node js felix

« Home / All Guides

Felix's Node.js Convincing the boss guide • Bad Use Cases

o CPU heavy apps

o Simple CRUD / HTML apps

o NoSQL + Node.js + Buzzword Bullshit

• Good Use Cases

o JSON APIs

o Single page apps

o Shelling out to unix tools

o Streaming data

o Soft Realtime Applications

• Convincing the boss

o Building a prototype

o Finding developers

o Vibrant community

o Performance

o Corporate Backing

• Convincing a client

Now that you're all hyped up about using node.js, it's time to convince your boss. Well, maybe. I have had the pleasure ofconsulting for different businesses on whether node.js is the right technology, and sometimes the answer is simply no.

So this guide is my opinionated collection of advice for those of you that want to explore whether node.js makes sense for their business, and if so, how to convince the management.

Bad Use Cases

CPU heavy apps

Even though I love node.js, there are several use cases where it simply doesn't make sense. The most obvious such case is apps that are very heavy on CPU usage, and very light on actual I/O. So if you're planning to write video encoding software, artificial intelligence or similar CPU hungry software, please do not use node.js. While you can twist and bend things quite a bit, you'll probably get better results with C or C++.

Page 28: Node js felix

That being said, node.js allows you to easily write C++ addons, so you could certainly use it as a scripting engine on top of your super-secret algorithms.

Simple CRUD / HTML apps

While node.js will eventually be a fun tool for writing all kinds of web applications, you shouldn't expect it to provide you with more benefits than PHP, Ruby or Python at this point. Yes, your app might end up slightly more scalable, but no - your app will not magically get more traffic just because you write it in node.js.

The truth is that while we are starting to see good frameworks for node.js, there is nothing as powerful as Rails, CakePHP or Django on the scene yet. If most of your app is simply rendering HTML based on some database, using node.js will not provide many tangible business benefits yet.

NoSQL + Node.js + Buzzword Bullshit

If the architecture for your next apps reads like the cookbook of NoSQL ingredients, please pause for a second and read this.

Yes, Redis, CouchDB, MongoDB, Riak, Casandra, etc. all look really tempting, but so did that red apple Eve couldn't resist. If you're already taking a technological risk with using node.js, you shouldn't multiply it with more technology you probably don't fully understand yet.

Sure, there are legitimate use cases for choosing a document oriented database. But if you are trying to build a business on top of your software, sticking to conservative database technology (like postgres or mysql) might just outweigh the benefits of satisfying your inner nerd and impressing your friends.

Good Use Cases

JSON APIs

Building light-weight REST / JSON api's is something where node.js really shines. Its non-blocking I/O model combined with JavaScript make it a great choice for wrapping other data sources such as databases or web services and exposing them via a JSON interface.

Page 29: Node js felix

Single page apps

If you are planning to write an AJAX heavy single page app (think gmail), node.js is a great fit as well. The ability to process many requests / seconds with low response times, as well as sharing things like validation code between the client and server make it a great choice for modern web applications that do lots of processing on the client.

Shelling out to unix tools

With node.js still being young, it's tempting to re-invent all kinds of software for it. However, an even better approach is tapping into the vast universe of existing command line tools. Node's ability to spawn thousands of child processes and treating their outputs as a stream makes it an ideal choice for those seeking to leverage existing software.

Streaming data

Traditional web stacks often treat http requests and responses as atomic events. However, the truth is that they are streams, and many cool node.js applications can be built to take advantage of this fact. One great example is parsing file uploads in real time, as well as building proxies between different data layers.

Soft Realtime Applications

Another great aspect of node.js is the ease at which you can develop soft real time systems. By that I mean stuff like twitter, chat software, sport bets or interfaces to instant messaging networks.

But please be careful here, since JavaScript is a dynamic / garbage collected language, your response times may sometimes vary depending on how often and long the garbage collection kicks in (at which point your program is stopped). So don't try to build hard realtime systems in node, that require consistent response times. Erlang is probably a better choice for these kinds of applications.

Convincing the boss

Once you have determined that your use case is a good fit for node.js, it's time to convince your boss or management of giving it a go.

Page 30: Node js felix

Building a prototype

The best way to put your foot into the door, is to suggest taking a week to build a simple prototype of a certain part of the application you have in mind. It's usually easy to get management to agree to that, since they don't have to make a long term commitment yet.

After you've got the approval, it's usually easy to get a basic system up and running, which will provide you with much more hard data and evidence of the benefits of node.js.

Finding developers

Think of JavaScript whatever you want, but at this point it's becoming the lingua franca of computer programming. Pretty much every personal computer has one or more JavaScript interpreters (browsers) installed, which means it's almost impossible for most web developers to not learn it at some point in their career.

This means that you get a huge and diverse pool of people you can hire, and you probably already have plenty of talent in your own company. So if you're working for a growing company, this is a strong argument favouring node.js.

Vibrant community

At this point the node.js community is growing at an insane pace, attracting some of the smartest developers in the industry. This also means that the node ecosystem is growing every day, and it's also easy to get free and commercial support from various sources.

Performance

This argument has to be carefully played, but if performance is a critical aspect of your application, node.js has lots to offer. With five companies (Mozilla, Google, Apple, Microsoft, Opera) competing over the best JavaScript implementation, node's underlaying interpreter (Google's v8) has become insanely fast, and getting better every day.

Combining this with node's radical model of non-blocking I/O, you have to try very hard to create a sluggish application. Most node apps are easily capable of handling thousands of concurrent connections, on what could be considered moderate hardware by any standards.

Page 31: Node js felix

Corporate Backing

One of the risks with using a young open source project is the lack of longterm commitment by its authors. This isn't the case with node.js. Node is currently sponsored by Joyent, who has hired Ryan Dahl and several other core contributors, so there is a real economic force backing the future development of the project.

Amongst other things, this has already given companies like Yahoo! and HP (formerly Palm) enough confidence to build their next generation products on node.js, so your boss can certainly relax by reading their reassuring testimonials.

Convincing a client

If you're a freelancer or small company doing contract work, convincing a client to use node.js might be a different story. After all they are usually very dependent on your judgement, as well as continuous support for the software you create for them.

My advice here is to be a little more conservative, and double check if node is a good fit. If it is, make sure that you have the resources and time to support the application in the future. The node.js team is releasing new versions at a rapid pace, and so you should expect a little work every 3-6 months to update to the latest version.

© 2011, Debuggable Limited.