A basic requirejs for WScript

So I like the module pattern when programming javascript.  So when I came to writing a script to process some inbound emails in an MSSQL database, I had already chosen JavaScript as my language of choice, and wanted to use the module pattern, so I wrote a crude but effective require function:-

function require(FN) {
    var cache = require.__cache = require.__cache || {};
    if (cache[FN]) return cache[FN];
    var FSO = WScript.CreateObject("Scripting.FileSystemObject");
    var T = null;
    try {
        var TS = FSO.OpenTextFile(FN,1);
        if (TS.AtEndOfStream) return "";
        T = TS.ReadAll();
        TS.Close();
        TS = null;
    } catch(e) {
        WScript.echo("ERROR! " + e.number + ", " + e.description + ", FN=" + FN);
        WScript.quit();
        return;
    }
    FSO = null;
    T = "(function(global){\n" + '"use strict";' + "\n" + T + "})(this);\n\n////@ sourceURL=" + FN;
    cache[FN] = eval(T);
    if ("VERSIONINFO" in cache[FN]) WScript.echo(cache[FN].VERSIONINFO);
    return cache[FN];
}

Use as follows:-

var interface = require("module.js");
interface.run();

Where module.js contains:-

return {
  run: function() {
  }
};

What module returns, is up to the module. It may be an object, a function, a resource. I use this in a script called app.js that takes the first argument on the command line as the name of the app to run, loads it as a module, then calls main() passing the rest of the arguments to the main function.

var arguments = WScript.arguments;
if (arguments.length > 0) {
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
        args.push(WScript.arguments(i));
    }
    var name = args.shift();
    var app = require(name+".js");
    if (app) {
        var exitstatus = app.main.call(app, args);
        if (typeof exitstatus != undefined) {
            WScript.quit(exitstatus);
        }
    } else {
        WScript.echo("Error, cannot find " + name + ".js");
        WScript.quit(1);
    }
}

I can then run my application (procemail.js) as follows:-

cscript.exe app.js procemail
Advertisements

About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in JavaScript, module pattern, require, WScript and tagged , , , . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

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