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
| require | A require() function that knows about this module and can load other modules |
| module | An object that contains the properties “id” and “URI” |
| exports | An object that will be returned fromthe require() function. |
For More information about CommonJS, see: http://wiki.commonjs.org/wiki/CommonJS