A 5 minute pitch for node.js

I’ve been doing some HTML 5 development lately and was groaning about lack of server side support for Websockets when a college suggested I look at Node.js …

Node’s goal is to provide an easy way to build scalable network programs. …Node will show much better memory efficiency under high-loads than systems which allocate 2mb thread stacks for each connection. Furthermore, users of Node are free from worries of dead-locking the process—there are no locks. Almost no function in Node directly performs I/O, so the process never blocks.  Node.js

To keep this to the 5 minutes promised in the title, these 3 articles sold me on the potential of Node.js :

5 minutes later I finished my first node.js script that did exactly what I needed. And honestly more than half the 32 lines are comments:

/*
This script will tail (following) a file and stream new data out to clients
connected  via a WebSocket. The file to tail and the tcp port need to be
specified when launching this process:

Usage: node tail2socket.js MY_LOG_FILE 8000

This uses miksago's node-websocket-server

https://github.com/miksago/node-websocket-server

NOTE: As of 2010-10-20 the WebSocket spec and this library are in active
development. If this code doesn't work check for updated lib and browser.

*/
var ws = require('./lib/ws');
var tailFile = process.ARGV[2];
var port = process.ARGV[3];
var spawn = require('child_process').spawn;
var eachLine = /^(.*)$/mg;
var server = ws.createServer();
     server.listen(port);
var tail = spawn("tail", ["-f", tailFile]);
  tail.stdout.on("data", function(data){
  var line = String(data).match(eachLine);
  if (line && line.length){
    for (var i = 0 ; i < line.length; i++){
      server.broadcast(line[i]);
    }
  }
});
About these ads
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s