NodeJS: Experiments with Middle End Part 2

Note: This is the second in a series of posts describing my experiments with constructing a Middle End. In Part 1, we discussed the concept of the middle end and its advantages.

In my previous post, I talked about Kyle Simpson’s concept of a Middle End—a layer between the front end and back end. Today, I’m going to sketch out my very simple experiments with constructing such a layer.

What I am focusing on here is simply a means of sharing JavaScript code between the client side and the server side.

Let’s start with a very simple NodeJS Module, greetings.js:

var Greetings = function() { }
Greetings.prototype.hello = function(who) {
   return "Hello "+who;
}
module.exports = Greetings;

Next, let’s create a very simple NodeJS script that imports this module, and uses it:

var Greetings = require('./greetings');
var greetings = new Greetings();
console.log(greetings.hello('Node')+"!");

When we run it, this is what we get:

$ node test.js
Hello Node!

All very simple stuff.

Now, suppose we want to use the Greetings module in our front end web app. 

<script src="greetings.js" type="text/javascript"> </script>

Well, it runs and we get the desired output. However, Firebug reports an error within the greetings.js file:

module is not defined
[Break On This Error] module.exports = Greetings;

The solution to this issue is to “mock up” the module object so the error isn’t thrown:

var module = {
   exports: undefined
};

Run it again, and now we see no errors.

Great, so it’s working. We can share simple modules between the client and the server sides.

But what if we want to have a more complex module? One that has some dependencies?

That will be discussed in the next post.

All of the code is available as a Gist.