Myna. CommonJS

A library for interacting with a CommonJS environment

CommonJS is a standard for including and executing JavaScript code across multiple JS platforms.  CommonJS’s primary specification is the “require” function that allows you to include code and execute programs using an abstract classpath like so:

//loading a JavaScript class
var Twitter = require("TwitterAPI/Twitter");
var tapi = new Twitter(... options ...);

It is up to the platform implementing CommonJS to translate the class path into a source string and include it.  On Myna this is configured in the Administrator under general settings.  By default, Myna searches first in the MynaPath /shared/js/serveer_only/commonjs and then in /.  As an example these are valid locations for the fictional TwitterAPI:

  • /shared/js/server_only/commonjs/TwitterAPI/Twitter.js
  • /TwitterAPI/Twitter.sjs

Be careful with location and extension.  Paths are searched in the order defined, and .sjs files are favored over .js files in case of conflict

Writing a CommonJS module is simple

//TwitterAPI/Twitter.js

//load dependencies
require("io/file");// "top-level" loads start with a pathname
require("io/http");// "top-level" loads start with a pathname

// relative loads start with a . or ..
// relative loads are relative to module.id when nested or relative to
// $server.currentDir for the initial require() call
require("./TwitterAuth");

//constructor
exports = function(options){
//do stuff
}

exports.prototype ={
login:function(){
... do stuff ..
}
}

//body code is executed every time this file is require()d
Myna.log(
"debug",
"Called " + module.id + " located at " + module.uri
);

Within a CommonJS module there exists three local properties.

CommonJS Properties

requireA require() function that knows about this module and can load other modules
moduleAn object that contains the properties “id” and “URI”
exportsAn object that will be returned fromthe require() function.

For More information about CommonJS, see: http://wiki.commonjs.org/wiki/CommonJS

Summary
Myna. CommonJSA library for interacting with a CommonJS environment
Functions
getRequireFunctionreturns a custom CommonJS require function.

Functions

getRequireFunction

getRequireFunction:function (options)

returns a custom CommonJS require function.

Parameters

optionsoptions object, see below

Options

pathsOptional, default [] An array of MynaPaths to search first for modules
secondaryPathsOptional, default CommonJS paths as defined in Administrator An array of MynaPaths to search first for modules
getRequireFunction:function (options)
returns a custom CommonJS require function.
A MynaPath is a file URI String with certain automatic translations.