RingoJS

Module globals

RingoJS adopts some of the global properties from the Rhino shell and adds a few of its own.

Note that this module must and can not be imported like an ordinary module. It is evaluated only once upon RingoJS startup.


addToClasspath (path)

Adds path to the RingoJS application classpath at runtime. This is necessary if libraries and their classes are not in the default Java classpath.

Calling addToClasspath() will invoke an org.ringojs.engine.AppClassLoader, which is a subclass of java.net.URLClassLoader. It checks if the URL has been already loaded and if not, adds it to the resource search path. If the given URL ends with /, it will be treated as resource directory, otherwise it's assumed to refer to a .jar file. .jar files encapsulate various .class files in different packages, whereas resource directories are the starting point for the JVM's arbitrary .class lookup. The function throws an exception if it could not load a path or if it fails.

Example

// Adds Apache Lucene text search engine to the classpath
addToClasspath("../jars/lucene-core.jar");

Parameters

String|Resource|Repository path

a directory or jar path; or a single resource; or a repository


arguments

The arguments array contains the command line arguments RingoJS was started with.

Note that this variable is shadowed by the arguments object inside functions which is why it is usually safer to use system.args instead.


clearInterval (id)

Cancel a timeout previously scheduled with setInterval().

Parameters

Object id

the id object returned by setInterval()


clearTimeout (id)

Cancel a timeout previously scheduled with setTimeout().

Parameters

Object id

the id object returned by setTimeout()


console

Debug console to print messages on stderr. It’s similar to the console object implemented in most web browsers.

Example

console.log('Hello World!');

See


defineClass (clazz)

Loads a custom Java-based host object into the global scope. This is useful to provide transparent access to Java classes inside the JavaScript environment. It uses ScriptableObject.defineClass() to define the extension.

Example

// org.somejavalib.Foo extends org.mozilla.javascript.ScriptableObject
defineClass(org.somejavalib.Foo);
const x = new Foo();

Parameters

java.lang.Class clazz

the host object's Java class

See

ECMAScript 5 host object definition
Rhino's ScriptableObject.defineClass()
The Java package org.ringojs.wrappers includes typical host objects like Binary, EventAdapter and Stream.

environment

Deprecated!
Use the `system` module's `properties` and `env` exports instead.

The environment object contains the Java system properties and is specific to the Rhino engine. Java system properties are set on the command line using the -Dproperty=value syntax and can be modified during the runtime. They do not relate to the operating system's environment variables. Because of the misleading name of this global property, using system.properties is recommended.


exports

The exports object as defined in the CommonJS Modules 1.1.1 specification.

Define properties on the exports object to make them available to other modules requiring this module.

Example

exports.multiply = function(x, y) { return x * y; }

gc ()

Runs the garbage collector.


getRepository (path)

Resolve path following the same logic require uses for module ids and return an instance of org.ringojs.repository.Repository representing the resolved path. A repository provides a unified loading of scripts and other application resources. It represents an abstract container of resources. For file I/O use the fs module, which provides fine-grained functions for file and stream manipulation.

Example

> const fileRepository = getRepository("/usr/local/httpd/htdocs/");
> const resource = fileRepository.getResource("someFile.xml");
> resource.getUrl();
[java.net.URL file:/usr/local/httpd/htdocs/someFile.xml]

Parameters

String path

the repository path

Returns

org.ringojs.repository.Repository

a repository


getResource (path)

Resolve path following the same logic require uses for module ids and return an instance of org.ringojs.repository.Resource representing the resolved path. It represents an abstract container for exactly one resources. For file I/O use the fs module, which provides fine-grained functions for file and stream manipulation.

Example

// Current working directory: /usr/local/httpd/htdocs/
> const resource = getResource("./someFile.xml");
>
> resource.getChecksum();
1419793411000
>
> resource.getUrl();
[java.net.URL file:/usr/local/httpd/htdocs/someFile.xml]
>
> resource.getBaseName();
someFile
>
> resource.exists();
true
>
> // read the content
> resource.getContent();
'<?xml version="1.0" encoding="UTF-8"?> ...

Parameters

String path

the resource path

Returns

org.ringojs.repository.Resource

a resource


global

A reference to the global object itself.

When a module is evaluated in RingoJS it uses its own private module scope which in turn uses this shared global object as prototype. Therefore, properties of the global object are visible in every module.

Since the global object is hidden in the prototype chain of module scopes it cannot normally be accessed directly. This reference allows you to do so, defining real global variables if you want to do so.

Example

global.foo = "bar";

include (moduleId)

Load a module and include all its properties in the calling scope.

Example

include('fs');
// calls fs.isReadable()
if (isReadable('essay.txt') ) { ... }

Parameters

String moduleId

the id or path of the module to load


load (filename...)

Load JavaScript source files named by string arguments and execute them. If multiple arguments are given, each file is read in and executed in turn.

Parameters

String... filename...

one or more file names


module

The module object as defined in the CommonJS Modules 1.1.1 specification.

The RingoJS module object has the following properties:


module.directory

The directory that contains this module.


module.exports

By default, module.exports refers to exports object. Setting this property to a different value will cause that value to be used as exports object instead.


module.id

The module id of this module.

Example

// We are inside the foo.js module
// prints /usr/local/ringo-app/lib/foo
console.log(module.id);

module.path

The absolute path of this module's source.


module.resolve (path)

Resolve path relative to this module. Resolving itself is equivalent to calling require with a strict relative path starting with './'. If an absolute path is provided, the function will still resolve relative to the current module and never to the filesystem root.

module.resolve() returns an absolute path if the current module is located inside a regular file repository. For other types of modules such as those residing in a .jar file it returns a relative path relative to the module's module path root.

Example

// current module is located at /usr/local/a/b/module.js
module.resolve('.')          // -> /usr/local/a/b/
module.resolve('./other.js') // -> /usr/local/a/b/other.js
module.resolve('../c/d')     // -> /usr/local/a/c/d
module.resolve('/etc/hosts') // -> /usr/local/a/b/etc/hosts

Parameters

String path

Returns

String

the resolved path


module.singleton (id, factory)

module.singleton enables the creation of singletons across all workers using the same module. This means that a value within a module will be instantiated at most once for all concurrent worker threads even though workers usually operate on their own private scopes and variables.

The id argument identifies the singleton within the module. When module.singleton is called with an id that has not been initialized yet and the factory argument is defined, factory is invoked and its return value is henceforth used as singleton value for the given id.

Once the value of a singleton has been set, the factory function is never called again and all calls to module.singleton with that id return that original value.

module.singleton supports lazy initialization. A singleton can remain undefined if module.singleton is called without factory argument. In this case module.singleton returns undefined until it is first called with a factory argument.

Example

// db-controller.js
// Create a single cache for all workers
const entityCache = module.singleton("entityCache", function() {
  return new SomeFancyCache(1000);
});

// All instances of "db-controller" in different workers
// will use the same cache because it's a singleton
entityCache.put("somekey", { ... });
entityCache.get("somekey");

Parameters

String id

the singleton id

Function factory

(optional) factory function for the singleton

Returns

the singleton value


module.uri

This module's URI.

Example

// We are inside the foo.js module
// prints: /usr/local/ringo-app/lib/foo.js
console.log(module.uri);

print (args...)

Converts each argument to a string and prints it.

Parameters

*... args...

one ore more arguments


privileged (func)

Calls func with the privileges of the current code base instead of the privileges of the code in the call stack.

This is useful when running with Java security manager enabled using the -P or --policy command line switches.

Parameters

Function func

a function

Returns

Object

the return value of the function


quit ()

Quit the RingoJS shell. The shell will also quit in interactive mode if an end-of-file character (CTRL-D) is typed at the prompt.


require (moduleId)

The require function as defined in the CommonJS Modules 1.1.1 specification.

moduleId is resolved following these rules:

  • If moduleId starts with './' or '../' it is resolved relative to the current module.
  • If moduleId is relative (starting with a file or directory name), it is resolve relative to the module search path.
  • If path is absolute (e.g. starting with '/') it is interpreted as absolute file name.

The RingoJS require function has the following properties:

Parameters

String moduleId

the id or path of the module to load

Returns

Object

the exports object of the required module


require.extensions

An object used to extend the way require loads modules.

Use a file extension as key and a function as value. The function should accept a Resource object as argument and return either a string to be used as JavaScript module source or an object which will be directly returned by require.

For example, the following one-liner will enable require() to load XML files as E4X modules:

require.extensions['.xml'] = function(r) new XML(r.content);

require.main

If RingoJS was started with a command line script, require.main contains the module object of the main module. Otherwise, this property is defined but has the value undefined.

Example

// is the current module is the main module?
 if (require.main === module) {
  // Start up actions like in a Java public static void main() method
  const server = new Server();
  server.start();
}

require.paths

An array that contains the module search path. You can add or remove paths items to or from this array in order to change the places where RingoJS will look for modules.


seal (obj)

Seal the specified object so any attempt to add, delete or modify its properties would throw an exception.

Parameters

Object obj

a JavaScript object


setInterval (callback, delay, args...)

Calls a function repeatedly, with a fixed time delay between each call to that function. The function will be called in the thread of the local event loop. This means it will only run after the currently executing code and other code running before it have terminated.

Parameters

Function callback

a function

Number delay

the delay in milliseconds

*... args...

optional arguments to pass to the function

Returns

Object

an id object useful for cancelling the scheduled invocation


setTimeout (callback, delay, [args...])

Executes a function after specified delay. The function will be called in the thread of the local event loop. This means it will only run after the currently executing code and other code running before it have terminated.

Parameters

Function callback

a function

Number delay

the delay in milliseconds

*... [args...]

optional arguments to pass to the function

Returns

Object

an id object useful for cancelling the scheduled invocation


spawn (func)

Calls func in a new thread from an internal thread pool and returns immediately.

Parameters

Function func

a function


sync (func, [obj])

Returns a wrapper around a function that synchronizes on the original function or, if provided, on the second argument.

When multiple threads call functions that are synchronized on the same object, only one function call is allowed to execute at a time.

Example

exports.synchronizedFunction = sync(function() {
  // no two threads can execute this code in parallel
});

Parameters

Function func

a function

Object [obj]

optional object to synchronize on

Returns

Function

a synchronized wrapper around the function