Wednesday, June 27, 2012

Mootools Class in NodeJS global context

In continuation of my previous articles, here I came across a requirement to load Mootools Class in NodeJS global context. Let me try to explain, NodeJS module system is one-on-one with module-on-file, which creates a problem. For example lets say I have a Class Application as described in my other article, defined in Application.js

Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
exports.Application = Application;

And now I try to make use in my Server as below

server.js
require('mootools');
var _Application = require('./Application');
 
var app = new _Application.Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Not so good, you see _Application.Application() to create the object, this is fine if you want to have module to be in its own context, but what about if you don't ? Lets check how to load the Application class in global context so you could create the object in old fashion way var app = new Application();

To do so, you do not have to export the class as before, so the new code becomes as follows

Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});

Create one file Include.js with the following contents
 
Include.js
var fs = require('fs');
var vm = require('vm');
 
(function(){
 
var include = this.include = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);
 
})();

And the server file with following contents

server.js
require('./mootools');
require('./Include');
include('./Application.js');
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

The Include.js file have a function include that does the job of loading the javascript file in global context. So you can access the class the good way.

No comments:

Post a Comment