Global-Object.require

Global-Object.require(
   location as String
) as Object

Summary

Imports a module at the specified location, and returns a JavaScript object.

Parameters
location Location of the module to import.

Usage Notes

The location of the module is resolved with the same rules that MarkLogic resolves imported modules in XQuery.

If the document with the user-specified module name does not end with a file extension, require() will first look for the module with the user- specified name appended with the configured extensions for JavaScript module, and then appended with the configured extensions for XQuery module.

If the user specified module's file extension does not match any of the module path extension found in the MIME type configuration, JS-ILLEGALMODULEPATH is thrown.

If the user does not have execute permission on an existing module, the above logic to resolve a module name applies as if the module is not found and XDMP-MODNOTFOUND is thrown if the module cannot be located.

Once a module is located, its query language is determined to be XQuery if its name extension matches with any for the XQuery module; otherwise, it is imported as a JavaScript module.

If the imported module is in XQuery, the public functions and variables defined in it are available through the returned JavaScript object as properties, with either the original function name as the property name, or with "-" in the function names removed and the following letter capitalized.

In the case where a namespace is shared between built-in functions and XQuery modules (e.g., http://marklogic.com/xdmp/spell), the returned JavaScript object can be used to access both the built-ins and the XQuery functions. The lookup sequence is function name, followed by variable name then built-in name.

If the imported module is in JavaScript, the exported API of the module defined through exports or module.exports object is returned.

You can import JavaScript libraries with either the .js or .sjs extension (with corresponding mimetypes application/javascript and application/vnd.marklogic-javascript).

If there is a dependency cycle, the foreign module may not have finished executing at the time it is required by one of its transitive dependencies; in this case, the object returned by "require" must contain at least the exports that the foreign module has prepared before the call to require that led to the current module's execution.

Example

  lib.sjs:
  const PI = Math.PI;
  exports.area = function area(r) {
    return PI * r * r;
  };
  Test.js
  const circle = require("lib");
  circle.area(2);

Example

  const admin = require("/MarkLogic/admin");
  const conf = admin.getConfiguration();
  admin.forestGetId(conf, "Documents");
Powered by MarkLogic Server | Terms of Use | Privacy Policy