Loading TOC...
JavaScript Reference Guide (PDF)

JavaScript Reference Guide — Chapter 1

Server-Side JavaScript in MarkLogic

MarkLogic 9 integrates JavaScript as a first-class server-side programming language. You can call a JavaScript program from an App Server, and that program has server-side access to the MarkLogic built-in functions. This chapter describes the JavaScript implementation in MarkLogic and includes the following sections:

Google V8 JavaScript Engine

MarkLogic Server integrates the Google V8 JavaScript engine (https://code.google.com/p/v8/), a high-performance open source C++ implementation of JavaScript.

The version of V8 MarkLogic embeds is 4.6.88, with the following flags enabled:

  • --harmony Array.prototype.includes
  • --harmony toString
  • --harmony isConcatSpreadable
  • --harmony rest parameters

This version of V8 offers some of the newer EcmaScript 2015 (formerly known as EcmaScript 6) features. Some EcmaScript 15 features are:

  • Arrow Function
  • Spread Operator and rest Parameters
  • Maps and Sets
  • Classes
  • Constants and Block-Scoped Variables
  • Template Strings
  • Symbols

EcmaScript 2015 generators use the function* syntax. For a description of EcmaScript 6 generators, see documentation for implementation of generators such as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* and http://wiki.ecmascript.org/doku.php?id=harmony:generators. For generators, MarkLogic only supports the Generator.prototype.next() method (which the for ... of loop uses), not the Generator.prototype.return() and Generator.prototype.throw() methods.

The following is a simple JavaScript generator example to run in MarkLogic:

function* gen(limit){
  for (var i = 0; i < limit; i++)
    yield xdmp.eval('xs.dateTime(new Date())');}
var result=[];
for (var i of gen(10)){
/* returns ten different dateTime values (because they are each run
   in a separate eval) */

Familiarity For the JavaScript Developer

JavaScript as a programming language has become extremely popular, and it is familiar to a huge number of developers. Over the last several years, JavaScript has expanded its footprint from the browser to other programming environments like Node.js. MarkLogic Server-Side JavaScript expands that familiarity one level deeper into the database server level. This allows you to combine the power of programming at the database level with the familiarity of JavaScript.

Server-Side MarkLogic Power for Data Services

With JavaScript running within MarkLogic, you can do processing of your data right at the server level, without having to transfer the data to a middle tier. In MarkLogic, you have always been able to do this with XQuery. In MarkLogic 8, you can do that same processing using JavaScript, for which most organizations have a lot of experienced programers.

Dates in Server-Side JavaScript

MarkLogic has many XQuery functions that return date values, using W3C standard XML dates and durations. These functions are all available in Server-Side JavaScript, and their values are returned in the XML types.

For the return value from any of these functions, you can call toObject() and the date values are converted into JavaScript UTC dates. This way you can use the powerful XML date and duration functions if you want to, and you can combine that with any JavaScript handling of dates that you might prefer (or that you might already have JavaScript code to handle). For reference material on JavaScript Date functions, see any JavaScript reference (for example, Mozilla). For the MarkLogic Server-Side JavaScript date functions, see http://docs.marklogic.com/js/fn/dates.

Consider the following example:

var results = new Array();
var cdt = fn.currentDateTime();
var utc = cdt.toObject();

["2015-01-05T15:36:17.804712-08:00", "2015-01-05T23:36:17.804"]

In the above example, notice that the output from the cdt variable (the first item in the results array) retains the timezone information inherent in XML dateTime values. The output from the utc variable (the second item in the results array) no longer has the timezone shift, as it is now a UTC value.

Similarly, you can use any of the UTC methods on MarkLogic-based dates that are converted to objects, For example, the following returns the UTC month:

  .getMonth();  // note that the month is 0-based, so January is 0

The following returns the number of milliseconds since January 1, 1970:

var utc = fn.currentDateTime().toObject();
// => 1420502304000 (will be different for different times)

The flexibility to use JavaScript date functions when needed and XML/XQuery date functions when needed provides flexibility in how you use dates in Server-Side JavaScript.

Numeric Datatype Mappings in JavaScript

In Server-Side JavaScript, you have full access to all of the rich datatypes in MarkLogic, including the numeric datatypes. In general, Server-Side JavaScript maps numeric datatypes in MarkLogic to a JavaScript Number. There are a few cases, however, where MarkLogic wraps the number in a MarkLogic numeric type instead of returning a JavaScript Number. Those cases are:

  • If a value will overflow or might lose precision in a JavaScript Number, then MarkLogic wraps it in a numeric datatype (xs.decimal, for example).
  • If the returned value contains frequency information (for example, a numeric value returned from a search), then it is wrapped in a numeric type such as xs.integer, xs:double, or xs:float.
  • If the returned value is a JavaScript future, then MarkLogic wraps it in a numeric type.

JavaScript in Query Console

Query Console, which ships on port 8000 on default installations of MarkLogic, allows you to evaluate JavaScript using Server-Side JavaScript, making it is very easy to try out examples. For example, the following are each 'hello world' examples that you can run in Query Console by entering the following (with JavaScript selected as the Query Type):

"hello world"
fn.concat("hello ", "world")

Both return the string hello world. For details about Query Console, see the Query Console User Guide.

Programming in Server-Side JavaScript

When you put a JavaScript module under an App Server root with a sjs file extension, you can evaluate that module via HTTP from the App Server. For example, if you have an HTTP App Server with a root /space/appserver, and the port set to 1234, then you can save the following file as /space/appserver/my-js.sjs:


Evaluating this module in a browser pointed to http://localhost:1234/my-js.sjs (or substituting your hostname for localhost if your browser is on a different machine) returns the string hello.

You cannot serve up a Server-Side JavaScript module with a .js file extension (application/javascript mimetype) directly from the App Server; directly served modules need a .sjs extension (application/vnd.marklogic-javascript mimetype). You can import JavaScript libraries with either extension, however, as described in Importing JavaScript Modules Into JavaScript Programs.

Using xdmp.invoke or xdmp.invokeFunction for Scripting

If you want to have a single program that does some scripting of tasks, where one task relies on updates from the previous tasks, you can create a JavaScript module that uses xdmp.invoke or xdmp.invokeFunction, where the calls to xdmp.invoke or xdmp.invokeFunction have options to make their contents evaluate in a separate transaction.

Exception Handling

If you are accustomed to working with XQuery or you are developing in both XQuery and Server-Side JavaScript, you should be aware that the semantics of exception handling are not the same in the two languages.

MarkLogic implements the standard exception handling semantics for JavaScript: JavaScript statements in a try block are not rolled back if they complete before a caught exception is raised. In XQuery, all expressions evaluated in a try block are rolled back, even if the exception is caught.

For example, in the following code, the call to xdmp.documentSetMetadata data throws an XDMP-CONFLICTINGUPDATES exception because it tries to update the document metadata twice in the same transaction. The exception is trapped by the try-catch. The initial document insert succeeds because it was evaluated before the exception occurs.

'use strict';

                      {content :"value"},
                      {metadata:{a:1, b:2}})
  xdmp.documentSetMetadata("doc.json", {c:3})
} catch(err) {  

The equivalent XQuery code would not insert "doc.json". For more details, see try/catch Expression in the XQuery and XSLT Reference Guide.

« Table of contents
Next chapter »
Powered by MarkLogic Server 7.0-4.1 and rundmc | Terms of Use | Privacy Policy