First version of Restlet JS client for Node.js

Whereas the Restlet JS version for browser is written in JavaScript, it requires some adjustements to work in server-side JavaScript applications with Node.js. This is due to following:

  • Node.js uses a module system that requires to explicitly import modules you want to use
  • Because of module isolation, Node.js requires to specify which objects the module will provide
  • The XML support is different and based on extern modules
  • The code to parse JSON isn’t exactly the same
  • Node.js doesn’t use XMLHttpRequest class to execute HTTP requests but client, request and response objects provided by the HTTP module

For these reasons, the JavaScript code needs to be adapted but we don’t want to rewrite all contents since most of it is common. We integrate mechanisms provided by the Restlet forge in order to remain in the same spirit of Restlet Java editions. This means that we have a Restlet JavaScript client edition for browsers and Restlet JavaScript client edition for Node.js.

If you look at code, you can see some comments to actually handle these adjustements very simply, as shown below:

// [ifdef nodejs] uncomment
//var jsclass = require("./jsclass/core");
//var util = require("util");
//var http = require("http");
//var libxmljs = require("libxmljs");
// [enddef]


  createClientCall: function(request) {
    // [ifndef nodejs]
    return new XhrHttpClientCall();
    // [enddef]
    // [ifdef nodejs] uncomment
    //return new NodeJsHttpClientCall();
    // [enddef]


Such editions allow using Restlet JS client within Node.js applications in the same way than described in my previous post, First stones to the Restlet edition for JavaScript. Following code describes how to add Restlet code in an application of this kind:

var assert = require("assert");
var restlet = require('./lib/restlet-client');

var clientResource = new restlet.ClientResource(
clientResource.get(function(representation) {
  console.log("representation = "+representation);
  var content = representation.getText();
  console.log("content = "+content);
  var jsonRepresentation = new restlet.JsonRepresentation(representation);
  var contact = jsonRepresentation.getObject();
  assert.equal("lastName1", contact.lastName);
  assert.equal("firstName1", contact.firstName);
}, restlet.MediaType.APPLICATION_JSON);

This entry was posted in JavaScript, Node.js, Restlet and tagged , , . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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