Globals and module bindings
Contents
Server-side code in an Enonic app reaches a handful of names it never declares and never requires: app, log, require, resolve, __ and exports. Only one of them is a true global.
What is actually global
app is the only name XP installs on the JavaScript global object. Every other name on this page is module-scoped: XP wraps each module in a function and passes them in as arguments. The engine contributes a few globals of its own on top; the GraalJS adds Graal.
// what XP evaluates for every module it loads
(function (log, require, resolve, __, exports, module) {
// your module's code goes here
});
Three consequences worth knowing:
-
They are not on the global object. On GraalJS,
globalThis.appresolves whileglobalThis.log,globalThis.require,globalThis.resolve,globalThis.exportsandglobalThis.moduleare allundefined; Nashorn has noglobalThisbinding at all. Inside a moduletypeof requirestill answers"function", because the parameter is in scope. A bundled npm package that probes its environment through the global object will find nothing. -
They can be shadowed. A variable or parameter named
logdeclared in your module hides the binding for the rest of that scope, exactly as it would any other argument. -
They are per module. Each module body gets its own
exports, and arequireandresolvebound to that module’s own location — which is what makes a relative path resolve against the file that wrote it.
App
The app object holds information about the contextual app, and is the one name here that is genuinely global. It has the following properties:
- app.name
-
The name of the application.
- app.version
-
Version of the application.
- app.config
-
Values from the application’s configuration file. This can be set using
$XP_HOME/config/<app.name>.cfg. Every time the configuration is changed the app is restarted.
Examples:
// Get application name
var name = app.name; // com.enonic.app.superhero
// Get application version
var version = app.version; // 1.2.0
// Get some config from the <app.name>.cfg file
var myKey = app.config.secretkey; // Reads the string stored in the "secretkey" property
Log
The log object holds the logging methods. It’s one method for each log level and takes the same number of parameters.
log.debug(message, [args]) (1) (2)
| 1 | string message Message to log as a debug-level message. |
| 2 | array args Optional arguments used in message format. When the last argument is an exception/error instance, its stack trace will be logged. |
log.info(message, [args]) (1) (2)
| 1 | string message Message to log as a info-level message. |
| 2 | array args Optional arguments used in message format. When the last argument is an exception/error instance, its stack trace will be logged. |
log.warning(message, [args]) (1) (2)
| 1 | string message Message to log as a warning-level message. |
| 2 | array args Optional arguments used in message format. When the last argument is an exception/error instance, its stack trace will be logged. |
log.error(message, [args]) (1) (2)
| 1 | string message Message to log as a error-level message. |
| 2 | array args Optional arguments used in message format. When the last argument is an exception/error instance, its stack trace will be logged. |
Examples:
// Log a simple message
log.debug('Hello World');
// Log a formatting message
log.info('Hello %s', 'World');
// Log a formatting message
log.warning('%s %s', 'Hello', 'World');
// Log using the built-in JSON converter
log.error('My JSON %s', object );
// Log an exception with stack trace
try {
thisWillFail();
} catch (e) {
log.error('An error occurred', e);
}
// Log a formatting message with exception stack trace
try {
bean.run();
} catch (e) {
log.error('Error in %s', 'myFunction', e);
}
Resolve()
Resolves a fully qualified path to a local resource based on the current location. It does not check if a resource exists at the specified path. This function supports both relative (with dot-references) and absolute paths.
resolve(path) (1) (2)
| 1 | string path Path to resolve using current location. |
| 2 | returns the fully qualified resource path of the location. |
Examples:
// Absolute path
var path1 = resolve('/views/myview.html');
// Relative path - in this case, the resource must be in the same folder
var path2 = resolve('myview.html');
// Relative path (same as above)
var path3 = resolve('./myview.html');
// Relative path - resource is one level up
var path4 = resolve('../myview.html');
Require()
Loads a JavaScript file and returns its exports. The function implements parts of the CommonJS Modules Specification.
require(path) (1) (2)
| 1 | string path Path to the JavaScript to load. |
| 2 | returns The loaded JavaScript object exports. |
Examples:
// Absolute path
var lib1 = require('/lib/mylib.js');
// Relative path
var lib2 = require('mylib');
// Relative path (same as above)
var lib3 = require('./mylib.js');
// Relative path
var lib4 = require('../mylib');
If the path is relative then it will start looking for the file from the local directory. The file extension .js is not required.
Exports
exports is the object a module exposes to whatever requires it (implementations, libraries, and so on). This is part of the CommonJS module spec.
Assign to it from any module to publish functionality:
export function get(req: Request): Response {
return {body: 'hello'};
}
Authoring in TypeScript, write export and let the build transpile it — the emitted JavaScript assigns to exports. See TypeScript. |
ECMAScript modules are not supported
import, export and dynamic import() do not work at runtime, on either engine.
Use require() and exports in the code you deploy. Writing import/export in TypeScript is fine — the build transpiles it away before deployment. What must not reach the server is an import statement surviving into the emitted JavaScript.
Double underscore __
The double underscore is available in any server-side JavaScript code and is used for wrapping Java objects in a JavaScript object. Read more about the Java bridge.