Duktape built-ins

This section describes Duktape-specific built-in objects, methods, and values.

Additional global object properties

PropertyDescription
Duktape The Duktape built-in object. Contains miscellaneous implementation specific stuff.
Proxy Proxy constructor borrowed from ES6 (not part of Ecmascript E5/E5.1).
require Non-standard, CommonsJS module loading function.
print Non-standard, browser-like function for writing to stdout.
alert Non-standard, browser-like function for writing to stderr.

require()

CommonJS module loading function, see Modules.

print() and alert()

print() writes to stdout with an automatic flush afterwards. The bytes written depend on the arguments:

alert() behaves the same way, but writes to stderr. Unlike a browser alert(), the call does not block.

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.
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.
modSearch Module search function, must be provided by user code if using modules.
modLoaded Internal tracking table for loaded modules, maps resolved identifier to module metadata object.
Buffer Buffer constructor (function).
Pointer Pointer constructor (function).
Thread Thread constructor (function).
Logger Logger 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 buffer. For example:

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

If you wish to get back a string value, you can simply:

var result = String(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()

When given an arbitrary input value, Duktape.info() returns an array of values with internal information related to the value. The format of of the values in the array is version specific. This is mainly useful for debugging and diagnosis, e.g. when estimating rough memory usage of objects.

The current result array format is described in the table below. Notes:

Type0123456789
undefined type tag internal type tag - - - - - - - -
null type tag internal type tag - - - - - - - -
boolean type tag internal type tag - - - - - - - -
number type tag internal type tag - - - - - - - -
string type tag heap ptr refcount heap hdr size internal type tag - - - - -
object, Ecmascript function type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry next prop array count prop hash count func data size
object, Duktape/C function type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry next prop array count prop hash count -
object, thread type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry next prop array count prop hash count -
object, other type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry next prop array count prop hash count -
buffer, fixed type tag heap ptr refcount heap hdr size - - - - - -
buffer, dynamic type tag heap ptr refcount heap hdr size curr buf size - - - - -
buffer, external type tag heap ptr refcount heap hdr size curr buf size - - - - -
pointer type tag internal type tag - - - - - - - -
lightfunc type tag internal type tag - - - - - - - -

act()

Get information about a call stack entry. Takes a single number argument indicating depth in the call stack: -1 is the top entry, -2 is the one below that etc. Returns an object describing the call stack entry, or undefined if the entry doesn't exist. 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());
The properties provided for call stack entries may change between versions.

gc()

Trigger a forced mark-and-sweep collection. If mark-and-sweep is disabled, this call is a no-op.

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.

modSearch() and modLoaded

modSearch() is a module search function which must be provided by user code to support module loading. modLoaded is an internal module loading tracking table maintained by Duktape which maps a resolved absolute module identifier to the module's module object for modules which are either fully loaded or currently being loaded (module.exports is the exported value returned by require()).

See Modules for details.

Duktape.Buffer (constructor)

PropertyDescription
prototypePrototype for Buffer objects.

The Buffer constructor is a function which returns a plain buffer when called as a normal function and a Buffer object when called as a constructor. Otherwise the behavior is the same:

If the argument is a Node.js Buffer, ArrayBuffer, DataView, or a TypedArray, the call behaves as if the argument was a Duktape.Buffer, i.e. the underlying plain buffer is returned or promoted to a Duktape.Buffer. However, any slice byte offset/length information is ignored, so that the full underlying buffer is always returned.

Duktape.Buffer doesn't provide a way to make a copy of a buffer, but you can use the TypedArray bindings to do that: copy = Duktape.Buffer(new Uint8Array(new Duktape.Buffer(input))).

Duktape.Buffer.prototype

PropertyDescription
toStringConvert Buffer to a printable string.
valueOfReturn the primitive buffer value held by Buffer.

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

var plain_buf = Duktape.Buffer('test');
print(plain_buf.toString());

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.

Duktape.Logger (constructor)

PropertyDescription
prototypePrototype for Logger objects.
clogRepresentative logger for log entries written from C code.

Called as a constructor, creates a new Logger object with a specified name (first argument). If the name is omitted, Logger will automatically assign a name based on the calling function's fileName. If called as a normal function, throws a TypeError.

Logger instances have the following properties:

Tail calling might theoretically affect the automatic name assignment (i.e. when logger name argument is omitted). However, constructor calls are never converted to tail calls, so this is not a practical issue.

See Logging on how to use loggers.

Duktape.Logger.prototype

PropertyDescription
rawOutput a formatted log line (buffer value), by default writes to stderr.
fmtFormat a single (object) argument.
traceWrite a trace level (level 0, TRC) log entry.
debugWrite a debug level (level 1, DBG) log entry.
infoWrite an info level (level 2, INF) log entry.
warnWrite a warn level (level 3, WRN) log entry.
errorWrite an error level (level 4, ERR) log entry.
fatalWrite a fatal level (level 5, FTL) log entry.
lDefault log level, initial value is 2 (info).
nDefault logger name, initial value is "anon".