NJS API Reference#

The NJS module provides objects, methods, and properties for extending Angie functionality.

This reference contains only NJS-specific properties, methods, and modules not compliant with ECMAScript. Definitions of NJS properties and methods compliant with ECMAScript can be found in ECMAScript specification.

Angie Objects#

HTTP Request#

  • r.args{}

  • r.done()

  • r.error()

  • r.finish()

  • r.headersIn{}

  • r.headersOut{}

  • r.httpVersion

  • r.internal

  • r.internalRedirect()

  • r.log()

  • r.method

  • r.parent

  • r.remoteAddress

  • r.requestBody

  • r.requestBuffer

  • r.requestText

  • r.rawHeadersIn[]

  • r.rawHeadersOut[]

  • r.responseBody

  • r.responseBuffer

  • r.responseText

  • r.return()

  • r.send()

  • r.sendBuffer()

  • r.sendHeader()

  • r.setReturnValue()

  • r.status

  • r.subrequest()

  • r.uri

  • r.rawVariables{}

  • r.variables{}

  • r.warn()

The HTTP request object is available only in the HTTP JS module. Before 0.8.5, all string properties of the object were byte strings.

r.args{}

Request arguments object, read-only.

The query string is returned as an object. Since 0.7.6, duplicate keys are returned as an array, keys are case-sensitive, both keys and values are percent-decoded.

For example, the query string

a=1&b=%32&A=3&b=4&B=two%20words

is converted to r.args as:

{a: "1", b: ["2", "4"], A: "3", B: "two words"}

More advanced parsing scenarios can be achieved with the Query String module and with the $args variable, for example:

import qs from 'querystring';

function args(r) {
    return qs.parse(r.variables.args);
}

The argument object is evaluated at the first access to r.args. If only a single argument is needed, for example foo, Angie variables can be used:

r.variables.arg_foo

Here, Angie variables object returns the first value for a given key, case-insensitive, without percent-decoding.

To convert r.args back to a string, the Query String stringify method can be used.

r.done()

After calling this function, the next data chunks will be passed to the client without calling js_body_filter (0.5.2). May be called only from the js_body_filter function.

r.error(string)

Writes a string to the error log on the error level of logging.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

r.finish()

Finishes sending a response to the client.

r.headersIn{}

Incoming headers object, read-only.

The Foo request header can be accessed with the syntax: headersIn.foo or headersIn['Foo'].

The Authorization, Content-Length, Content-Range, Content-Type, ETag, Expect, From, Host, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Max-Forwards, Proxy-Authorization, Referer, Transfer-Encoding, and User-Agent request headers can have only one field value (0.4.1). Duplicate field values in Cookie headers are separated by semicolon (;). Duplicate field values in all other request headers are separated by commas.

r.headersOut{}

Outgoing headers object for the main request, writable.

If r.headersOut{} is the response object of a subrequest, it represents response headers. In this case, field values in Accept-Ranges, Connection, Content-Disposition, Content-Encoding, Content-Length, Content-Range, Date, Keep-Alive, Server, Transfer-Encoding, X-Accel-* response headers may be omitted.

The Foo response header can be accessed with the syntax: headersOut.foo or headersOut['Foo'].

Outgoing headers should be set before a response header is sent to a client; otherwise, the header update will be ignored. This means that r.headersOut{} is effectively writable in:

  • the js_content handler before r.sendHeader() or r.return() are called

  • the js_header_filter handler

Field values of multi-value response headers (0.4.0) can be set with the syntax:

r.headersOut['Foo'] = ['a', 'b']

where the output will be:

Foo: a
Foo: b

All previous field values of the Foo response header will be deleted.

For standard response headers that accept only a single field value such as Content-Type, only the last element of the array will take effect. Field values of the Set-Cookie response header are always returned as an array. Duplicate field values in Age, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Retry-After response headers are ignored. Duplicate field values in all other response headers are separated by commas.

r.httpVersion

HTTP version, read-only.

r.internal

Boolean value, true for internal locations.

r.internalRedirect(uri)

Performs an internal redirect to the specified uri. If the URI starts with the @ prefix, it is considered a named location. In a new location, all request processing is repeated starting from NGX_HTTP_SERVER_REWRITE_PHASE for ordinary locations and from NGX_HTTP_REWRITE_PHASE for named locations. As a result, a redirect to a named location does not check the client_max_body_size limit. Redirected requests become internal and can access internal locations. The actual redirect happens after the handler execution is completed.

Note

After redirect, a new NJS VM is started in the target location, and the VM in the original location is stopped. Values of Angie variables are kept and can be used to pass information to the target location. Since 0.5.3, the variable declared with the js_var directive for HTTP or Stream can be used.

Note

Since 0.7.4, the method accepts escaped URIs.

r.log(string)

Writes a string to the error log on the info level of logging.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

r.method

HTTP method, read-only.

r.parent

References the parent request object.

r.remoteAddress

Client address, read-only.

r.requestBody

The property was made obsolete in 0.5.0 and was removed in 0.8.0. The r.requestBuffer or r.requestText property should be used instead.

r.requestBuffer

Client request body if it has not been written to a temporary file (since 0.5.0). To ensure that the client request body is in memory, its size should be limited by client_max_body_size, and a sufficient buffer size should be set using client_body_buffer_size. The property is available only in the js_content directive.

r.requestText

The same as r.requestBuffer, but returns a string. Note that it may convert bytes invalid in UTF-8 encoding into the replacement character.

r.rawHeadersIn[]

Returns an array of key-value pairs exactly as they were received from the client (0.4.1).

For example, with the following request headers:

Host: localhost
Foo:  bar
foo:  bar2

the output of r.rawHeadersIn will be:

[
    ['Host', 'localhost'],
    ['Foo', 'bar'],
    ['foo', 'bar2']
]

All foo headers can be collected with the syntax:

r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1])

the output will be:

['bar', 'bar2']

Header field names are not converted to lower case, duplicate field values are not merged.

r.rawHeadersOut[]

Returns an array of key-value pairs of response headers (0.4.1). Header field names are not converted to lower case, duplicate field values are not merged.

r.responseBody

The property was made obsolete in 0.5.0 and was removed in 0.8.0. The r.responseBuffer or the r.responseText property should be used instead.

r.responseBuffer

Holds the subrequest response body, read-only (since 0.5.0). The size of r.responseBuffer is limited by the subrequest_output_buffer_size directive.

r.responseText

The same as r.responseBuffer but returns a string (since 0.5.0). Note that it may convert bytes invalid in UTF-8 encoding into the replacement character.

r.return(status[, string | Buffer])

Sends the entire response with the specified status to the client. The response can be a string or Buffer (0.5.0).

It is possible to specify either a redirect URL (for codes 301, 302, 303, 307, and 308) or the response body text (for other codes) as the second argument.

r.send(string | Buffer)

Sends a part of the response body to the client. The data sent can be a string or Buffer (0.5.0).

r.sendBuffer(data[, options])

Adds data to the chain of data chunks to be forwarded to the next body filter (0.5.2). The actual forwarding happens later, when all the data chunks of the current chain are processed.

The data can be a string or Buffer. The options is an object used to override Angie buffer flags derived from an incoming data chunk buffer. The flags can be overridden with the following flags:

last

Boolean, true if the buffer is the last buffer.

flush

Boolean, true if the buffer should have the flush flag.

The method may be called only from the js_body_filter function.

r.sendHeader()

Sends the HTTP headers to the client.

r.setReturnValue(value)

Sets the return value of the js_set handler (0.7.0). Unlike an ordinary return statement, this method should be used when the handler is a JS async function. For example:

async function js_set(r) {
    const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host);
    r.setReturnValue(digest);
}
r.status

Status, writable.

r.subrequest(uri[, options[, callback]])

Creates a subrequest with the given uri and options, and installs an optional completion callback.

A subrequest shares its input headers with the client request. To send headers different from original headers to a proxied server, the proxy_set_header directive can be used. To send a completely new set of headers to a proxied server, the proxy_pass_request_headers directive can be used.

If options is a string, then it holds the subrequest arguments string. Otherwise, options is expected to be an object with the following keys:

args

Arguments string, by default an empty string is used.

body

Request body, by default the request body of the parent request object is used.

method

HTTP method, by default the GET method is used.

detached

Boolean flag (0.3.9); if true, the created subrequest is a detached subrequest. Responses to detached subrequests are ignored. Unlike ordinary subrequests, a detached subrequest can be created inside a variable handler. The detached flag and callback argument are mutually exclusive.

The completion callback receives a subrequest response object with methods and properties identical to the parent request object.

Since 0.3.8, if a callback is not provided, the Promise object that resolves to the subrequest response object is returned.

For example, to view all response headers in the subrequest:

async function handler(r) {
    const reply = await r.subrequest('/path');

    for (const h in reply.headersOut) {
        r.log(`${h}: ${reply.headersOut[h]}`);
    }

    r.return(200);
}
r.uri

Current URI in request, normalized, read-only.

r.rawVariables{}

Angie variables as Buffers, writable (since 0.5.0).

r.variables{}

Angie variables object, writable (since 0.2.8).

For example, to get the $foo variable, one of the following syntax can be used:

r.variables['foo']
r.variables.foo

Since 0.8.6, regular expression captures can be accessed using the following syntax:

r.variables['1']
r.variables[1]

Angie treats variables referenced in angie.conf and unreferenced variables differently. When a variable is referenced, it may be cacheable, but when it is unreferenced, it is always uncacheable. For example, when the $request_id variable is only accessed from NJS, it has a new value every time it is evaluated. But, when the $request_id is referenced, for example:

proxy_set_header X-Request-Id $request_id;

the r.variables.request_id returns the same value every time.

A variable is writable if:

  • it was created using the js_var directive for HTTP or Stream (since 0.5.3)

  • it is referenced in Angie configuration file

Even so, some embedded variables still cannot be assigned a value (for example, $http_).

r.warn(string)

Writes a string to the error log on the warning level of logging.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

Stream Session#

  • s.allow()

  • s.decline()

  • s.deny()

  • s.done()

  • s.error()

  • s.log()

  • s.off()

  • s.on()

  • s.remoteAddress

  • s.rawVariables{}

  • s.send()

  • s.sendDownstream()

  • s.sendUpstream()

  • s.status

  • s.setReturnValue()

  • s.variables{}

  • s.warn()

The stream session object is available only in the Stream JS module. Before 0.8.5, all string properties of the object were byte strings.

s.allow()

An alias to s.done(0) (0.2.4).

s.decline()

An alias to s.done(-5) (0.2.4).

s.deny()

An alias to s.done(403) (0.2.4).

s.done([code])

Sets an exit code for the current phase handler to a code value, by default 0. The actual finalization happens when the js handler is completed and all pending events, for example, from ngx.fetch() or setTimeout(), are processed (0.2.4).

Possible code values:

  • 0 — successful finalization, passing control to the next phase

  • -5 — undecided, passing control to the next handler of the current phase (if any)

  • 403 — access is forbidden

May be called only from a phase handler function: js_access or js_preread.

s.error(string)

Writes a sent string to the error log on the error level of logging.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

s.log(string)

Writes a sent string to the error log on the info level of logging.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

s.off(eventName)

Unregisters the callback set by the s.on() method (0.2.4).

s.on(event, callback)

Registers a callback for the specified event (0.2.4).

An event may be one of the following strings:

upload

New data (string) from a client.

download

New data (string) to a client.

upstream

New data (Buffer) from a client (since 0.5.0).

downstream

New data (Buffer) to a client (since 0.5.0).

The completion callback has the following prototype: callback(data, flags), where data is string or Buffer (depending on the event type); flags is an object with the following properties:

last

A boolean value, true if data is a last buffer.

s.remoteAddress

Client address, read-only.

s.rawVariables

Angie variables as Buffers, writable (since 0.5.0).

s.send(data[, options])

Adds data to the chain of data chunks that will be forwarded in the forward direction: in download callback to a client; in upload to an upstream server (0.2.4). The actual forwarding happens later, when all the data chunks of the current chain are processed.

The data can be a string or Buffer (0.5.0). The options is an object used to override Angie buffer flags derived from an incoming data chunk buffer. The flags can be overridden with the following flags:

last

Boolean, true if the buffer is the last buffer.

flush

Boolean, true if the buffer should have the flush flag.

The method can be called multiple times per callback invocation.

s.sendDownstream()

Identical to s.send(), except for it always sends data to a client (since 0.7.8).

s.sendUpstream()

Identical to s.send(), except for it always sends data from a client (since 0.7.8).

s.status

Session status code, an alias to the $status variable, read-only (since 0.5.2).

s.setReturnValue(value)

Sets the return value of the js_set handler (0.7.0). Unlike an ordinary return statement, this method should be used when the handler is a JS async function. For example:

async function js_set(r) {
    const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host);
    r.setReturnValue(digest);
}
s.variables{}

Angie variables object, writable (since 0.2.8). A variable can be writable only if it is referenced in Angie configuration file. Even so, some embedded variables still cannot be assigned a value.

s.warn(string)

Writes a sent string to the error log on the warning level of logging.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

Periodic Session#

  • PeriodicSession.rawVariables{}

  • PeriodicSession.variables{}

The Periodic Session object is provided as the first argument for the js_periodic handler for HTTP and Stream (since 0.8.1).

PeriodicSession.rawVariables{}

Angie variables as Buffers, writable.

PeriodicSession.variables{}

Angie variables object, writable.

Headers#

  • Headers()

  • Headers.append()

  • Headers.delete()

  • Headers.get()

  • Headers.getAll()

  • Headers.forEach()

  • Headers.has()

  • Headers.set()

The Headers interface of the Fetch API is available since 0.5.1.

A new Headers object can be created using the Headers() constructor (since 0.7.10):

Headers([init])
init

An object containing HTTP headers for prepopulating the Headers object, can be a string, an array of name-value pairs, or an existing Headers object.

A new Headers object can be created with the following properties and methods:

append()

Appends a new value into an existing header in the Headers object, or adds the header if it does not already exist (since 0.7.10).

delete()

Deletes a header from the Headers object (since 0.7.10).

get()

Returns a string containing the values of all headers with the specified name separated by a comma and a space.

getAll(name)

Returns an array containing the values of all headers with the specified name.

forEach()

Executes a provided function once for each key/value pair in the Headers object (since 0.7.10).

has()

Returns a boolean value indicating whether a header with the specified name exists.

set()

Sets a new value for an existing header inside the Headers object, or adds the header if it does not already exist (since 0.7.10).

Request#

  • Request()

  • Request.arrayBuffer()

  • Request.bodyUsed

  • Request.cache

  • Request.credentials

  • Request.headers

  • Request.json()

  • Request.method

  • Request.mode

  • Request.text()

  • Request.url

The Request interface of the Fetch API is available since 0.7.10.

A new Request object can be created using the Request() constructor:

Request[resource[, options]])

Creates a Request object to fetch that can be passed later to ngx.fetch(). The resource can be a URL or an existing Request object. The options is an optional argument that is expected to be an object with the following keys:

body

The request body, by default is empty.

headers

The response headers object — the object containing HTTP headers for prepopulating the Headers object, can be a string, an array of name-value pairs, or an existing Headers object.

method

The HTTP method, by default the GET method is used.

A new Request object can be created with the following properties and methods:

arrayBuffer()

Returns a Promise that resolves with an ArrayBuffer.

bodyUsed

A boolean value, true if the body was used in the request.

cache

Contains the cache mode of the request.

credentials

Contains the credentials of the request, by default is same-origin.

headers

The Headers read-only object associated with the Request.

json()

Returns a Promise that resolves with the result of parsing the request body as JSON.

method

Contains the request method.

mode

Contains the mode of the request.

text()

Returns a Promise that resolves with a string representation of the request body.

url

Contains the URL of the request.

Response#

  • Response()

  • Response.arrayBuffer()

  • Response.bodyUsed

  • Response.headers

  • Response.json()

  • Response.ok

  • Response.redirected

  • Response.status

  • Response.statusText

  • Response.text()

  • Response.type

  • Response.url

The Response interface is available since 0.5.1.

A new Response object can be created using the Response() constructor (since 0.7.10):

Response[body[, options]])

Creates a Response object. The body is an optional argument, can be a string or a buffer, by default is null. The options is an optional argument that is expected to be an object with the following keys:

headers

The response headers object — the object containing HTTP headers for prepopulating the Headers object, can be a string, an array of name-value pairs, or an existing Headers object.

status

The status code of the response.

statusText

The status message corresponding to the status code.

A new Response() object can be created with the following properties and methods:

arrayBuffer()

Takes a Response stream and reads it to completion. Returns a Promise that resolves with an ArrayBuffer.

bodyUsed

A boolean value, true if the body was read.

headers

The Headers read-only object associated with the Response.

json()

Takes a Response stream and reads it to completion. Returns a Promise that resolves with the result of parsing the body text as JSON.

ok

A boolean value, true if the response was successful (status codes between 200–299).

redirected

A boolean value, true if the response is the result of a redirect.

status

The status code of the response.

statusText

The status message corresponding to the status code.

text()

Takes a Response stream and reads it to completion. Returns a Promise that resolves with a string.

type

The type of the response.

url

The URL of the response.

ngx#

  • ngx.build

  • ngx.conf_file_path

  • ngx.conf_prefix

  • ngx.error_log_path

  • ngx.fetch()

  • ngx.log()

  • ngx.prefix

  • ngx.version

  • ngx.version_number

  • ngx.worker_id

The ngx global object is available since 0.5.0.

ngx.build

A string containing an optional Angie build name, corresponds to the --build=name argument of the configure script, by default is "" (0.8.0).

ngx.conf_file_path

A string containing the file path to current Angie configuration file (0.8.0).

ngx.conf_prefix

A string containing the file path to Angie configuration prefix — the directory where Angie is currently looking for configuration (0.7.8).

ngx.error_log_path

A string containing the file path to the current error log file (0.8.0).

ngx.fetch(resource, [options])

Makes a request to fetch a resource (0.5.1), which can be a URL or the Request object (0.7.10). Returns a Promise that resolves with the Response object. Since 0.7.0, the https:// scheme is supported; redirects are not handled.

If the URL in the resource is specified as a domain name, it is determined using a resolver. If the https:// scheme is specified, the js_fetch_trusted_certificate directive should be configured for the authentication of the resource's HTTPS server.

The options parameter is expected to be an object with the following keys:

body

Request body, by default is empty.

buffer_size

The buffer size for reading the response, by default is 4096.

headers

Request headers object.

max_response_body_size

The maximum size of the response body in bytes, by default is 32768.

method

HTTP method, by default the GET method is used.

verify

Enables or disables verification of the HTTPS server certificate, by default is true (0.7.0).

Example:

let reply = await ngx.fetch('http://example.com/');
let body = await reply.text();

r.return(200, body);
ngx.log(level, message)

Writes a message to the error log with the specified level of logging. The level parameter specifies one of the log levels; the message parameter can be a string or Buffer. The following log levels can be specified: ngx.INFO, ngx.WARN, and ngx.ERR.

Note

As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

ngx.prefix

A string containing the file path to Angie prefix — a directory that keeps server files (0.8.0).

ngx.version

A string containing Angie version, for example: 1.25.0 (0.8.0).

ngx.version_number

A number containing Angie version, for example: 1025000 (0.8.0).

ngx.worker_id

A number that corresponds to Angie internal worker ID, the value is between 0 and the value specified in the worker_processes directive (0.8.0).

ngx.shared#

The ngx.shared global object is available since 0.8.0.

SharedDict#

  • ngx.shared.SharedDict.add()

  • ngx.shared.SharedDict.capacity

  • ngx.shared.SharedDict.clear()

  • ngx.shared.SharedDict.delete()

  • ngx.shared.SharedDict.freeSpace()

  • ngx.shared.SharedDict.get()

  • ngx.shared.SharedDict.has()

  • ngx.shared.SharedDict.incr()

  • ngx.shared.SharedDict.items()

  • ngx.shared.SharedDict.keys()

  • ngx.shared.SharedDict.name

  • ngx.shared.SharedDict.pop()

  • ngx.shared.SharedDict.replace()

  • ngx.shared.SharedDict.set()

  • ngx.shared.SharedDict.size()

  • ngx.shared.SharedDict.type

The shared dictionary object is available since 0.8.0. The shared dictionary name, type, and size are set with the js_shared_dict_zone directive in HTTP or Stream.

A SharedDict() object has the following properties and methods:

ngx.shared.SharedDict.add(key, value [,timeout])

Sets the value for the specified key in the dictionary only if the key does not exist yet. The key is a string representing the key of the item to add; the value is the value of the item to add.

The optional timeout argument is specified in milliseconds and overrides the timeout parameter of the js_shared_dict_zone directive in HTTP or Stream (since 0.8.5). It can be useful when some keys are expected to have unique timeouts.

Returns true if the value has been successfully added to the SharedDict dictionary; false if the key already exists in the dictionary. Throws SharedMemoryError if there is not enough free space in the SharedDict dictionary. Throws TypeError if the value is of a different type than expected by this dictionary.

ngx.shared.SharedDict.capacity

Returns the capacity of the SharedDict dictionary, corresponds to the size parameter of js_shared_dict_zone directive in HTTP or Stream.

ngx.shared.SharedDict.clear()

Removes all items from the SharedDict dictionary.

ngx.shared.SharedDict.delete(key)

Removes the item associated with the specified key from the SharedDict dictionary; true if the item in the dictionary existed and was removed, false otherwise.

ngx.shared.SharedDict.freeSpace()

Returns the free page size in bytes. If the size is zero, the SharedDict dictionary will still accept new values if there is space in the occupied pages.

ngx.shared.SharedDict.get(key)

Retrieves the item by its key; returns the value associated with the key or undefined if there is none.

ngx.shared.SharedDict.has(key)

Searches for an item by its key; returns true if such item exists or false otherwise.

ngx.shared.SharedDict.incr(key,delta[[,init], timeout])

Increments the integer value associated with the key by delta. The key is a string; the delta is the number to increment or decrement the value by. If the key does not exist, the item will be initialized to an optional init argument, by default is 0.

The optional timeout argument is specified in milliseconds and overrides the timeout parameter of the js_shared_dict_zone directive in HTTP or Stream (since 0.8.5). It can be useful when some keys are expected to have unique timeouts.

Returns the new value. Throws SharedMemoryError if there is not enough free space in the SharedDict dictionary. Throws TypeError if this dictionary does not expect numbers.

Note

This method can be used only if the dictionary type was declared with type=number parameter of the js_shared_dict_zone directive in HTTP or Stream.

ngx.shared.SharedDict.items([maxCount])

Returns an array of the SharedDict dictionary key-value items (since 0.8.1). The maxCount parameter sets the maximum number of items to retrieve, by default is 1024.

ngx.shared.SharedDict.keys([maxCount])

Returns an array of the SharedDict dictionary keys. The maxCount parameter sets the maximum number of keys to retrieve, by default is 1024.

ngx.shared.SharedDict.name

Returns the name of the SharedDict dictionary, corresponds to the zone= parameter of js_shared_dict_zone directive in HTTP or Stream.

ngx.shared.SharedDict.pop(key)

Removes the item associated with the specified key from the SharedDict dictionary; returns the value associated with the key or undefined if there is none.

ngx.shared.SharedDict.replace(key, value)

Replaces the value for the specified key only if the key already exists; returns true if the value was successfully replaced, false if the key does not exist in the SharedDict dictionary. Throws SharedMemoryError if there is not enough free space in the SharedDict dictionary. Throws TypeError if the value is of a different type than expected by this dictionary.

ngx.shared.SharedDict.set(key, value [,timeout])

Sets the value for the specified key; returns this SharedDict dictionary (for method chaining).

The optional timeout argument is specified in milliseconds and overrides the timeout parameter of the js_shared_dict_zone directive in HTTP or Stream (since 0.8.5). It can be useful when some keys are expected to have unique timeouts.

ngx.shared.SharedDict.size()

Returns the number of items for the SharedDict dictionary.

ngx.shared.SharedDict.type

Returns string or number that corresponds to the SharedDict dictionary type set by the type= parameter of js_shared_dict_zone directive in HTTP or Stream.

Built-in Objects#

console#

  • console.error()

  • console.info()

  • console.log()

  • console.time()

  • console.timeEnd()

  • console.warn()

The console object is available in Angie since 0.8.2, in CLI since 0.2.6.

console.error(msg[, msg2 ...])

Outputs one or more error messages. The message may be a string or an object.

console.info(msg[, msg2 ...])

Outputs one or more info messages. The message may be a string or an object.

console.log(msg[, msg2 ...])

Outputs one or more log messages. The message may be a string or an object.

console.time(label)

Starts a timer that can track how long an operation takes. The label parameter allows naming different timers. If console.timeEnd() with the same name is called, the time that elapsed since the timer was started will be output, in milliseconds.

console.timeEnd(label)

Stops a timer previously started by console.time(). The label parameter allows naming different timers.

console.warn(msg[, msg2 ...])

Outputs one or more warning messages. The message may be a string or an object.

crypto#

  • crypto.getRandomValues()

  • crypto.subtle.encrypt()

  • crypto.subtle.decrypt()

  • crypto.subtle.deriveBits()

  • crypto.subtle.deriveKey()

  • crypto.subtle.digest()

  • crypto.subtle.exportKey()

  • crypto.subtle.generateKey()

  • crypto.subtle.importKey()

  • crypto.subtle.sign()

  • crypto.subtle.verify()

The crypto object is a global object that allows using cryptographic functionality (since 0.7.0).

crypto.getRandomValues(typedArray)

Gets cryptographically strong random values. Returns the same array passed as typedArray but with its contents replaced with the newly generated random numbers. Possible values:

typedArray

Can be Int8Array, Int16Array, Uint16Array, Int32Array, or Uint32Array.

crypto.subtle.encrypt(algorithm, key, data)

Encrypts data using the provided algorithm and key. Returns a Promise that fulfills with an ArrayBuffer containing the ciphertext. Possible values:

algorithm

An object that specifies the algorithm to be used and any extra parameters if required:

  • For RSA-OAEP, pass the object with the following keys:

    name

    A string, should be set to RSA-OAEP:

    crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
    
  • For AES-CTR, pass the object with the following keys:

    name

    A string, should be set to AES-CTR.

    counter

    An ArrayBuffer, TypedArray, or DataView — the initial value of the counter block, must be 16 bytes long (the AES block size). The rightmost length bits of this block are used for the counter, and the rest is used for the nonce. For example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter.

    length

    The number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap.

  • For AES-CBC, pass the object with the following keys:

    name

    A string, should be set to AES-CBC.

    iv

    Or the initialization vector, is an ArrayBuffer, TypedArray, or DataView, must be 16 bytes, unpredictable, and preferably cryptographically random. However, it need not be secret, for example, it may be transmitted unencrypted along with the ciphertext.

  • For AES-GCM, pass the object with the following keys:

    name

    A string, should be set to AES-GCM.

    iv

    Or the initialization vector, is an ArrayBuffer, TypedArray, or DataView, must be 16 bytes, and must be unique for every encryption operation carried out with a given key.

    additionalData

    (optional) is an ArrayBuffer, TypedArray, or DataView that contains additional data that will not be encrypted but will be authenticated along with the encrypted data. If additionalData is specified, then the same data must be specified in the corresponding call to decrypt(): if the data given to the decrypt() call does not match the original data, the decryption will throw an exception. The bit length of additionalData must be smaller than 2^64 - 1.

    tagLength

    (optional, default is 128) - a number that determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption. Possible values: 32, 64, 96, 104, 112, 120, or 128. The AES-GCM specification recommends that it should be 96, 104, 112, 120, or 128, although 32 or 64 bits may be acceptable in some applications.

key

A CryptoKey that contains the key to be used for encryption.

data

An ArrayBuffer, TypedArray, or DataView that contains the data to be encrypted (also known as the plaintext).

crypto.subtle.decrypt(algorithm, key, data)

Decrypts encrypted data. Returns a Promise with the decrypted data. Possible values:

algorithm

An object that specifies the algorithm to be used, and any extra parameters as required. The values given for the extra parameters must match those passed into the corresponding encrypt() call.

  • For RSA-OAEP, pass the object with the following keys:

    name

    A string, should be set to RSA-OAEP:

    crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
    
  • For AES-CTR, pass the object with the following keys:

    name

    A string, should be set to AES-CTR.

    counter

    An ArrayBuffer, TypedArray, or DataView — the initial value of the counter block, must be 16 bytes long (the AES block size). The rightmost length bits of this block are used for the counter, and the rest is used for the nonce. For example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter.

    length

    The number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap.

  • For AES-CBC, pass the object with the following keys:

    name

    A string, should be set to AES-CBC.

    iv

    Or the initialization vector, is an ArrayBuffer, TypedArray, or DataView, must be 16 bytes, unpredictable, and preferably cryptographically random. However, it need not be secret (for example, it may be transmitted unencrypted along with the ciphertext).

  • For AES-GCM, pass the object with the following keys:

    name

    A string, should be set to AES-GCM.

    iv

    Or the initialization vector, is an ArrayBuffer, TypedArray, or DataView, must be 16 bytes, and must be unique for every encryption operation carried out with a given key.

    additionalData

    (optional) is an ArrayBuffer, TypedArray, or DataView that contains additional data that will not be encrypted but will be authenticated along with the encrypted data. If additionalData is specified, then the same data must be specified in the corresponding call to decrypt(): if the data given to the decrypt() call does not match the original data, the decryption will throw an exception. The bit length of additionalData must be smaller than 2^64 - 1.

    tagLength

    (optional, default is 128) - a number that determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption. Possible values: 32, 64, 96, 104, 112, 120, or 128. The AES-GCM specification recommends that it should be 96, 104, 112, 120, or 128, although 32 or 64 bits may be acceptable in some applications.

key

A CryptoKey that contains the key to be used for decryption. If RSA-OAEP is used, this is the privateKey property of the CryptoKeyPair object.

data

An ArrayBuffer, TypedArray, or DataView that contains the data to be decrypted (also known as ciphertext).

crypto.subtle.deriveBits(algorithm, baseKey, length)

Derives an array of bits from a base key. Returns a Promise which will be fulfilled with an ArrayBuffer that contains the derived bits. Possible values:

algorithm

Is an object that defines the derivation algorithm to use:

  • For HKDF, pass the object with the following keys:

    name

    A string, should be set to HKDF.

    hash

    A string with the digest algorithm to use: SHA-1, SHA-256, SHA-384, or SHA-512.

    salt

    An ArrayBuffer, TypedArray, or DataView that represents random or pseudo-random value with the same length as the output of the digest function. Unlike the input key material passed into deriveKey(), salt does not need to be kept secret.

    info

    An ArrayBuffer, TypedArray, or DataView that represents application-specific contextual information used to bind the derived key to an application or context, and enables deriving different keys for different contexts while using the same input key material. This property is required but may be an empty buffer.

  • For PBKDF2, pass the object with the following keys:

    name

    A string, should be set to PBKDF2.

    hash

    A string with the digest algorithm to use: SHA-1, SHA-256, SHA-384, or SHA-512.

    salt

    An ArrayBuffer, TypedArray, or DataView that represents random or pseudo-random value of at least 16 bytes. Unlike the input key material passed into deriveKey(), salt does not need to be kept secret.

    iterations

    A number that represents the number of times the hash function will be executed in deriveKey().

  • For ECDH, pass the object with the following keys (since 0.9.1):

    name

    A string, should be set to ECDH.

    public

    A CryptoKey that represents the public key of the other party. The key must be generated using the same curve as the base key.

baseKey

Is a CryptoKey that represents the input to the derivation algorithm - the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey using crypto.subtle.importKey().

length

Is a number representing the number of bits to derive. For browser compatibility, the number should be a multiple of 8.

crypto.subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)

Derives a secret key from a master key. Possible values:

algorithm

Is an object that defines the derivation algorithm to use:

  • For HKDF, pass the object with the following keys:

    name

    A string, should be set to HKDF.

    hash

    A string with the digest algorithm to use: SHA-1, SHA-256, SHA-384, or SHA-512.

    salt

    An ArrayBuffer, TypedArray, or DataView that represents random or pseudo-random value with the same length as the output of the digest function. Unlike the input key material passed into deriveKey(), salt does not need to be kept secret.

    info

    An ArrayBuffer, TypedArray, or DataView that represents application-specific contextual information used to bind the derived key to an application or context, and enables deriving different keys for different contexts while using the same input key material. This property is required but may be an empty buffer.

  • For PBKDF2, pass the object with the following keys:

    name

    A string, should be set to PBKDF2.

    hash

    A string with the digest algorithm to use: SHA-1, SHA-256, SHA-384, or SHA-512.

    salt

    An ArrayBuffer, TypedArray, or DataView that represents random or pseudo-random value of at least 16 bytes. Unlike the input key material passed into deriveKey(), salt does not need to be kept secret.

    iterations

    A number that represents the number of times the hash function will be executed in deriveKey().

  • For ECDH, pass the object with the following keys (since 0.9.1):

    name

    A string, should be set to ECDH.

    publicKey

    A CryptoKey that represents the public key of the other party. The key must be generated using the same curve as the base key.

baseKey

Is a CryptoKey that represents the input to the derivation algorithm - the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey using crypto.subtle.importKey().

derivedKeyAlgorithm

Is an object that defines the algorithm the derived key will be used for:

  • For HMAC, pass the object with the following keys:

    name

    A string, should be set to HMAC.

    hash

    A string with the name of the digest function to use: SHA-1, SHA-256, SHA-384, or SHA-512.

    length

    (optional) is a number that represents the length in bits of the key. If not specified, the length of the key is equal to the block size of the chosen hash function.

  • For AES-CTR, AES-CBC, or AES-GCM, pass the object with the following keys:

    name

    A string, should be set to AES-CTR, AES-CBC, or AES-GCM, depending on the algorithm used.

    length

    A number that represents the length in bits of the key to generate: 128, 192, or 256.

extractable

Is a boolean value that indicates whether it will be possible to export the key.

keyUsages

Is an Array that indicates what can be done with the derived key. The key usages must be allowed by the algorithm set in derivedKeyAlgorithm. Possible values:

encrypt

Key for encrypting messages.

decrypt

Key for decrypting messages.

sign

Key for signing messages.

verify

Key for verifying signatures.

deriveKey

Key for deriving a new key.

deriveBits

Key for deriving bits.

wrapKey

Key for wrapping a key.

unwrapKey

Key for unwrapping a key.

crypto.subtle.digest(algorithm, data)

Generates a digest of the given data. Takes as its arguments an identifier for the digest algorithm to use and the data to digest. Returns a Promise which will be fulfilled with the digest. Possible values:

algorithm

Is a string that defines the hash function to use: SHA-1 (not for cryptographic applications), SHA-256, SHA-384, or SHA-512.

data

Is an ArrayBuffer, TypedArray, or DataView that contains the data to be digested.

crypto.subtle.exportKey(format, key)

Exports a key: takes a key as a CryptoKey object and returns the key in an external, portable format (since 0.7.10). If the format was jwk, then the Promise fulfills with a JSON object containing the key. Otherwise, the promise fulfills with an ArrayBuffer containing the key. Possible values:

format

A string that describes the data format in which the key should be exported, can be the following:

raw

The raw data format.

pkcs8

The PKCS #8 format.

spki

The SubjectPublicKeyInfo format.

jwk

The JSON Web Key (JWK) format (since 0.7.10).

key

The CryptoKey that contains the key to be exported.

crypto.subtle.generateKey(algorithm, extractable, usage)

Generates a new key for symmetric algorithms or key pair for public-key algorithms (since 0.7.10). Returns a Promise that fulfills with the generated key as a CryptoKey or CryptoKeyPair object. Possible values:

algorithm

A dictionary object that defines the type of key to generate and provides extra algorithm-specific parameters:

  • For RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, pass the object with the following keys:

    name

    A string, should be set to RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, depending on the used algorithm.

    hash

    A string that represents the name of the digest function to use, can be SHA-256, SHA-384, or SHA-512.

  • For ECDSA, pass the object with the following keys:

    name

    A string, should be set to ECDSA.

    namedCurve

    A string that represents the name of the elliptic curve to use, may be P-256, P-384, or P-521.

  • For HMAC, pass the object with the following keys:

    name

    A string, should be set to HMAC.

    hash

    A string that represents the name of the digest function to use, can be SHA-256, SHA-384, or SHA-512.

    length

    (optional) is a number that represents the length in bits of the key. If omitted, the length of the key is equal to the length of the digest generated by the chosen digest function.

  • For AES-CTR, AES-CBC, or AES-GCM, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" , where ALGORITHM is the name of the algorithm.

  • For ECDH, pass the object with the following keys (since 0.9.1):

    name

    A string, should be set to ECDH.

    namedCurve

    A string that represents the name of the elliptic curve to use, may be P-256, P-384, or P-521.

extractable

Boolean value that indicates if it is possible to export the key.

usage

An array that indicates possible actions with the key:

encrypt

Key for encrypting messages.

decrypt

Key for decrypting messages.

sign

Key for signing messages.

verify

Key for verifying signatures.

deriveKey

Key for deriving a new key.

deriveBits

Key for deriving bits.

wrapKey

Key for wrapping a key.

unwrapKey

Key for unwrapping a key.

crypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages)

Imports a key: takes as input a key in an external, portable format and gives a CryptoKey object. Returns a Promise that fulfills with the imported key as a CryptoKey object. Possible values:

format

A string that describes the data format of the key to import, can be the following:

raw

The raw data format.

pkcs8

The PKCS #8 format.

spki

The SubjectPublicKeyInfo format.

jwk

The JSON Web Key (JWK) format (since 0.7.10).

keyData

The ArrayBuffer, TypedArray, or DataView object that contains the key in the given format.

algorithm

A dictionary object that defines the type of key to import and provides extra algorithm-specific parameters:

  • For RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, pass the object with the following keys:

    name

    A string, should be set to RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, depending on the used algorithm.

    hash

    A string that represents the name of the digest function to use, can be SHA-1, SHA-256, SHA-384, or SHA-512.

  • For ECDSA, pass the object with the following keys:

    name

    A string, should be set to ECDSA.

    namedCurve

    A string that represents the name of the elliptic curve to use, may be P-256, P-384, or P-521.

  • For HMAC, pass the object with the following keys:

    name

    A string, should be set to HMAC.

    hash

    A string that represents the name of the digest function to use, can be SHA-256, SHA-384, or SHA-512.

    length

    (optional) is a number that represents the length in bits of the key. If omitted, the length of the key is equal to the length of the digest generated by the chosen digest function.

  • For AES-CTR, AES-CBC, or AES-GCM, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" , where ALGORITHM is the name of the algorithm.

  • For PBKDF2, pass the PBKDF2 string.

  • For HKDF, pass the HKDF string.

  • For ECDH, pass the object with the following keys (since 0.9.1):

    name

    A string, should be set to ECDH.

    namedCurve

    A string that represents the name of the elliptic curve to use, may be P-256, P-384, or P-521.

extractable

Boolean value that indicates if it is possible to export the key.

keyUsages

An array that indicates possible actions with the key:

encrypt

Key for encrypting messages.

decrypt

Key for decrypting messages.

sign

Key for signing messages.

verify

Key for verifying signatures.

deriveKey

Key for deriving a new key.

deriveBits

Key for deriving bits.

wrapKey

Key for wrapping a key.

unwrapKey

Key for unwrapping a key.

crypto.subtle.sign(algorithm, key, data)

Returns signature as a Promise that fulfills with an ArrayBuffer containing the signature. Possible values:

algorithm

Is a string or object that specifies the signature algorithm to use and its parameters:

  • For RSASSA-PKCS1-v1_5, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .

  • For RSA-PSS, pass the object with the following keys:

    name

    A string, should be set to RSA-PSS.

    saltLength

    A long integer that represents the length of the random salt to use, in bytes.

  • For ECDSA, pass the object with the following keys:

    name

    A string, should be set to ECDSA.

    hash

    An identifier for the digest algorithm to use, can be SHA-256, SHA-384, or SHA-512.

  • For HMAC, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .

key

Is a CryptoKey object that the key to be used for signing. If algorithm identifies a public-key cryptosystem, this is the private key.

data

Is an ArrayBuffer, TypedArray, or DataView object that contains the data to be signed.

crypto.subtle.verify(algorithm, key, signature, data)

Verifies a digital signature; returns a Promise that fulfills with a boolean value: true if the signature is valid, otherwise false. Possible values:

algorithm

Is a string or object that specifies the algorithm to use and its parameters:

  • For RSASSA-PKCS1-v1_5, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .

  • For RSA-PSS, pass the object with the following keys:

    name

    A string, should be set to RSA-PSS.

    saltLength

    A long integer that represents the length of the random salt to use, in bytes.

  • For ECDSA, pass the object with the following keys:

    name

    A string, should be set to ECDSA.

    hash

    An identifier for the digest algorithm to use, can be SHA-256, SHA-384, or SHA-512.

  • For HMAC, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .

key

Is a CryptoKey object that the key to be used for verifying. It is the secret key for a symmetric algorithm and the public key for a public-key system.

signature

Is an ArrayBuffer, TypedArray, or DataView that contains the signature to verify.

data

Is an ArrayBuffer, TypedArray, or DataView object that contains the data whose signature is to be verified.

CryptoKey#

  • CryptoKey.algorithm

  • CryptoKey.extractable

  • CryptoKey.type

  • CryptoKey.usages

The CryptoKey object represents a cryptographic key obtained from one of the SubtleCrypto methods: crypto.subtle.generateKey(), crypto.subtle.deriveKey(), crypto.subtle.importKey().

CryptoKey.algorithm

Returns an object describing the algorithm for which this key can be used and any associated extra parameters (since 0.8.0), read-only.

CryptoKey.extractable

A boolean value, true if the key can be exported (since 0.8.0), read-only.

CryptoKey.type

A string value that indicates which kind of key is represented by the object, read-only. Possible values:

secret

This key is a secret key for use with a symmetric algorithm.

private

This key is the private half of an asymmetric algorithm's CryptoKeyPair.

public

This key is the public half of an asymmetric algorithm's CryptoKeyPair.

CryptoKey.usages

An array of strings indicating what this key can be used for (since 0.8.0), read-only. Possible array values:

encrypt

Key for encrypting messages.

decrypt

Key for decrypting messages.

sign

Key for signing messages.

verify

Key for verifying signatures.

deriveKey

Key for deriving a new key.

deriveBits

Key for deriving bits.

CryptoKeyPair#

  • CryptoKeyPair.privateKey

  • CryptoKeyPair.publicKey

The CryptoKeyPair is a dictionary object of the WebCrypto API that represents an asymmetric key pair.

CryptoKeyPair.privateKey

A CryptoKey object representing the private key.

CryptoKeyPair.publicKey

A CryptoKey object representing the public key.

njs#

  • njs.version

  • njs.version_number

  • njs.dump()

  • njs.memoryStats

  • njs.on()

The njs object is a global object that represents the current VM instance (since 0.2.0).

njs.version

Returns a string with the current version of NJS (for example, "0.7.4").

njs.version_number

Returns a number with the current version of NJS. For example, "0.7.4" is returned as 0x000704 (since 0.7.4).

njs.dump(value)

Returns the pretty-print string representation for a value.

njs.memoryStats

Object containing memory statistics for the current VM instance (since 0.7.8).

size

Amount of memory in bytes NJS memory pool claimed from the operating system.

njs.on(event, callback)

Registers a callback for the specified VM event (since 0.5.2). An event may be one of the following strings:

exit

Is called before the VM is destroyed. The callback is called without arguments.

process#

  • process.argv

  • process.env

  • process.kill()

  • process.pid

  • process.ppid

The process object is a global object that provides information about the current process (0.3.3).

process.argv

Returns an array that contains the command-line arguments passed when the current process was launched.

process.env

Returns an object containing the user environment.

Note

By default, Angie removes all environment variables inherited from its parent process except the TZ variable. Use the env directive to preserve some of the inherited variables.

process.kill(pid, number | string)

Sends the signal to the process identified by pid. Signal names are numbers or strings such as 'SIGINT' or 'SIGHUP'. See kill(2) for more information.

process.pid

Returns the PID of the current process.

process.ppid

Returns the PID of the current parent process.

String#

By default, all strings in NJS are Unicode strings. They correspond to ECMAScript strings that contain Unicode characters. Before 0.8.0, byte strings were also supported.

Byte Strings (Removed)#

Note

Since 0.8.0, the support for byte strings and byte string methods were removed. When working with byte sequences, the Buffer object and Buffer properties, such as r.requestBuffer, r.rawVariables, should be used.

Byte strings contained a sequence of bytes and were used to serialize Unicode strings to external data and deserialize from external sources. For example, the toUTF8() method serialized a Unicode string to a byte string using UTF-8 encoding. The toBytes() method serialized a Unicode string with code points up to 255 into a byte string; otherwise, null was returned.

The following methods were made obsolete and removed in 0.8.0:

  • String.bytesFrom() (removed in 0.8.0, use Buffer.from())

  • String.prototype.fromBytes() (removed in 0.8.0)

  • String.prototype.fromUTF8() (removed in 0.8.0, use TextDecoder)

  • String.prototype.toBytes() (removed in 0.8.0)

  • String.prototype.toString() with encoding (removed in 0.8.0)

  • String.prototype.toUTF8() (removed in 0.8.0, use TextEncoder.

Web API#

TextDecoder#

  • TextDecoder()

  • TextDecoder.prototype.encoding

  • TextDecoder.prototype.fatal

  • TextDecoder.prototype.ignoreBOM

  • TextDecoder.prototype.decode()

The TextDecoder produces a stream of code points from a stream of bytes (0.4.3).

TextDecoder([[encoding], options])

Creates a new TextDecoder object for specified encoding; currently, only UTF-8 is supported. The options is TextDecoderOptions dictionary with the property:

fatal

Boolean flag indicating if TextDecoder.decode() must throw the TypeError exception when a coding error is found, by default is false.

TextDecoder.prototype.encoding

Returns a string with the name of the encoding used by TextDecoder(), read-only.

TextDecoder.prototype.fatal

Boolean flag, true if the error mode is fatal, read-only.

TextDecoder.prototype.ignoreBOM

Boolean flag, true if the byte order marker is ignored, read-only.

TextDecoder.prototype.decode(buffer, [options])

Returns a string with the text decoded from the buffer by TextDecoder(). The buffer can be ArrayBuffer. The options is TextDecodeOptions dictionary with the property:

stream

Boolean flag indicating if additional data will follow in subsequent calls to decode(): true if processing the data in chunks, and false for the final chunk or if the data is not chunked. By default is false.

Example:

>> (new TextDecoder()).decode(new Uint8Array([206,177,206,178]))
αβ

TextEncoder#

  • TextEncoder()

  • TextEncoder.prototype.encode()

  • TextEncoder.prototype.encodeInto()

The TextEncoder object produces a byte stream with UTF-8 encoding from a stream of code points (0.4.3).

TextEncoder()

Returns a newly constructed TextEncoder that will generate a byte stream with UTF-8 encoding.

TextEncoder.prototype.encode(string)

Encodes string into a Uint8Array with UTF-8 encoded text.

TextEncoder.prototype.encodeInto(string, uint8Array)

Encodes a string to UTF-8, puts the result into destination Uint8Array, and returns a dictionary object that shows the progress of the encoding. The dictionary object contains two members:

read

The number of UTF-16 units of code from the source string converted to UTF-8.

written

The number of bytes modified in the destination Uint8Array.

Timers#

  • clearTimeout()

  • setTimeout()

clearTimeout(timeout)

Cancels a timeout object created by setTimeout().

setTimeout(function, milliseconds[, argument1, argumentN])

Calls a function after a specified number of milliseconds. One or more optional arguments can be passed to the specified function. Returns a timeout object.

Example:

function handler(v)
{
    // ...
}

t = setTimeout(handler, 12);

// ...

clearTimeout(t).

Global Functions#

  • atob()

  • btoa()

atob(encodedData)

Decodes a string of data which has been encoded using Base64 encoding. The encodedData parameter is a binary string that contains Base64-encoded data. Returns a string that contains decoded data from encodedData.

The similar btoa() method can be used to encode and transmit data which may otherwise cause communication problems, then transmit it and use the atob() method to decode the data again. For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31.

Example:

const encodedData = btoa("text to encode"); // encode a string
const decodedData = atob(encodedData); // decode the string
btoa(stringToEncode)

Creates a Base64-encoded ASCII string from a binary string. The stringToEncode parameter is a binary string to encode. Returns an ASCII string containing the Base64 representation of stringToEncode.

The method can be used to encode data which may otherwise cause communication problems, transmit it, then use the atob() method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.

Example:

const encodedData = btoa("text to encode"); // encode a string
const decodedData = atob(encodedData); // decode the string

Built-in Modules#

Buffer#

The Buffer object is a Node.js-compatible way to work with binary data. Due to the file's extensive size, this section contains a comprehensive list of Buffer methods. Full documentation for each method can be found in Node.js documentation.

  • Buffer.alloc()

  • Buffer.allocUnsafe()

  • Buffer.byteLength()

  • Buffer.compare()

  • Buffer.concat()

  • Buffer.from(array)

  • Buffer.from(arrayBuffer)

  • Buffer.from(buffer)

  • Buffer.from(object)

  • Buffer.from(string)

  • Buffer.isBuffer()

  • Buffer.isEncoding()

  • buffer[]

  • buf.buffer

  • buf.byteOffset

  • buf.compare()

  • buf.copy()

  • buf.equals()

  • buf.fill()

  • buf.includes()

  • buf.indexOf()

  • buf.lastIndexOf()

  • buf.length

  • buf.readIntBE()

  • buf.readIntLE()

  • buf.readUIntBE()

  • buf.readUIntLE()

  • buf.readDoubleBE()

  • buf.readDoubleLE()

  • buf.readFloatBE()

  • buf.readFloatLE()

  • buf.subarray()

  • buf.slice()

  • buf.swap16()

  • buf.swap32()

  • buf.swap64()

  • buf.toJSON()

  • buf.toString()

  • buf.write()

  • buf.writeIntBE()

  • buf.writeIntLE()

  • buf.writeUIntBE()

  • buf.writeUIntLE()

  • buf.writeDoubleBE()

  • buf.writeDoubleLE()

  • buf.writeFloatBE()

  • buf.writeFloatLE()

For detailed documentation of Buffer methods, please refer to Node.js Buffer documentation.

Crypto#

The Crypto module provides cryptographic functionality support. The Crypto module object is imported using import crypto from 'crypto'.

Note

Since 0.7.0, extended crypto API is available as a global crypto object.

  • crypto.createHash()

  • crypto.createHmac()

crypto.createHash(algorithm)

Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. The algorithm can be md5, sha1, and sha256.

crypto.createHmac(algorithm, secret key)

Creates and returns an HMAC object that uses the given algorithm and secret key. The algorithm can be md5, sha1, and sha256.

Hash#

  • hash.update()

  • hash.digest()

hash.update(data)

Updates the hash content with the given data.

hash.digest([encoding])

Calculates the digest of all of the data passed using hash.update(). The encoding can be hex, base64, and base64url. If encoding is not provided, a Buffer object (0.4.4) is returned.

Note

Before version (0.4.4), a byte string was returned instead of a Buffer object.

hash.copy()

Makes a copy of the current state of the hash (since 0.7.12).

Example:

import crypto from 'crypto';

crypto.createHash('sha1').update('A').update('B').digest('base64url');
/* BtlFlCqiamG-GMPiK_GbvKjdK10 */

HMAC#

  • hmac.update()

  • hmac.digest()

hmac.update(data)

Updates the HMAC content with the given data.

hmac.digest([encoding])

Calculates the HMAC digest of all of the data passed using hmac.update(). The encoding can be hex, base64, and base64url. If encoding is not provided, a Buffer object (0.4.4) is returned.

Note

Before version 0.4.4, a byte string was returned instead of a Buffer object.

fs#

The fs module provides operations with the file system. The module object is imported using import fs from 'fs'.

  • fs.accessSync()

  • fs.appendFileSync()

  • fs.mkdirSync()

  • fs.readdirSync()

  • fs.readFileSync()

  • fs.realpathSync()

  • fs.renameSync()

  • fs.rmdirSync()

  • fs.symlinkSync()

  • fs.unlinkSync()

  • fs.writeFileSync()

  • fs.promises.readFile()

  • fs.promises.appendFile()

  • fs.promises.writeFile()

  • fs.promises.readdir()

  • fs.promises.mkdir()

  • fs.promises.rmdir()

  • fs.promises.rename()

  • fs.promises.unlink()

  • fs.promises.symlink()

  • fs.promises.access()

  • fs.promises.realpath()

For detailed documentation of fs methods, please refer to Node.js fs documentation.

Query String#

The Query String module provides methods for parsing and formatting URL query strings. The module object is imported using import qs from 'querystring'.

  • querystring.decode()

  • querystring.encode()

  • querystring.escape()

  • querystring.parse()

  • querystring.stringify()

  • querystring.unescape()

querystring.decode()

An alias to querystring.parse().

querystring.encode()

An alias to querystring.stringify().

querystring.escape(string)

Performs URL percent-encoding of the string in a manner optimized for the requirements of URL query strings. The method is used by querystring.stringify() and should not be used directly.

querystring.parse(string[, separator[, equal[, options]]])

Parses the string as a URL query string and returns an object. The optional separator parameter (default: &) specifies the substring for delimiting key-value pairs. The optional equal parameter (default: =) specifies the substring for delimiting keys and values. The optional options parameter is an object that may contain the following property:

decodeURIComponent

Function to use when decoding percent-encoded characters in the query string, default: querystring.unescape().

maxKeys

The maximum number of keys to parse, default: 1000. The 0 value removes limitations for counting keys.

Example:

>> qs.parse('foo=bar&abc=xyz&abc=123')
{
    foo: 'bar',
    abc: ['xyz', '123']
}
querystring.stringify(object[, separator[, equal[, options]]])

Produces a URL query string from the object by iterating through its own properties. The optional separator parameter (default: &) specifies the substring for delimiting key-value pairs. The optional equal parameter (default: =) specifies the substring for delimiting keys and values. The optional options parameter is an object that may contain the following property:

encodeURIComponent

Function to use when converting URL-unsafe characters to percent-encoding in the query string, default: querystring.escape().

Example:

>> qs.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
'foo=bar&baz=qux&baz=quux&corge='
querystring.unescape(string)

Performs decoding of URL percent-encoded characters in the string. The method is used by querystring.parse() and should not be used directly.

XML#

  • xml.parse()

  • xml.c14n()

  • xml.exclusiveC14n()

  • xml.serialize()

  • xml.serializeToString()

  • XMLDoc

  • XMLNode

  • XMLAttr

The XML module allows working with XML documents (since 0.7.10). The XML module object is imported using import xml from 'xml'.

Example:

import xml from 'xml';

let data = `<note><to b="bar" a= "foo" >Tove</to><from>Jani</from></note>`;
let doc = xml.parse(data);

console.log(doc.note.to.$text) /* 'Tove' */
console.log(doc.note.to.$attr$b) /* 'bar' */
console.log(doc.note.$tags[1].$text) /* 'Jani' */

let dec = new TextDecoder();
let c14n = dec.decode(xml.exclusiveC14n(doc.note));
console.log(c14n) /* '<note><to a="foo" b="bar">Tove</to><from>Jani</from></note>' */

c14n = dec.decode(xml.exclusiveC14n(doc.note.to));
console.log(c14n) /* '<to a="foo" b="bar">Tove</to>' */

c14n = dec.decode(xml.exclusiveC14n(doc.note, doc.note.to /* excluding 'to' */));
console.log(c14n) /* '<note><from>Jani</from></note>' */
parse(string | Buffer)

Parses a string or Buffer for an XML document; returns an XMLDoc wrapper object representing the parsed XML document.

c14n(root_node[, excluding_node])

Canonicalizes root_node and its children according to Canonical XML Version 1.1. The root_node can be XMLNode or XMLDoc wrapper object around XML structure. Returns Buffer object that contains canonicalized output.

excluding_node

Allows omitting from the output a part of the document.

exclusiveC14n(root_node[, excluding_node[, withComments[,prefix_list]]])

Canonicalizes root_node and its children according to Exclusive XML Canonicalization Version 1.0.

root_node

Is XMLNode or XMLDoc wrapper object around XML structure.

excluding_node

Allows omitting from the output a part of the document corresponding to the node and its children.

withComments

A boolean value, false by default. If true, canonicalization corresponds to Exclusive XML Canonicalization Version 1.0. Returns Buffer object that contains canonicalized output.

prefix_list

An optional string with a space-separated namespace prefixes for namespaces that should also be included in the output.

serialize()

The same as xml.c14n() (since 0.7.11).

serializeToString()

The same as xml.c14n() except it returns the result as a string (since 0.7.11).

XMLDoc

An XMLDoc wrapper object around XML structure, the root node of the document.

doc.$root

The document's root by its name or undefined.

doc.abc

The first root tag named abc as XMLNode wrapper object.

XMLNode

An XMLNode wrapper object around XML tag node.

node.abc

The same as node.$tag$abc.

node.$attr$abc

The node's attribute value of abc, writable since 0.7.11.

node.$attr$abc=xyz

The same as node.setAttribute('abc', xyz) (since 0.7.11).

node.$attrs

An XMLAttr wrapper object for all attributes of the node.

node.$name

The name of the node.

node.$ns

The namespace of the node.

node.$parent

The parent node of the current node.

node.$tag$abc

The first child tag of the node named abc, writable since 0.7.11.

node.$tags

An array of all children tags.

node.$tags = [node1, node2, ...]

The same as node.removeChildren(); node.addChild(node1); node.addChild(node2) (since 0.7.11).

node.$tags$abc

All children tags named abc of the node, writable since 0.7.11.

node.$text

The content of the node, writable since 0.7.11.

node.$text = 'abc'

The same as node.setText('abc') (since 0.7.11).

node.addChild(nd)

Adds XMLNode as a child to node (since 0.7.11). nd is recursively copied before adding to the node.

node.removeAllAttributes()

Removes all attributes of the node (since 0.7.11).

node.removeAttribute(attr_name)

Removes the attribute named attr_name (since 0.7.11).

node.removeChildren(tag_name)

Removes all the children tags named tag_name (since 0.7.11). If tag_name is absent, all children tags are removed.

node.removeText()

Removes the node's text value (0.7.11).

node.setAttribute(attr_name, value)

Sets a value for an attr_name (since 0.7.11). When the value is null, the attribute named attr_name is deleted.

node.setText(value)

Sets a text value for the node (since 0.7.11). When the value is null, the text of the node is deleted.

XMLAttr

An XMLAttrs wrapper object around XML node attributes.

attr.abc

The attribute value of abc.

zlib#

The zlib module (0.5.2) provides compression and decompression functionality using zlib. The module object is imported using import zlib from 'zlib'.

  • zlib.constants

  • zlib.deflateRawSync()

  • zlib.deflateSync()

  • zlib.inflateRawSync()

  • zlib.inflateSync()

zlib.constants

Returns a dictionary of zlib constants.

zlib.deflateRawSync(data[, options])

Compresses data using the Deflate algorithm without the zlib header.

zlib.deflateSync(data[, options])

Compresses data using the Deflate algorithm.

zlib.inflateRawSync(data[, options])

Decompresses data using the Deflate algorithm without the zlib header.

zlib.inflateSync(data[, options])

Decompresses data using the Deflate algorithm.

The options parameter is an object that may contain the following properties:

level

Compression level (default: zlib.constants.Z_DEFAULT_COMPRESSION).

memLevel

Specifies how much memory should be allocated for the compression state (default: zlib.constants.Z_DEFAULT_MEMLEVEL).

strategy

Tunes the compression algorithm (default: zlib.constants.Z_DEFAULT_STRATEGY).

windowBits

Sets the window size (default: zlib.constants.Z_DEFAULT_WINDOWBITS).

dictionary

Buffer containing the predefined compression dictionary.

info

A boolean value, if true, returns an object with buffer and engine.

chunkSize

Chunk size for compression (default: zlib.constants.Z_DEFAULT_CHUNK).

Example:

import zlib from 'zlib';

const deflated = zlib.deflateSync('Hello World!');
const inflated = zlib.inflateSync(deflated);

console.log(inflated.toString()); // 'Hello World!'