Thursday, March 03, 2011

Simple HTML Form parsing in node.js

I'm new to Node.js, but already having fun with it. I was trying to grab form POST data and couldn't find a simple example to learn from (using a multipart MIME parser seemed a little like overkill) so I wrote the following code.

The code registers two callbacks - one for the 'data' event which is called when a chunk of body data arrives (there may be more than one such call depending on the size of the body) and the other for the 'end' event when the request has "ended".

Of course, this example is too simple to use in most real systems (caveat lector) - no checks on the content are made, and the parsing takes place only after the whole body is read. Not ideal.
var http = require('http');
var url = require('url') ;

http.createServer(

function (request, response) {
var full_url = url.parse( request.url, true ) ;
var pathname = full_url.pathname ;
var q_params = full_url.query ;
var body = "" ;

response.writeHead(200, {'Content-Type': 'text/plain'});

if ( request.method === "POST" &&
request.headers['content-type'] === "application/x-www-form-urlencoded"){

request.on('data',
       function( chunk ) {
         // append the chunk to the growing message body
body += chunk ;
}) ;

request.on('end', function(){
var params = body.split('&') ;

for ( param in params ){
var pair = params[param].split('=') ;
response.write("Name: " + pair[0] + " = " + pair[1] + "\n") ;
}

response.end() ;
}) ;
}
}
).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

0 comments: