Meryl – A thin web layer for NodeJS
Lately, there has been a rising star that succeeded to attract quite a bit of IT people’s attention with its powerful and natural support for developing server-side applications using JavaScript in an event-driven manner. Yes it’s the new (for about one year?) fun platform NodeJS which is neatly written by Ryan Dahl, the nice guy who helps the community gracefully and accepts the contributions modestly.

I know, you’re not the only one saying that there are already plenty of event-driven platforms like Twisted (Python), Event Machine (Ruby) or even programming languages with their first-class support for non-blocking processes like Erlang and Scala. So then, what is in the name of NodeJS? Because it is JavaScript, which is the programming language of web that is already widely accepted very much by web crew and this time it is fast. It is fast why because it is tightly adapted on Google’s new V8 JavaScript engine , which really boosts JavaScript execution speed with its innovative internals. And one of the most important reasons in my humble opinion is that NodeJS has a very active and helpful community around it. Day by day, new modules, libraries and frameworks are coming and people around them get really excited to be part of this formation and interaction. Please experiment this by subscribing the NodeJS mailing group, I really find it hard to follow every thread. Also check out the amount of NodeJS IRC channel’s activity with Mathias Pettersson‘ s genius NodeJS application that displays incoming messages around the world as dots on a well-designed map
interface.
By the way there is another reality that rising of html5 has boosted NodeJS popularity, that’s because with html5, web browsers are now becoming complete and perfect platform for programmable user interfaces. They provide solutions for every kind of requirements more with already implemented features on popular browsers like ‘web workers’, ‘web socket’, ‘canvas drawing’ and ’storage’ etc. recently. Browsers has just become the ‘Earth’, a unique, organic and complex platform to live in which are already available for everyone, under their feet. So, while the browsers’ logic managed by JavaScript, using JavaScript on server side makes us use one army-knife for every kind of application development safari. Dealing with one programming language of course also makes us feel more comfortable, professional and cheerful. I won’t dive into the features of JavaScript but “it is not a dsl converting dom objects into sliding menus” (thanks Manoj Mathai for this http://gianttweet.com/18688351371) and strongly recommend obtaining this book if you haven’t got a copy already.
While the jargon ‘event-driven development‘ tells much for programmers, nowadays it has a special meaning for serious corporation’s serious server-side applications with its ability of handling plenty of concurrent tasks easily. Dealing with more requests with higher throughput using same hardware resources is almost the key purpose of scaling horizontally for ‘hot’ server applications. This is where NodeJS appears under the spotlights because it has just become one of the biggest buster candidate for these issues. This quote from NodeJS web site is quite lean and mean.
Node’s goal is to provide an easy way to build scalable network programs.
If you’re confused with platforms dealing concurrency with non-blocking processes that they can use the only one core of modern multi-core processors, you’re right. But there are opportunities for NodeJS codebase to overcome this issue. Also there are helper projects like spark (thanks goes Tim Caswell) that forks your NodeJS processes to maximize the core usage of multi-core CPUs with plenty of options.
Ok, in fact this write up was planned to introduce my own simplistic and minimalistic web framework Meryl written on top of NodeJS, but how much NodeJS get me excited, I wanted to introduce it you briefly (Yes, I know it was a long brief
). Don’t wait, go obtain the latest NodeJS release here and build it for your own box. As this entry posted, the version of NodeJS is:
> node -v v0.1.101
Meryl is a minimalistic web framework for NodeJS. Yes, it is minimalistic because it is only 140 lines of code with restricted amount of simple features. You can go for project homepage on GitHub http://github.com/coffeemate/meryl/ . Since Meryl has the motto of ‘minimalistic’ it promises quite amazing set of features.
Meryl has:
- Router implementation with path expressions.
- Handler implementation which has a context object carrying easy access information about requests.
- Middleware implementation for filtering every request for applying generic logics.
- Easy to extend small codebase.
- Simple usage.
Let’s break down for some real examples. If you obtained NodeJS already, you’d also better install npm (Node Packaging Manager). Npm is conventionally accepted current package manager for NodeJS modules and you’re so lucky that Meryl has already bundled for it. Go install npm with a few easy steps published here.
Thanks to author of npm Isaac Z. Schlueter who’s provided us installing and publishing NodeJS modules flawlessly.
Once you install npm, simply grab meryl by typing:
> npm install meryl
If you see the ‘ok’ at the end of the output of installation process, you are ready to go with Meryl. As this posted Meryl has the version of ‘0.2.0′ and not tested well with a poor documentation. However it has enough base to be introduced. Here is a simple ‘hello world’ example.
// app.js
var meryl = require('meryl');
meryl.h('GET /', function (req, resp) {
return "<h1>Hello, World</h1>";
});
require('http').createServer(meryl.cgi).listen(3000);
require('sys').debug('serving http://localhost:3000');
This usual but useless example demonstrates the basic usage of Meryl. On the first line we import Meryl and obtain an instance of it. The function ‘h’ declares a handler which sends a simple html response to client, when client requests an url that matches with ‘METHOD path’ pattern expression given in the first parameter. Finally we attach meryl to the NodeJS’s built-in http module and put it into listening state on port 3000. You should run the code using NodeJS executable.
> node app.js serving http://localhost:3000
Once the code runs, you are ready to hit running server by your http client, mostly your browser pointing address http://localhost:3000. If you see the ‘Hello, World!’ you are done. Also you should try requesting a non-exisitng url and see what happens.
Since you are given the simplest usage, Meryl has more. Let’s try a more complex example.
// app.js
var meryl = require('meryl');
meryl.h('POST /users/{userid}', function (req, resp) {
return '<h1>User of id: '
+ this.userid + ' updated with data'
+ this.postdata + '</h1>';
});
require('http').createServer(meryl.cgi).listen(3000);
require('sys').debug('serving http://localhost:3000');
This time we have a RESTful path and a variable named ‘userid’ inside it. When Meryl matches and routes request to this handler, handler can access path, get (query string) and post parameters within the current function execution object context. Also notice that this time we are trying to handle http post requests.
By the way there are two types of path variables,
- { … } – curly braced parameters are partial, they match until the meet ‘?’, ‘/’ or ‘.’ character
- < ... > – tagged(!) parameters are greedy, they match whatever they meet until you denote a block character.
To explain more, i want to show you sample usages of that two kind of path parameters.
// Won't match http://localhost:3000/static/common/css/style.css
meryl.h('GET /static/{filepath}', function (req, resp) {
...
});
// Will match http://localhost:3000/static/common/css/style.css
meryl.h('GET /static/<filepath>', function (req, resp) {
// common/css/style.css
var filepath = this.filepath;
...
});
Also you are free to mix your usual regular expression in path matching patterns.
Meryl has a simple middleware implementation implies a basic interface. Take the example below.
// app.js
var meryl = require('meryl');
var sys = require('sys');
// Works on all requests
meryl.p('.*', function() {
this.headers.Server = 'Node - Meryl';
return true;
}
);
// Works on all GET request
meryl.p('GET <whatever>', function() {
sys.debug('page requested: ' + this.whatever);
return true;
}
);
// Works on all requests under virtual path 'protected'
meryl.p('GET /protected/<filepath>', function() {
throw new Error('Access denied: ' + this.filepath);
}
);
meryl.h('GET /', function (req, resp) {
return '<h1>Welcome, Meryl.</h1>';
});
// rest is omitted for brevity
// ...
require('http').createServer(meryl.cgi).listen(3000);
require('sys').debug('serving http://localhost:3000');
We declare a filter by using the function ‘p’. It almost works like any proper handler but they are responsible for processing every request they match before any handler matches. There can be more than one filter that executes on the same request in order they declared in the code. If one filter returns the boolean of ‘false’, the next declared filter won’t be called. If every filter returns the boolean of ‘true’ the handler matched is executed at the end of the chain. In the example we declare three filters. The first one match every requests comes into server and attaches an header to be sent to the client, it returns ‘true’ by default and let Meryl to call second declared filter. The second one works on every http ‘GET’ request and logs the paths to the standart output. And the last one works on every request under the virtual directory ‘protected’. As you guess it denies incoming requests and breaks the chain by throwing an exception. Once the chain broken down, the matched handler for the current route won’t be called.
Meryl currently shows two error pages. It shows ‘404′ document not found page when it can not match a handler for an incoming request and ‘500′ server error page when an error occured on the server side. You are free to define your custom handlers for both.
meryl.err = function(req, resp) { ... }
meryl.notFound = function(req, resp) { ... }
Meryl is really small and funny. I’m spending so enjoyable times while playing with it. I know it’s too experimental and featurless for in production use. But don’t stop here. There are plenty rock solid, full stacked web frameworks for production use like TJ Holowaychuk‘ s ExpressJS (On Connect), Geddy, Grasshopper etc.
Also you should checkout the great amount of existing modules written for NodeJS http://wiki.github.com/ry/node/modules
This has become quite a long post. It’s done for now but I will continue propaganding NodeJS and Meryl with my plain English
. Please do feedback, it is greatly appreciated.
Find me on twitter http://twitter.com/kadirpekel
Good luck with NodeJS.


It’s so popular that nowadays almost all web applications on the internet use Facebook Connect to attract their potential users to move their pre-built social networking structure to on their own systems. It’s no exception that our new social networking based project at work wants to adopt this feature so since we use Spring 3.x as the main framework of our project, as team we’ve spend some time to inject the Facebook Connect structure into the Spring Security (F.K.A Acegi Security). As a nice side effect, i decided to extract this integration information from our in house project to contribute and rearranged the structure to share with you in a more easy and convenient way.