Duktape built-ins

This section summarizes Duktape-specific and non-Ecmascript built-in objects, methods, and values.

Additional global object properties

Property Description
global References the global object itself. See proposal-global.
Duktape The Duktape built-in object. Contains miscellaneous implementation specific stuff.
TextEncoder TextEncoder() from WHATWG Encoding API. Converts a string into a buffer using UTF-8 encoding.
TextDecoder TextDecoder() from WHATWG Encoding API. Converts a buffer into a string using UTF-8 encoding.

The Duktape object

PropertyDescription
version Duktape version number: (major * 10000) + (minor * 100) + patch.
env Cryptic, version dependent summary of most important effective options like endianness and architecture.
fin Set or get finalizer of an object.
enc Encode a value (hex, base-64, JX, JC): Duktape.enc('hex', 'foo').
dec Decode a value (hex, base-64, JX, JC): Duktape.dec('base64', 'Zm9v').
info Get internal information (such as heap address and alloc size) of a value in a version specific format. The C API equivalent is duk_inspect_value().
act Get information about call stack entry.
gc Trigger mark-and-sweep garbage collection.
compact Compact the memory allocated for a value (object).
errCreate Callback to modify/replace a created error.
errThrow Callback to modify/replace an error about to be thrown.
Pointer Pointer constructor (function).
Thread Thread constructor (function).

version

The version property allows version-based feature detection and behavior. Version numbers can be compared directly: a logically higher version will also be numerically higher. For example:

if (typeof Duktape !== 'object') {
    print('not Duktape');
} else if (Duktape.version >= 10203) {
    print('Duktape 1.2.3 or higher');
} else if (Duktape.version >= 800) {
    print('Duktape 0.8.0 or higher (but lower than 1.2.3)');
} else {
    print('Duktape lower than 0.8.0');
}

The value of version for pre-releases is one less than the actual release, e.g. 1199 for a 0.12.0 pre-release and 10299 for a 1.3.0 pre-release. See Versioning.

Remember to check for existence of Duktape when doing feature detection. Your code should typically work on as many engines as possible. Avoid the common pitfall of using a direct identifier reference in the check:

// Bad idea: ReferenceError if missing
if (!Duktape) {
    print('not Duktape');
}

// Better: check through 'this' (bound to global)
if (!this.Duktape) {
    print('not Duktape');
}

// Better: use typeof to check also type explicitly
if (typeof Duktape !== 'object') {
    print('not Duktape');
}

env

env summarizes the most important effective compile options in a version specific, quite cryptic manner. The format is version specific and is not intended to be parsed programmatically. This is mostly useful for developers (see duk_hthread_builtins.c for the code which sets the value).

Example from Duktape 1.1.0:

ll u n p2 a4 x64 linux gcc     // l|b|m integer endianness, l|b|m IEEE double endianness
                               // p|u packed/unpacked tval
                               // n|various, memory optimization options (n = none)
                               // p1|p2|p3 prop memory layout
                               // a1|a4|a8: align target
                               // x64|x86|arm|etc: architecture
                               // linux|windows|etc: operating system
                               // gcc|clang|msvc|etc: compiler

fin()

When called with a single argument, gets the current finalizer of an object:

var currFin = Duktape.fin(o);

When called with two arguments, sets the finalizer of an object (returns undefined):

Duktape.fin(o, function(x) { print('finalizer called'); });
Duktape.fin(o, undefined);  // disable

enc()

enc() encodes its argument value into chosen format. The first argument is a format (currently supported are "hex", "base64", "jx" and "jc"), second argument is the value to encode, and any further arguments are format specific.

For "hex" and "base64", buffer values are encoded as is, other values are string coerced and the internal byte representation (extended UTF-8) is then encoded. The result is a string. For example, to encode a string into base64:

var result = Duktape.enc('base64', 'foo');
print(result);  // prints 'Zm9v'

For "jx" and "jc" the argument list following the format name is the same as for JSON.stringify(): value, replacer (optional), space (optional). For example:

var result = Duktape.enc('jx', { foo: 123 }, null, 4);
print(result);  // prints JX encoded {foo:123} with 4-space indent

dec()

dec() provides the reverse function of enc().

For "hex" and "base64" the input value is first string coerced (it only really makes sense to decode strings). The result is always a plain buffer. For example:

var result = Duktape.dec('base64', 'Zm9v');
print(typeof result, result);  // prints 'object foo'

If you prefer a full Uint8Array over a plain buffer, you can coerce the result as follows:

var result = Object(Duktape.dec('base64', 'Zm9v'));
print(typeof result, result);  // prints 'object foo'

If you wish to get back a string value, you can coerce the plain buffer to a string e.g. as follows:

// Use TextDecoder which decodes the input as UTF-8.  You can also use
// the Node.js Buffer binding to achieve a similar result.

var result = new TextDecoder().decode(Duktape.dec('base64', 'Zm9v'));
print(typeof result, result);  // prints 'string foo'

For "jx" and "jc" the argument list following the format name is the same as for JSON.parse(): text, reviver (optional). For example:

var result = Duktape.dec('jx', "{foo:123}");
print(result.foo);  // prints 123

info()

Duktape.info() returns an object exposing internal information related to its argument value. See duk_inspect_value() for description of current fields.

The properties of the result object are not under versioning guarantees and may change in an incompatible fashion even in minor versions (but not patch versions).

act()

Get information about a call stack entry. Takes a single number argument indicating depth in the call stack: -1 is the top (innermost) entry, -2 is the one below that etc. Returns an object describing the call stack entry, or undefined if the entry doesn't exist. See duk_inspect_callstack_entry() for description of current fields.

The properties of the result object are not under versioning guarantees and may change in an incompatible fashion even in minor versions (but not patch versions).

Example:

function dump() {
    var i, t;
    for (i = -1; ; i--) {
        t = Duktape.act(i);
        if (!t) { break; }
        print(i, t.lineNumber, t.function.name, Duktape.enc('jx', t));
    }
}

dump();

The example, when executed with the command line tool, currently prints something like:

-1 0 act {lineNumber:0,pc:0,function:{_func:true}}
-2 4 dump {lineNumber:4,pc:16,function:{_func:true}}
-3 10 global {lineNumber:10,pc:5,function:{_func:true}}

The interesting entries are lineNumber and function which provides e.g. the function name.

You can also implement a helper to get the current line number using Duktape.act():

function getCurrentLine() {
    'use duk notail';

    /* Tail calls are prevented to ensure calling activation exists.
     * Call stack indices: -1 = Duktape.act, -2 = getCurrentLine, -3 = caller
     */

    var a = Duktape.act(-3) || {};
    return a.lineNumber;
}
print('running on line:', getCurrentLine());

gc()

Trigger a forced mark-and-sweep collection. The call takes an optional integer flags field, see duktape.h for constants.

compact()

Minimize the memory allocated for a target object. Same as the C API call duk_compact() but accessible from Ecmascript code. If called with a non-object argument, this call is a no-op. The argument value is returned by the function, which allows code such as:

var obj = {
    foo: Duktape.compact({ bar:123 })
}

This call is useful when you know that an object is unlikely to gain new properties, but you don't want to seal or freeze the object in case it does.

errCreate() and errThrow()

These can be set by user code to process/replace errors when they are created (errCreate) or thrown (errThrow). Both values are initially non-existent.

See Error handlers (errCreate and errThrow) for details.

Duktape.Pointer (constructor)

PropertyDescription
prototypePrototype for Pointer objects.

The Pointer constructor is a function which can be called both as an ordinary function and as a constructor:

Duktape.Pointer.prototype

PropertyDescription
toStringConvert Pointer to a printable string.
valueOfReturn the primitive pointer value held by Pointer.

toString() and valueOf accept both plain pointers and Pointer objects as their this binding. This allows code such as:

var plain_ptr = Duktape.Pointer({ test: 'object' });
print(plain_ptr.toString());

Duktape.Thread (constructor)

PropertyDescription
prototypePrototype for Thread objects.
resumeResume target thread with a value or an error. Arguments: target thread, value, flag indicating whether value is to be thrown (optional, default false).
yieldYield a value or an error from current thread. Arguments: value, flag indicating whether value is to be thrown (optional, default false).
currentGet currently running Thread object.

The Thread constructor is a function which can be called both as an ordinary function and as a constructor. The behavior is the same in both cases:

Duktape.Thread.prototype

PropertyDescription
No properties at the moment.

TextEncoder

TextEncoder() is part of the WHATWG Encoding API and provides a clean way of encoding a string into a buffer (Uint8Array) using UTF-8 encoding. Surrogate pairs are combined during the process. For example:

var str = '\u{1f4a9}';                   // non-BMP codepoint
print(str.length);                       // length is 2, represented as a surrogate pair
var u8 = new TextEncoder().encode(str);
print(u8.length);                        // length is 4, a single UTF-8 codepoint
print(Duktape.enc('jx', u8));            // |f09f92a9|, UTF-8 bytes F0 9F 92 A9

TextDecoder

TextDecoder() is part of the WHATWG Encoding API and provides a clean way of decoding a buffer into a string using UTF-8 encoding. Non-BMP codepoints are represented as surrogate pairs in the resulting string. For example:

var u8 = new Uint8Array([ 0xf0, 0x9f, 0x92, 0xa9 ]);  // a single non-BMP codepoint
var str = new TextDecoder().decode(u8);
print(str.length);                       // length is 2, represented as a surrogate pair
print(str.charCodeAt(0));                // 55357, high surrogate
print(str.charCodeAt(1));                // 56489, low surrogate