Tag-Archive for ◊ Node.js ◊

Monday, April 16th, 2012
Director is a URL router module which comes as part of the flatiron framework.  It works in a browser for single page apps and in Node.js. It’s not a plugin for another framework. It’s not dependent on anything. It’s a modern router that was designed from the ground up with javascript.
Installing flatiron
You can install flatiron using npm (npm install flatiron –g)
Director handles routing for HTTP requests similar to journey or express:
var http = require(‘http’);
var director = require(../lib/director’);
function sayWelcome(route) {
this.res.writeHead(200, { ‘Content-Type’‘text/plain’ });
this.res.end(‘Welcome to flatiron routing sample’);
}
var router = new director.http.Router({
: {
get: sayWelcome
}
});
router.get(‘/index’, sayWelcome);
router.get(‘/home’, sayWelcome);
var server = http.createServer(function (req, res) {
router.dispatch(req, res, function (err){
if (err) {
res.writeHead(404);
res.end(‘Error!!!’);
}
})
});
server.listen(8083);
When developing large client-side or server-side applications it is not always possible to define routes in one location. Usually individual decoupled components register their own routes with the application router. Director supports ad-hoc routing also.
router.path(/\/customers\/(\w+)/, function (res) {
this.post(function(id) {
//sayWelcome(‘some’);
this.res.writeHead(200, { ‘Content-Type’‘text/plain’ });
this.res.end(‘Create a customer with Id = ‘ + id)
});
this.get(function (id) {
//sayWelcome(‘some’);
this.res.writeHead(200, { ‘Content-Type’‘text/plain’ });
this.res.end(‘Gets a customer with Id = ‘ + id)
});
this.get(/\/orders/, function (id) {
this.res.writeHead(200, { ‘Content-Type’‘text/plain’ });
this.res.end(‘Gets orders for a customer with Id = ‘ + id)
});
});















Category: General | Tags: ,  | Leave a Comment
Tuesday, April 10th, 2012
Pure javascript, while great with unicode-encoded strings, does not handle straight binary data very well. This is fine on the browser, where most data is in the form of strings. However, node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both which make it necessary to deal with purely binary streams of data. Node has several strategies for manipulating, creating, and consuming streams. Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. The Buffer class is a global, making it very rare that one would need to ever require(‘buffer’).
Converting between Buffers and JavaScript string objects requires an explicit encoding method. The encodings that are supported are ‘ascii’, ‘utf8′, ‘usc2′, ‘base64′, ’binary’ and ‘hex’.
Writing to buffers
new Buffer(size) methods allocates a new buffer of size octets. Once the buffer is created, the buffer.write method is used to write a string value to the buffer
var buffer = new Buffer(100);
var stringToWrite = ‘Sample text to add to a buffer’;
//Write data to a buffer
buffer.write(stringToWrite, ‘utf-8′);
//finding the length of buffer
var offset = Buffer.byteLength(stringToWrite);
console.log(offset);
//Appending data to the existing buffer
buffer.write(‘. This is an appended text’, offset, ‘utf-8′);
console.log(buffer.toString(‘utf-8′));
Copy values to buffer
buffer.copy allows one to copy the contents of one buffer onto another. The first argument is the target buffer on which to copy the contents of buffer, and the rest of the arguments allow for copying only a subsection of the source buffer to somewhere in the middle of the target buffer. For example:
var helloBuffer = new Buffer(50);
helloBuffer.write(‘Hello ’, 0, ‘utf-8′)
var welcomeBuffer = new Buffer(‘node.js.’);
var helloStringLength = Buffer.byteLength(‘Hello ‘);
var welcomeStringLength = Buffer.byteLength(‘node.js.’);
//Copies from welcomeBuffer to helloBuffer
welcomeBuffer.copy(helloBuffer, helloStringLength, 0);
console.log(helloBuffer.toString(‘utf-8′));
Cropping the buffer
buf.slice([start], [end]) method returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. The slice is not a new buffer and merely references a subset of the memory space. Modifying the slice will also modify the original buffer. For example:
var nodejsSlice = helloBuffer.slice(helloStringLength, helloStringLength + welcomeStringLength);
console.log(nodejsSlice.toString());
nodejsSlice.write(‘Prajeesh’);
console.log(helloBuffer.toString());


Category: General | Tags:  | Leave a Comment
Sunday, April 01st, 2012

The EventEmitter is the base building block for all compositions that would need to broadcast data to multiple consumers. Whenever there is an object that represents the source of several kinds of events, node.js usually makes the underlying class inherit from EventEmitter. The EventEmitter implementation makes use of the observer pattern by providing the ‘on’ function for objects that are interested in listening to an event. For e.g. you can listen to a specific event by calling the ‘on()‘ function on your object, providing the name of the event, as well as a callback closure as the

parameters.
eventEmitterInstance.once(‘event’, callbackSample1); //singular callback registration
//or
eventEmitterInstance.on(‘event’, callBackSample2); //multiple callback
Below given is a sample server implementation that logs the messages passed as querystring to the server using the EventEmitter implementation
var http = require(‘http’);
var port = process.env.PORT;
var server = http.createServer(function(request, response){
var eventEmitter = require(‘events’).EventEmitter;
var eventEmitterInstance = new eventEmitter();
var querystring = require(‘querystring’);
var message = querystring.parse(request.url).message;
var callbackSample1 = function(message)
{
console.log(‘logging from 1st callback function ‘ + message);
};
var callBackSample2 = function(message)
{
console.log(‘logging from 2nd callback function ‘ + message);
};
eventEmitterInstance.once(‘event’,
callbackSample1);
//singular callback registration
eventEmitterInstance.emit(message);
eventEmitterInstance.on(‘event’,
callBackSample2);
//multiple callback
eventEmitterInstance.emit(message);
eventEmitterInstance.emit(message);
eventEmitterInstance.removeListener(‘event’,
callBackSample2);
response.writeHead(200);
response.end(‘<html>’+
‘<head>’+
‘<meta http-equiv=”Content-Type”
content=”text/html; ‘
+
‘charset=UTF-8″
/>’
+
‘</head>’+
‘<body>’+
‘<form method=”post”>’ +
‘<h1>Messaging sample </h1>’ +
‘</form>’+
‘</body>’+
‘</html>’);
});
server.listen(port);
console.log(‘Server started….’);
As you can see, the on() function 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.
Saturday, March 31st, 2012
Cloud9 IDE is an online development environment for Javascript and Node.js applications as well as HTML, CSS, PHP, Java, Ruby and 23 other languages. Cloud9 IDE lets you build, debug, and run your Node.js applications within the browser. Set breakpoints, follow the call stack, and analyze your performance. In this post I’ll demonstrate how to build a simple Node.js server app using Cloud9 IDE.
Creating a new project:
Creating a project in Cloud 9 IDE requires an account which is available as a free subscription at http://c9.io/.
After successful registration you can create a new project by adding a new project form the dashboard.
After entering the project name you can select the type of project to create
·
Git project: will allow you to run git commands from the console and push your changes to Github
·
Mercurial: will allow you to run hg commands form the console and push your changes to Bitbucket.
·
FTP: will allow you to upload your files directly to an FTP server you have access to.
Select create after choosing a project type. Now, just click Start Editing to get started!
You can right click on the selected project and add a ‘New File’
Creating the node.js server
We’ll create a simple http server with controllers to handle the request and send the response to the
clients. Create a new loginController.js file and add the code given below.

exports.process = function handle(response) {

response.writeHead(200);
response.end(‘<html>’ +
‘<head>’ +
‘<meta http-equiv=”Content-Type”
content=”text/html; ‘
+
‘charset=UTF-8″ />’ +
‘</head>’ +
‘<body>’ +
‘<form action=”/login” method=”post”>’ +
‘Login name:<input type=text value=”"
name=”txtLogin” style=”width: 100px”></br>’
+
‘Password
:<input type=password value=”" name=”txtPassword”
style=”width: 100px”></br>’
+
‘<input type=”submit” value=”Login”
/> &nbsp; &nbsp; <input type=”submit”
value=”Cancel” />’
+
‘</form>’ +
‘</body>’ +
‘</html>’);
The process property is assigned to an object called ’exports’. Such an ‘exports’ object is available in every module, and it is returned whenever the required function is used to include the module. We can now use this function as given below
var loginController = require(‘./handlers/loginController’);
loginController.process(response);
Similarly you can create the other controllers and then the http server like
var http = require(‘http’);
var homeController = require(‘./handlers/homeController’);
var loginController = require(‘./handlers/loginController’);
var errorController = require(‘./handlers/errorController’);
var port = process.env.PORT;
var requestListener = function(request, response)
{
switch(request.url)
{
case ‘/’:
homeController.process(response);
break;
case ‘/login’:
loginController.process(response);
break;
default:
errorController.process(response);
break;
}
}
var server = http.createServer(requestListener);
server.listen(port);
In the first line, we included the http core module and assign it to a variable called http. Later we use this variable called server by calling http.createServer(). You can also specify which port the server listens to. When
Node.js projects run within Cloud 9 IDE, you can retrieve the port information with process.env.PORT. You can run the project by clicking the Debug button.
Category: General | Tags: ,  | One Comment