DailyJS

DailyJS

The JavaScript blog.


Tagfibers
Featured

templating node modules async fibers images thumbnails jade

Node Roundup: 0.6.15, node-inherit, Synchronize.js, jaded

Posted on .

You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.6.15

Node 0.6.15 is out. It includes npm 1.1.16, and some platform-specific bug fixes for Windows and Mac OS.

Thumbbot

Thumbbot (GitHub: vdemedes / thumbbot, License: MIT, npm: thumbbot) by Vadim Demedes is a thumbnail generator API built with PhantomJS, ImageMagick, and ffmpeg.

The Thumbbot class is instantiated with a source and output file:

bot = new Thumbbot 'video.mp4', 'video_thumb.png'  
bot.set width: 200, height: 150  
bot.set position: '00:05:04'  
bot.snap (err) ->  
    # done

The author has included Mocha tests, and various output formats are supported (png, jpg, gif).

node-inherit

node-inherit (License: MIT, npm: inherit) by Dmitry Filatov adds some sugar to help with class-like declarations, constructors, super calls, and static methods.

An inherited class looks like this:

var B = inherit(A, {  
    getProperty: function() {
      return this.property + ' of instanceB';
    },

    getType: function() {
      return this.__base() + 'B';
    }
  },

  staticMethod: function() {
    return this.__base() + ' of staticB';
  }
});

This example assumes a class called A -- notice how the getType method can access A's getType using this.__base. The full example can be viewed in the project's readme.

Dmitry has included some Nodeunit tests that also demonstrate the main features of the library.

Synchronize.js

Synchronize.js (GitHub: alexeypetrushin / synchronize, License: MIT, npm: synchronize) by Alexey Petrushin is another library that's built on fibers to attempt to "flatten" all of those pesky callbacks people like to talk about on Hacker News.

Existing methods can be wrapped with the sync method provided by the library:

var sync = require('synchronize')  
  , fs = require('fs');

fs.readFile_ = sync(fs.readFile);

sync.fiber(function() {  
  var data = fs.readFile_(__filename, 'utf8');
  console.log(data);

  try {
    data = fs.readFile_('invalid', 'utf8');
  } catch (err) {
    console.log(err);
  }
});

Asynchronous methods can be used in a synchronous fashion within the sync.fiber callback. Wrapped functions will behave as if return and throw were called synchronously. The author has written Mocha tests, but the library itself is fairly small so it's not too hard to figure out how it uses fibers to wrap functions: synchronize.js.

jaded

jaded (License: MIT, npm: jaded) from Fractal is an alternate command-line interface for Jade that includes AMD support:

  Usage: jaded [options]

  Options:

    -h, --help            output usage information
    -V, --version         output the version number
    -i --input [folder]   Specify input folder
    -o --output [folder]  Specify output folder
    -d --development      Beautify output and insert line numbers
    -a --amd              Wrap output in AMD closure

Featured

frameworks node modules async fibers

Node Roundup: Gumroad, Functools, Asyncblock, Geddy, Lemmy

Posted on .

 Gumroad

Gumroad logo

Gumroad is a new payment service aimed at digital goods sales that works in over 190 countries. As someone who builds small web applications with subscription fees, I can honestly say that receiving payments is the least fun part of development. It's fun getting paid, but dealing with payment provider APIs can be stressful to say the least. So I read with interest when Vadim Demedes sent us his Node Gumroad client (License: MIT, GitHub: vdemedes / node-gumroad, npm: gumroad).

The client is a class that is instantiated with a Gumroad username and password. After calling an authentication method, item links can be created and managed. For more about Gumroad's links, take a look at How does Gumroad work?

Functools

Functools (License: WTFPL, GitHub: azer / functools, npm: functools) by E. Azer Koçulu has continued to evolve since we featured it last year. Using languages like Clojure and Python for inspiration, Azer has created a small API of familiar flow control functionality. A compose method can be used to call functions in sequence, and asynchronous functions are also supported. There's also a curry method.

In Avoiding Nested Callbacks in JavaScript, the author discusses Functools, along with more detailed examples than supplied in the README.

Asyncblock

Asyncblock (License: MIT, GitHub: scriby / asyncblock, npm: asyncblock) is another flow control related library that we've previously featured on DailyJS. Now version 2.0 has been released, which includes on-the-fly source transformation:

Note that when V8 supports generators, which is currently planned, the source transformation functionality of asyncblock will be able to transform most of the asyncblock code to be based on generators instead of fibers with no change to the original source. This helps reduce risk as it provides a path forward for asyncblock even if support for fibers became impossible in the future.

The examples in the README show how using asyncblock with source transformation can result in very succinct code.

GeddyJS

Meanwhile, Daniel Erickson let us know via Twitter that GeddyJS (License: Apache 2, GitHub: mde / geddy, npm: geddy) 0.3 is out. This Node web framework now has a new Bootstrap website, compete with a detailed tutorial and a list of the major features.

If you're new to Geddy, it's a full stack framework. Pretty much everything you need to build a web app is included. If you've seen Geddy before, then version 0.3 seems to have changed a lot since the 0.1 days. The only parts of the API that seem to have remained the same are models.

Lemmy

Lemmy is an Express boilerplate generator inspired by Motörhead's Lemmy. And why not? There was an Amiga Motörhead game in the early 90s, so why not an Express generator? Anyway, it can be used to create a JavaScript or CoffeeScript application with Mocha tests.

Lemmy uses commands to generate lots of useful stubs, like middleware, routes, and models. And the author writes a mean README.

Featured

node modules backbone.js fibers

Node Roundup: 0.6.10, 0.7.3, Backbone.IO, Notes

Posted on .

Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

0.6.10, 0.7.3

Node 0.6.10 was released last week. Of interest to Windows users is the following:

  • Add npm msysgit bash shim to msi installer
  • dgram: Implement udp multicast methods on Windows

Node 0.7.3 has also been released. This reverts support for isolates:

It was decided that the performance benefits that isolates offer (faster spin-up times for worker processes, faster inter-worker communication, possibly a lower memory footprint) are not actual bottlenecks for most people and do not outweigh the potential stability issues and intrusive changes to the code base that first-class support for isolates requires.

Ben Noordhuis finishes the commit message with "Good bye, isolates. We hardly knew ye". I couldn't find any discussions about this in the nodejs-dev group, but I noticed David Herron mention it here: Good bye isolates, Node.js hardly knew ye.

Backbone.IO

Backbone.IO (License: MIT, npm: backbone.io) by Scott Nelson is a Backbone.js module that can synchronise multiple clients. When a model is synced, the server-side code will trigger events on collections across multiple clients.

The server-side code uses a Connect-inspired middleware API. Notice the familiar signature:

var backend = backboneio.createBackend();

backend.use(function(req, res, next) {  
    console.log(req.backend);
    console.log(req.method);
    console.log(JSON.stringify(req.model));
    next();
});

backend.use(backboneio.middleware.memoryStore());  

Scott has included tests as well, which are built using Mocha and Sinon.

Notes

Notes by Oleg Podsechin is an example app built using his Common Node and Mongo Sync libraries. This is an effort to bring traditional declarative synchronous code to Node through node-fibers.

Here's a taster:

// Get an array of notes
mongo.db('notes').getCollection('notes').find().toArray();

// Save a note
mongo.db('notes').getCollection('notes').save({ name: request.params.name });  

Featured

node apps modules async fibers

Node Roundup: 0.6.6, asyncblock, Introduction to Node Modules, Review19

Posted on .

Node 0.6.6

Node 0.6.6 is out, which updates npm, fixes some bugs, and adds pause/resume semantics to
stdin. Node also has a new website that is greener than ever, but
remains clean and features a new corporate-friendly edge.

There's also a post on the official Node blog entitled Growing
up
by Ryan Dahl that
discusses Windows Azure support:

The overarching goal of the port was to expand our user base to the largest number of developers. Happily, this has paid off in the form of being a first class citizen on Azure.

asyncblock

asyncblock (License: MIT, npm: asyncblock) is a fork of node-green-light. It works like a flow control library combined with
node-fibers.

The author compares a 'pure Node' example with his own library's code:

function example(callback){
    var finishedCount = 0;
    var fileContents = [];

    var continuation = function(){
        if(finishedCount < 2){
            return;
        }

        fs.writeFile('path3', fileContents[0], function(err) {
            if(err) {
                throw new Error(err);
            }

            fs.readFile('path3', 'utf8', function(err, data){ 
                console.log(data);
                console.log('all done');
            });
        });
    };

    fs.readFile('path1', 'utf8', function(err, data) {
        if(err) {
            throw new Error(err);
        }

        fnishedCount++;
        fileContents[0] = data;

        continuation();
    });

    fs.readFile('path2', 'utf8', function(err, data) {
        if(err) {
            throw new Error(err);
        }

        fnishedCount++;
        fileContents[1] = data;

        continuation();
    });
}

This is the equivalent source using asyncblock and fibers:

var asyncblock = require('asyncblock');

asyncblock(function(flow){
    fs.readFile('path1', 'utf8', flow.add('first'));
    fs.readFile('path2', 'utf8', flow.add('second'));

    var fileContents = flow.wait();

    fs.writeFile('path3', fileContents.first, flow.add());
    flow.wait();

    fs.readFile('path3', 'utf8', flow.add());
    var data = flow.wait();

    console.log(data);
    console.log('all done');
});

Error handling is addressed by including
flow.errorCallback. There are examples of how to use this
in the project's documentation.

Introduction to Node Modules

Robert Kuzelj has been writing a series of posts about Node modules:

He demonstrates how to make packages, and how to take advantage of npm's
major features.

Review19

In other Node-related DailyJS articles I've invited readers to share
their own apps with the community. Review19 by
Srirangan is one such project: a kanban and scrum project management tool.

It's built with Socket.IO to provide a real-time
view of a project, and uses simple agile-inspired records that should be
familiar to users of Jira or Pivotal Tracker.

Sign up is free, so give it a try. The author has a Google Group to
support the community at Review19
Community
.

Featured

node modules network fibers

Node Roundup: Node 0.5.4, Multimeter, Distributed Web Architectures Meetup Videos

Posted on .

You can send your node modules and articles in for review through our [contact form](/contact.html) or [@dailyjs](http://twitter.com/dailyjs).

Node 0.5.4

Node 0.5.4 was released last week. This version introduces yet more Windows
improvements through libuv. It can now be built on Microsoft Visual
Studio via GYP. There are also bug fixes, and V8 has been updated to
3.5.4.

Multimeter

Multimeter (npm: multimeter) is another interesting project by James Halliday. This one generates ANSI progress bars, suitable for use in your next great
console-based application.

var multimeter = require('multimeter')
  , multi = multimeter(process);

// Drop creates a new progress bar at the cursor
multi.drop(function(bar) {
  var iv = setInterval(function() {
    var p = bar.percent();

    bar.percent(p + 1); 

    if (p >= 100) clearInterval(iv);
  }, 25);
});

Videos for Node Distributed Web Architectures Meetup

Joyent have been kind enough to publish videos for the Distributed Web
Architectures
meetup

that was held on the 4th of August.

Curtis Chambers from Uber discusses how Uber's real-time mobile system
has been made more efficient with Node. Dave Pacheco from Joyent
explores behind the scenes of the analytics and visualisation tools in
their SmartDataCenter software. And, Matt Ranney explains how Node has
helped reduce latency in Voxer's real-time voice application.