Emulating XMLHttpRequest in node.js

I’ve been following the node.js project for a while. It’s a really cool, lightweight, event-based implementation of server side Javascript using V8. I hadn’t used it at all because it was missing a few key features, mainly binary support. I checked the project status a few days ago and lo and behold, binary support had been added. Now it was getting interesting! I decided to start a project to learn a bit about it. node-XMLHttpRequest (node-XHR): XMLHttpRequest emulation to allow reuse of browser based libraries.

node.js has a http client library included. I implemented XMLHttpRequest using this library but may need to switch to tcp to support additional missing features. One of the biggest missing features in node.js is SSL support, so node-XHR does not support it. There are additional problems with a server side implementation of XHR. In the browser domain and port restrictions apply. The browser knows what server and port the connection uses. With a server side implementation you are not necessarily connected to a server at the start. Short of using variables in a config file there is no way of knowing the local server’s config. You could be running on a non-standard port. Due to these issues it’s important to specify the full URL of the target if it’s anything more than localhost on port 80. I haven’t implemented any cross domain restrictions which means remote connections are allowed.

Here’s the demo code (demo.js) included with the project:


var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
	puts("State: " + this.readyState);

	if (this.readyState == 4) {
		puts("Complete.\nBody length: " + this.responseText.length);
		puts("Body:\n" + this.responseText);

xhr.open("GET", "http://driverdan.com");

Look familiar? It should, the syntax is the same as the standard XMLHttpRequest. It wouldn’t be very useful if it wasn’t.

The project can be viewed at http://github.com/driverdan/node-XMLHttpRequest

Posted on October 4, 2009 at 4:02 pm by admin · Permalink
In: Uncategorized · Tagged with: , ,

You're visiting the blog of Daniel DeFelippi. Click here to view my profile site, driverdan.com.