Node.js

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.


Articles on Node.js

Node.js Hello Framework

A far from complete collection of Hello World examples for various Node.js web frameworks.

YSlow.js: Release 0.3.1

Links: readme | package | source | tests

0.3.2

Previous Version

  • 0.3.1
  • 0.3.0
    • Fixing error handling in run. Now passes both error and results to callback. See README examples for details. This update is not backwards compatabile with previous releases.
  • 0.2.1
    • Removing unused dependainces.
  • 0.2.0
    • Top down refactor using updated Phapper.
    • Includes better pathing support for finding included yslow.js.
    • Downloads and install yslow.js if it can't be found, which should never happen.
    • Adding limited support for Windows.
  • 0.1.2
    • Fixing critical issue in NODE_PATH search when working with global installations.
  • 0.1.1
    • Refactored to use Phapper, way cleaner and less code.
    • Refactored tests for change to Phapper.
    • Refactored stubs..
    • Adding functional tests.
  • 0.0.1
    • Initial release.

Phapper.js: Release 0.1.9

Links: readme | package | source | tests

0.1.9

  • Fixing a minor bug with the install script.

Previous Versions

  • 0.1.8
    • Updating PhantomJS version to 1.9.7.
  • 0.1.6
    • Replacing exec-sync with execSync for easier Mac installation.
  • 0.1.5
    • Removing unused dependancies.
  • 0.1.4
    • Fixing small issue with passed in arguments on init.
    • Added ability to pass exec object, see readme examples.
    • Cleaned up tests, added more.
    • Cleaned up make test / npm test.
    • Allowing for passing of cwd to sync function.
  • 0.1.3
    • Adding windows handling and phantomjs version overide.
    • Updating readme.
  • 0.1.2
    • Adding phantomjs install.
    • Adding better phantomjs path support.
  • 0.1.1
    • Refactored to not require JSON stdout parse.
    • Refactored run and runSync return values, see readme.
  • 0.0.1
    • Initial release.

Github Webhooks with git-fish

I wrote git-fish – a Github Webhook listener – to provide a simple and modular method for executing an autodeployment on mervine.net when adding or updating a post. I designed it to as simple and as modular as possible. While written in Node.js, I tend to use it execute simple bash scripts, like the mervine.net deployment script:

#!/bin/bash

cd /home/jmervine/mervine.net
make deploy/soft

With this combination, I can use [Github] as my psudo-CMS, to create and update posts and when I save an addition or change, it becomes visable on the site in seconds (including, updating code and purging cache).

For detailed information on setting up and using git-fish or my other see my git-fish project page.

Enjoy!

HTTPerf.js: Release 0.1.0

Removing runSync. Refactoring run to support sending spawned process SIGINT to capture current report from httperf and exit.

Forking in Node.js / Threading HTTPerf with HTTPerf.js

Occasionally, we want to generate load beyond what a single httperf thread can handle, especially when working in Node.js, where the connection limits can get very high. The code sample below does that, but also serves as an example of how to use the cluster module to fork actions and collect the resulting data. Enjoy!

Simple Timing in Node.js

I just stumbled upon a cool feature of Node.js for adding timing to applications using console.time and console.timeEnd`.

// pointless example that show all parts
console.time('timer');
setTimeout(function() {
    console.timeEnd('timer');
}, 500);

// => timer: 511ms

Note: I've heard (and in somecases proven) that in most cases console. method are not asynchronous (i.e. blocking) and therefore should never be used in production code. Notice that in the above example, console.time and console.timeEnd appear to have about 11ms of overhead on my machine.

NPM Registry's

I'm starting this list with the plan on adding as many as I can find. Please shoot me any known public registry's in the comments below.

http://registry.npmjs.vitecho.com/
http://npm.nodejs.org.au:5984/registry/_design/app/_rewrite (AUS)

Usage:

npm install --registry http://registry.npmjs.vitecho.com/ npm-foo

Published on in Node.js

Jade Bootstrap Layout Template

After using the Express command line generation untility, you get a very basic layout.jade. Here's the standard modifications I make for use with BootstrapCDN.

Pretty Sleep using Node.js

$ node -e 'n=0; setInterval(function(){n++;if(n>=20){console.log(".");process.exit(0);}process.stdout.write(".");},1000);'

Benchmarking with YSlow.js on Node.js

In my last post on this topic (Benchmarking with HTTPerf.js and NodeUnit) I covered benchmarking application render times from the server to first byte. In this post, I'm going cover basic client benchmarking using YSlow and PhantomJS via YSlow.js on Node.js.

Benchmarking with HTTPerf.js and NodeUnit

I covered this in the HTTPerf.js README a bit, but wanted to take a deer look at how I'm using HTTPerf.js to benchmark web applications.

Working with Events and Strings in Node.js

Being new to Node.js, it took me an amazing amount of time to figure out how to assgin event stream chunks (foo.on('data', ...)) to a variable and work with it. An amazing amount of time, because it's actually really easy if you understand callbacks (which I didn't) and because all the examples I could find worked with console.log. In this case, I didn't want to log the result, but pass it, process it, etc. So here's an example from GitMD with some additional comments to help you along the way.

Published on in Node.js

Notes: JavaScript `median(Array)`

function median(values) {
    values.sort( function(a,b) {return a - b;} );
    var half = Math.floor(values.length/2);
    if (values.length % 2) {
        return values[half];
    } else {
        return (values[half-1] + values[half]) / 2.0;
    }
}

Simple Rules for Stable, Performant and Maintainable Apps

Here are some simple and basic rules I've found for building applications that are maintainable and perform well, both in speed and stability. These rules, at one level or another, can apply to smaller modules and libraries, scripts, as well as fully featured large scale applications (both web and otherwise). In this post I will focus more on web applications, since that's where I've spent most of my time. At a higher level, they should apply to almost all areas of software development.

Stubbing Binaries for Testing

Being a Dev Ops guy, I write gems, scripts and hacks that tend to hook in to system binaries. I know, it would probably be better to write C bindings, but heretofore that hasn't been something I really want to tackle. Additionally, I almost always write tests for my stuff. I've come across the problem where my tests pass locally, but not on Travis-CI.

Node.js forever handing via make

Tasks

  • start :: starts application using forever
  • stop :: stops application using forever
  • restart :: restart application using forever

    # This set's your local directory to to your NODE_PATH
    NODE_EXEC    = NODE_PATH=.:$(NODE_PATH)
    
    # This is for local (non `-g`) npm installs.
    # NODE_MODS    = ./node_modules/.bin
    
    # Some good `forever` options.
    FOREVER_OPTS = -p ./logs  \
                    -l server_out.log \
                    -o ./logs/server_out.log \
                    -e ./logs/server_err.log \
                    --append \
                    --plain \
                    --minUptime 1000 \
                    --spinSleepTime 1000
    
    start: setup/dirs
        # starting app in server mode
        $(NODE_EXEC) $(NODE_MODS)/forever $(FOREVER_OPTS) [email protected] server.js
    
    stop:
        # stopping app in server mode
        $(NODE_EXEC) $(NODE_MODS)/forever $(FOREVER_OPTS) [email protected] server.js
    
    restart: setup/dirs
        # restarting app in server mode
        $(NODE_EXEC) $(NODE_MODS)/forever $(FOREVER_OPTS) [email protected] server.js
    
    setup/dirs:
        # creating required directories for `forever`
        mkdir -p logs pids
    

Get the gist.

Installing Node.js from Source

Note: This has been tested on Ubuntu 12.01. It should also work on most CentOS (Redhat) version and Mac's, but I haven't personally tested it.

Copy and save this to a script called something like install_node.sh and run bash install_node.sh. It expects sudo access.

#!/usr/bin/env bash
set -x
cd /tmp
rm -rf node

set -ue
git clone git://github.com/joyent/node.git

cd node
git checkout v0.10.20

./configure --prefix=/usr
make
sudo make install

# vim: ft=sh:

Get the gist.

Clustering in Node.js

I recently had to setup a Node.js application for production deployment... I come from the Ruby world, so I wanted my end product to be something like what you get when using Unicorn. Here's a little walk through.

Published on in Node.js

Hello World: Sinatra vs. Node.js

Sinatra

require 'sinatra'
get '/' do
  "Hello World"
end

Express

var app = require('express');
app.get('/', function(req, res) {
    res.send("Hello World!");
});
app.listen(8000);

Installing Node.js on CentOS

I wrote the following script to install Node.js on CentOS to handle a Rails missing a JavaScript runtime environment error.

#!/usr/bin/env bash
set -ue
sudo echo "Ensure sudo access."
sudo touch /etc/yum.repos.d/naulinux-extras.repo
sudo sh -c "echo '[naulinux-extras]
name=NauLinux Extras
baseurl=http://downloads.naulinux.ru/pub/NauLinux/6.2/\$basearch/Extras/RPMS/
enabled=0
gpgcheck=1
gpgkey=http://downloads.naulinux.ru/pub/NauLinux/RPM-GPG-KEY-linux-ink
' > /etc/yum.repos.d/naulinux-extras.repo"
sudo yum --enablerepo=naulinux-extras install nodejs