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:
include("/utils.js"); include("XMLHttpRequest.js"); 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"); xhr.send(); |
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
In: Uncategorized · Tagged with: Javascript, node.js, XMLHttpRequest

