<!-- review: finished -->

<a id="njs-reference"></a>

# NJS API Reference

The [NJS](https://en.angie.software//angie/docs/installation/external-modules/njs.md#external-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 the [ECMAScript specification](http://www.ecma-international.org/ecma-262/).

<a id="njs-nginx-objects"></a>

## Angie Objects

<a id="njs-http-request"></a>

### 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](https://en.angie.software//angie/docs/installation/external-modules/http_js.md#http-js) module. Before 0.8.5, all string properties of the object were byte strings.

<a id="r-args"></a>

`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

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

> is converted to `r.args` as:

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

> More advanced parsing scenarios can be achieved with the [Query String](#njs-querystring) module and the `$args` variable, for example:

> ```javascript
> import qs from 'querystring';

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

> The arguments 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:

> ```javascript
> r.variables.arg_foo
> ```

> Here, the 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.

<a id="r-done"></a>

`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.

<a id="r-error"></a>

`r.error(string)`
: Writes a `string` to the error log on the `error` level of logging.
  <br/>
  #### NOTE
  As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

<a id="r-finish"></a>

`r.finish()`
: Finishes sending a response to the client.

<a id="r-headers-in"></a>

`r.headersIn{}`
: Incoming headers object, read-only.
  <br/>
  The `Foo` request header can be accessed with the syntax: `headersIn.foo` or `headersIn['Foo']`.
  <br/>
  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.

<a id="r-headers-out"></a>

`r.headersOut{}`
: Outgoing headers object for the main request, writable.
  <br/>
  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.
  <br/>
  The `Foo` response header can be accessed with the syntax: `headersOut.foo` or `headersOut['Foo']`.
  <br/>
  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:
  <br/>
  - the `js_content` handler before `r.sendHeader()` or `r.return()` are called
  - the `js_header_filter` handler
  <br/>
  Field values of multi-value response headers (0.4.0) can be set with the syntax:
  <br/>
  ```javascript
  r.headersOut['Foo'] = ['a', 'b']
  ```
  <br/>
  where the output will be:
  <br/>
  ```text
  Foo: a
  Foo: b
  ```
  <br/>
  All previous field values of the `Foo` response header will be deleted.
  <br/>
  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.

<a id="r-http-version"></a>

`r.httpVersion`
: HTTP version, read-only.

<a id="r-internal"></a>

`r.internal`
: Boolean value, `true` for internal locations.

<a id="r-internal-redirect"></a>

`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.
  <br/>
  #### 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, a variable declared with the `js_var` directive for HTTP or Stream can be used.
  <br/>
  #### NOTE
  Since 0.7.4, the method accepts escaped URIs.

<a id="r-log"></a>

`r.log(string)`
: Writes a `string` to the error log on the `info` level of logging.
  <br/>
  #### NOTE
  As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

<a id="r-method"></a>

`r.method`
: HTTP method, read-only.

<a id="r-parent"></a>

`r.parent`
: References the parent request object.

<a id="r-remote-address"></a>

`r.remoteAddress`
: Client address, read-only.

<a id="r-request-body"></a>

`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.

<a id="r-request-buffer"></a>

`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.

<a id="r-request-text"></a>

`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.

<a id="r-raw-headers-in"></a>

`r.rawHeadersIn[]`
: Returns an array of key-value pairs exactly as they were received from the client (0.4.1).
  <br/>
  For example, with the following request headers:
  <br/>
  ```text
  Host: localhost
  Foo:  bar
  foo:  bar2
  ```
  <br/>
  the output of `r.rawHeadersIn` will be:
  <br/>
  ```javascript
  [
      ['Host', 'localhost'],
      ['Foo', 'bar'],
      ['foo', 'bar2']
  ]
  ```
  <br/>
  All `foo` headers can be collected with the syntax:
  <br/>
  ```javascript
  r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1])
  ```
  <br/>
  the output will be:
  <br/>
  ```javascript
  ['bar', 'bar2']
  ```
  <br/>
  Header field names are not converted to lower case, duplicate field values are not merged.

<a id="r-raw-headers-out"></a>

`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.

<a id="r-response-body"></a>

`r.responseBody`
: The property was deprecated in 0.5.0 and was removed in 0.8.0. The `r.responseBuffer` or `r.responseText` property should be used instead.

<a id="r-response-buffer"></a>

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

<a id="r-response-text"></a>

`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.

<a id="r-return"></a>

`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).
  <br/>
  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.

<a id="r-send"></a>

`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).

<a id="r-sendbuffer"></a>

`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.
  <br/>
  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:
  <br/>
  `last`
  : Boolean, `true` if the buffer is the last buffer.
  <br/>
  `flush`
  : Boolean, `true` if the buffer should have the `flush` flag.
  <br/>
  The method may be called only from the `js_body_filter` function.

<a id="r-send-header"></a>

`r.sendHeader()`
: Sends the HTTP headers to the client.

<a id="r-set-return-value"></a>

`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:
  <br/>
  ```javascript
  async function js_set(r) {
      const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host);
      r.setReturnValue(digest);
  }
  ```

<a id="r-status"></a>

`r.status`
: Status, writable.

<a id="r-subrequest"></a>

`r.subrequest(uri[, options[, callback]])`
: Creates a subrequest with the given `uri` and `options`, and installs an optional completion `callback`.
  <br/>
  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.
  <br/>
  If `options` is a string, then it holds the subrequest arguments string. Otherwise, `options` is expected to be an object with the following keys:
  <br/>
  `args`
  : Arguments string, by default an empty string is used.
  <br/>
  `body`
  : Request body, by default the request body of the parent request object is used.
  <br/>
  `method`
  : HTTP method, by default the `GET` method is used.
  <br/>
  `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.
  <br/>
  The completion `callback` receives a subrequest response object with methods and properties identical to the parent request object.
  <br/>
  Since 0.3.8, if a `callback` is not provided, the `Promise` object that resolves to the subrequest response object is returned.
  <br/>
  For example, to view all response headers in the subrequest:
  <br/>
  ```javascript
  async function handler(r) {
      const reply = await r.subrequest('/path');
  <br/>
      for (const h in reply.headersOut) {
          r.log(`${h}: ${reply.headersOut[h]}`);
      }
  <br/>
      r.return(200);
  }
  ```

<a id="r-uri"></a>

`r.uri`
: Current URI in request, normalized, read-only.

<a id="r-raw-variables"></a>

`r.rawVariables{}`
: Angie variables as Buffers, writable (since 0.5.0).

<a id="r-variables"></a>

`r.variables{}`
: Angie variables object, writable (since 0.2.8).
  <br/>
  For example, to get the `$foo` variable, one of the following syntax can be used:
  <br/>
  ```javascript
  r.variables['foo']
  r.variables.foo
  ```
  <br/>
  Since 0.8.6, regular expression captures can be accessed using the following syntax:
  <br/>
  ```javascript
  r.variables['1']
  r.variables[1]
  ```
  <br/>
  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:
  <br/>
  ```nginx
  proxy_set_header X-Request-Id $request_id;
  ```
  <br/>
  the `r.variables.request_id` returns the same value every time.
  <br/>
  A variable is writable if:
  <br/>
  - it was created using the `js_var` directive for HTTP or Stream (since 0.5.3)
  - it is referenced in Angie configuration file
  <br/>
  Even so, some embedded variables still cannot be assigned a value (for example, `$http_`).

<a id="r-warn"></a>

`r.warn(string)`
: Writes a `string` to the error log on the `warning` level of logging.
  <br/>
  #### NOTE
  As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

<a id="njs-stream-session"></a>

### 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](https://en.angie.software//angie/docs/installation/external-modules/stream_js.md#stream-js) module. Before 0.8.5, all string properties of the object were byte strings.

<a id="njs-s-allow"></a>

`s.allow()`
: An alias to `s.done(0)` (0.2.4).

<a id="njs-s-decline"></a>

`s.decline()`
: An alias to `s.done(-5)` (0.2.4).

<a id="njs-s-deny"></a>

`s.deny()`
: An alias to `s.done(403)` (0.2.4).

<a id="njs-s-done"></a>

`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).
  <br/>
  Possible code values:
  <br/>
  - `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
  <br/>
  May be called only from a phase handler function: `js_access` or `js_preread`.

<a id="njs-s-error"></a>

`s.error(string)`
: Writes a sent `string` to the error log on the `error` level of logging.
  <br/>
  #### NOTE
  As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

<a id="s-log"></a>

`s.log(string)`
: Writes a sent `string` to the error log on the `info` level of logging.
  <br/>
  #### NOTE
  As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

<a id="s-off"></a>

`s.off(eventName)`
: Unregisters the callback set by the `s.on()` method (0.2.4).

<a id="s-on"></a>

`s.on(event, callback)`
: Registers a `callback` for the specified `event` (0.2.4).
  <br/>
  An `event` may be one of the following strings:
  <br/>
  `upload`
  : New data (string) from a client.
  <br/>
  `download`
  : New data (string) to a client.
  <br/>
  `upstream`
  : New data (Buffer) from a client (since 0.5.0).
  <br/>
  `downstream`
  : New data (Buffer) to a client (since 0.5.0).
  <br/>
  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:
  <br/>
  `last`
  : A boolean value, `true` if data is a last buffer.

<a id="s-remote-address"></a>

`s.remoteAddress`
: Client address, read-only.

<a id="s-raw-variables"></a>

`s.rawVariables`
: Angie variables as Buffers, writable (since 0.5.0).

<a id="s-send"></a>

`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.
  <br/>
  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:
  <br/>
  `last`
  : Boolean, `true` if the buffer is the last buffer.
  <br/>
  `flush`
  : Boolean, `true` if the buffer should have the `flush` flag.
  <br/>
  The method can be called multiple times per callback invocation.

<a id="s-send-downstream"></a>

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

<a id="s-send-upstream"></a>

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

<a id="s-status"></a>

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

<a id="s-set-return-value"></a>

`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:
  <br/>
  ```javascript
  async function js_set(r) {
      const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host);
      r.setReturnValue(digest);
  }
  ```

<a id="s-variables"></a>

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

<a id="s-warn"></a>

`s.warn(string)`
: Writes the sent `string` to the error log on the `warning` logging level.
  <br/>
  #### NOTE
  As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged.

<a id="njs-periodic-session"></a>

### 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.

<a id="njs-headers"></a>

### 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).

<a id="njs-request"></a>

### 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:
  <br/>
  `body`
  : The request body, by default is empty.
  <br/>
  `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.
  <br/>
  `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.

<a id="njs-response"></a>

### 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:
  <br/>
  `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.
  <br/>
  `status`
  : The status code of the response.
  <br/>
  `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.

<a id="njs-ngx"></a>

### 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).

<a id="ngx-fetch"></a>

`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.
  <br/>
  If the URL in the `resource` is specified as a domain name, it is resolved 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.
  <br/>
  The `options` parameter is expected to be an object with the following keys:
  <br/>
  `body`
  : Request body, by default is empty.
  <br/>
  `buffer_size`
  : The buffer size for reading the response, by default is `4096`.
  <br/>
  `headers`
  : Request headers object.
  <br/>
  `max_response_body_size`
  : The maximum size of the response body in bytes, by default is `32768`.
  <br/>
  `method`
  : HTTP method, by default the `GET` method is used.
  <br/>
  `verify`
  : Enables or disables verification of the HTTPS server certificate, by default is `true` (0.7.0).
  <br/>
  Example:
  <br/>
  ```javascript
  let reply = await ngx.fetch('http://example.com/');
  let body = await reply.text();
  <br/>
  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`.
  <br/>
  #### 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).

<a id="njs-ngx-shared"></a>

### ngx.shared

The `ngx.shared` global object is available since 0.8.0.

<a id="njs-shareddict"></a>

#### 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` argument is a string representing the key of the item to add; the `value` argument is the value of the item to add.
  <br/>
  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.
  <br/>
  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 the `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` argument is a string; the `delta` argument is the number to increment or decrement the value by. If the key does not exist, the item will be initialized to the optional `init` argument, by default is `0`.
  <br/>
  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.
  <br/>
  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.
  <br/>
  #### NOTE
  This method can be used only if the dictionary type was declared with the `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 the `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).
  <br/>
  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 the `js_shared_dict_zone` directive in HTTP or Stream.

<a id="njs-builtin-objects"></a>

## Built-in Objects

<a id="njs-console"></a>

### 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()` is called with the same name, 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.

<a id="njs-builtin-crypto"></a>

### 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:
  <br/>
  `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:
  <br/>
  `algorithm`
  : An object that specifies the algorithm to be used and any extra parameters if required:
    <br/>
    - For `RSA-OAEP`, pass an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `RSA-OAEP`:
        ```javascript
        crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
        ```
    - For `AES-CTR`, pass an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `AES-CTR`.
    <br/>
      `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.
    <br/>
      `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 an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `AES-CBC`.
    <br/>
      `iv`
      : 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 an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `AES-GCM`.
    <br/>
      `iv`
      : 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.
    <br/>
      `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`.
    <br/>
      `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.
  <br/>
  `key`
  : A `CryptoKey` that contains the key to be used for encryption.
  <br/>
  `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:
  <br/>
  `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.
    <br/>
    - For `RSA-OAEP`, pass an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `RSA-OAEP`:
        ```javascript
        crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
        ```
    - For `AES-CTR`, pass an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `AES-CTR`.
    <br/>
      `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.
    <br/>
      `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 an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `AES-CBC`.
    <br/>
      `iv`
      : 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 an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `AES-GCM`.
    <br/>
      `iv`
      : 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.
    <br/>
      `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`.
    <br/>
      `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.
  <br/>
  `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.
  <br/>
  `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` containing the derived bits. Possible values:
  <br/>
  `algorithm`
  : An object that defines the derivation algorithm to use:
    <br/>
    - For `HKDF`, pass an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `HKDF`.
    <br/>
      `hash`
      : A string with the digest algorithm to use: `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `salt`
      : An `ArrayBuffer`, `TypedArray`, or `DataView` that represents a 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.
    <br/>
      `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 an object with the following keys:
    <br/>
      `name`
      : A string, should be set to `PBKDF2`.
    <br/>
      `hash`
      : A string with the digest algorithm to use: `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `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.
    <br/>
      `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):
    <br/>
      `name`
      : A string, should be set to `ECDH`.
    <br/>
      `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.
  <br/>
  `baseKey`
  : 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()`.
  <br/>
  `length`
  : 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:
  <br/>
  `algorithm`
  : An object that defines the derivation algorithm to use:
    <br/>
    - For `HKDF`, pass the object with the following keys:
    <br/>
      `name`
      : A string, should be set to `HKDF`.
    <br/>
      `hash`
      : A string with the digest algorithm to use: `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `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.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `PBKDF2`.
    <br/>
      `hash`
      : A string with the digest algorithm to use: `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `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.
    <br/>
      `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):
    <br/>
      `name`
      : A string, should be set to `ECDH`.
    <br/>
      `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.
  <br/>
  `baseKey`
  : 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()`.
  <br/>
  `derivedKeyAlgorithm`
  : An object that defines the algorithm the derived key will be used for:
    <br/>
    - For `HMAC`, pass the object with the following keys:
    <br/>
      `name`
      : A string, should be set to `HMAC`.
    <br/>
      `hash`
      : A string with the name of the digest function to use: `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `AES-CTR`, `AES-CBC`, or `AES-GCM`, depending on the algorithm used.
    <br/>
      `length`
      : A `number` that represents the length in bits of the key to generate: `128`, `192`, or `256`.
  <br/>
  `extractable`
  : A boolean value that indicates whether it will be possible to export the key.
  <br/>
  `keyUsages`
  : 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:
    <br/>
    `encrypt`
    : Key for encrypting messages.
    <br/>
    `decrypt`
    : Key for decrypting messages.
    <br/>
    `sign`
    : Key for signing messages.
    <br/>
    `verify`
    : Key for verifying signatures.
    <br/>
    `deriveKey`
    : Key for deriving a new key.
    <br/>
    `deriveBits`
    : Key for deriving bits.
    <br/>
    `wrapKey`
    : Key for wrapping a key.
    <br/>
    `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:
  <br/>
  `algorithm`
  : A string that defines the hash function to use: `SHA-1` (not for cryptographic applications), `SHA-256`, `SHA-384`, or `SHA-512`.
  <br/>
  `data`
  : 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:
  <br/>
  `format`
  : A string that describes the data format in which the key should be exported, can be the following:
    <br/>
    `raw`
    : The raw data format.
    <br/>
    `pkcs8`
    : The [PKCS #8](https://datatracker.ietf.org/doc/html/rfc5208) format.
    <br/>
    `spki`
    : The [SubjectPublicKeyInfo](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1) format.
    <br/>
    `jwk`
    : The [JSON Web Key](https://datatracker.ietf.org/doc/html/rfc7517) (JWK) format (since 0.7.10).
  <br/>
  `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:
  <br/>
  `algorithm`
  : A dictionary object that defines the type of key to generate and provides extra algorithm-specific parameters:
    <br/>
    - For `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, pass the object with the following keys:
    <br/>
      `name`
      : A string, should be set to `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, depending on the algorithm used.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `ECDSA`.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `HMAC`.
    <br/>
      `hash`
      : A string that represents the name of the `digest` function to use, can be `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `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):
    <br/>
      `name`
      : A string, should be set to `ECDH`.
    <br/>
      `namedCurve`
      : A string that represents the name of the elliptic curve to use, may be `P-256`, `P-384`, or `P-521`.
  <br/>
  `extractable`
  : Boolean value that indicates if it is possible to export the key.
  <br/>
  `usage`
  : An `array` that indicates possible actions with the key:
    <br/>
    `encrypt`
    : Key for encrypting messages.
    <br/>
    `decrypt`
    : Key for decrypting messages.
    <br/>
    `sign`
    : Key for signing messages.
    <br/>
    `verify`
    : Key for verifying signatures.
    <br/>
    `deriveKey`
    : Key for deriving a new key.
    <br/>
    `deriveBits`
    : Key for deriving bits.
    <br/>
    `wrapKey`
    : Key for wrapping a key.
    <br/>
    `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:
  <br/>
  `format`
  : A string that describes the data format of the key to import, can be the following:
    <br/>
    `raw`
    : The raw data format.
    <br/>
    `pkcs8`
    : The [PKCS #8](https://datatracker.ietf.org/doc/html/rfc5208) format.
    <br/>
    `spki`
    : The [SubjectPublicKeyInfo](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1) format.
    <br/>
    `jwk`
    : The [JSON Web Key](https://datatracker.ietf.org/doc/html/rfc7517) (JWK) format (since 0.7.10).
  <br/>
  `keyData`
  : The `ArrayBuffer`, `TypedArray`, or `DataView` object that contains the key in the given format.
  <br/>
  `algorithm`
  : A dictionary object that defines the type of key to import and provides extra algorithm-specific parameters:
    <br/>
    - For `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, pass the object with the following keys:
    <br/>
      `name`
      : A string, should be set to `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, depending on the used algorithm.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `ECDSA`.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `HMAC`.
    <br/>
      `hash`
      : A string that represents the name of the `digest` function to use, can be `SHA-256`, `SHA-384`, or `SHA-512`.
    <br/>
      `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):
    <br/>
      `name`
      : A string, should be set to `ECDH`.
    <br/>
      `namedCurve`
      : A string that represents the name of the elliptic curve to use, may be `P-256`, `P-384`, or `P-521`.
  <br/>
  `extractable`
  : Boolean value that indicates if it is possible to export the key.
  <br/>
  `keyUsages`
  : An `array` that indicates possible actions with the key:
    <br/>
    `encrypt`
    : Key for encrypting messages.
    <br/>
    `decrypt`
    : Key for decrypting messages.
    <br/>
    `sign`
    : Key for signing messages.
    <br/>
    `verify`
    : Key for verifying signatures.
    <br/>
    `deriveKey`
    : Key for deriving a new key.
    <br/>
    `deriveBits`
    : Key for deriving bits.
    <br/>
    `wrapKey`
    : Key for wrapping a key.
    <br/>
    `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:
  <br/>
  `algorithm`
  : A string or object that specifies the signature algorithm to use and its parameters:
    <br/>
    - 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:
    <br/>
      `name`
      : A string, should be set to `RSA-PSS`.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `ECDSA`.
    <br/>
      `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"* `.
  <br/>
  `key`
  : A `CryptoKey` object that contains the key to be used for signing. If algorithm identifies a public-key cryptosystem, this is the private key.
  <br/>
  `data`
  : 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:
  <br/>
  `algorithm`
  : A string or object that specifies the algorithm to use and its parameters:
    <br/>
    - 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:
    <br/>
      `name`
      : A string, should be set to `RSA-PSS`.
    <br/>
      `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:
    <br/>
      `name`
      : A string, should be set to `ECDSA`.
    <br/>
      `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"* `.
  <br/>
  `key`
  : A `CryptoKey` object that contains 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.
  <br/>
  `signature`
  : An `ArrayBuffer`, `TypedArray`, or `DataView` that contains the signature to verify.
  <br/>
  `data`
  : An `ArrayBuffer`, `TypedArray`, or `DataView` object that contains the data whose signature is to be verified.

<a id="njs-cryptokey"></a>

#### 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:
  <br/>
  `secret`
  : This key is a secret key for use with a symmetric algorithm.
  <br/>
  `private`
  : This key is the private half of an asymmetric algorithm's `CryptoKeyPair`.
  <br/>
  `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:
  <br/>
  `encrypt`
  : Key for encrypting messages.
  <br/>
  `decrypt`
  : Key for decrypting messages.
  <br/>
  `sign`
  : Key for signing messages.
  <br/>
  `verify`
  : Key for verifying signatures.
  <br/>
  `deriveKey`
  : Key for deriving a new key.
  <br/>
  `deriveBits`
  : Key for deriving bits.

<a id="njs-cryptokeypair"></a>

#### 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.

<a id="njs-njs"></a>

### 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).
  <br/>
  `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:
  <br/>
  `exit`
  : Is called before the VM is destroyed. The callback is called without arguments.

<a id="njs-process"></a>

### 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.
  <br/>
  #### 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)](https://man7.org/linux/man-pages/man2/kill.2.html) for more information.

`process.pid`
: Returns the PID of the current process.

`process.ppid`
: Returns the PID of the current parent process.

<a id="njs-string"></a>

### 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.

<a id="byte-strings-removed"></a>

#### Byte Strings (Removed)

#### NOTE
Since 0.8.0, the support for byte strings and byte string methods was removed. When working with byte sequences, the [Buffer](#njs-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`)

<a id="njs-webapi"></a>

## Web API

<a id="njs-textdecoder"></a>

### 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 the specified `encoding`; currently, only UTF-8 is supported. The `options` is a `TextDecoderOptions` dictionary with the property:
  <br/>
  `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 a `TextDecodeOptions` dictionary with the property:
  <br/>
  `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`.
  <br/>
  Example:
  <br/>
  ```javascript
  >> (new TextDecoder()).decode(new Uint8Array([206,177,206,178]))
  αβ
  ```

<a id="njs-textencoder"></a>

### 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 the destination `Uint8Array`, and returns a dictionary object that shows the progress of the encoding. The dictionary object contains two members:
  <br/>
  `read`
  : The number of UTF-16 units of code from the source `string` converted to UTF-8.
  <br/>
  `written`
  : The number of bytes modified in the destination `Uint8Array`.

<a id="njs-timers"></a>

## 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.
  <br/>
  Example:
  <br/>
  ```javascript
  function handler(v)
  {
      // ...
  }
  <br/>
  t = setTimeout(handler, 12);
  <br/>
  // ...
  <br/>
  clearTimeout(t);
  ```

<a id="njs-global-functions"></a>

### 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`.
  <br/>
  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`.
  <br/>
  Example:
  <br/>
  ```javascript
  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`.
  <br/>
  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`.
  <br/>
  Example:
  <br/>
  ```javascript
  const encodedData = btoa("text to encode"); // encode a string
  const decodedData = atob(encodedData); // decode the string
  ```

<a id="njs-builtin-modules"></a>

## Built-in Modules

<a id="njs-buffer"></a>

### Buffer

The `Buffer` object is a Node.js-compatible way to work with binary data. Due to the file's extensive size, this section is limited to a comprehensive list of Buffer methods.

- `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](https://nodejs.org/api/buffer.html).

<a id="njs-crypto"></a>

### 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](#njs-builtin-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`.

<a id="hash"></a>

#### 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 is returned (0.4.4).
  <br/>
  #### 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:

```javascript
import crypto from 'crypto';

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

<a id="hmac"></a>

#### 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 is returned (0.4.4).
  <br/>
  #### NOTE
  Before version 0.4.4, a byte string was returned instead of a Buffer object.

<a id="njs-fs"></a>

### 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](https://nodejs.org/api/fs.html).

<a id="njs-querystring"></a>

### 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:
  <br/>
  `decodeURIComponent`
  : Function to use when decoding percent-encoded characters in the query string, default: `querystring.unescape()`.
  <br/>
  `maxKeys`
  : The maximum number of keys to parse, default: `1000`. The `0` value removes limitations for counting keys.
  <br/>
  Example:
  <br/>
  ```javascript
  >> 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:
  <br/>
  `encodeURIComponent`
  : Function to use when converting URL-unsafe characters to percent-encoding in the query string, default: `querystring.escape()`.
  <br/>
  Example:
  <br/>
  ```javascript
  >> 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.

<a id="njs-xml"></a>

### 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:

```javascript
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](https://www.w3.org/TR/xml-c14n). The `root_node` can be an `XMLNode` or `XMLDoc` wrapper object around XML structure. Returns a Buffer object that contains canonicalized output.
  <br/>
  `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](https://www.w3.org/TR/xml-exc-c14n/).
  <br/>
  `root_node`
  : An `XMLNode` or `XMLDoc` wrapper object around XML structure.
  <br/>
  `excluding_node`
  : Allows omitting from the output a part of the document corresponding to the node and its children.
  <br/>
  `withComments`
  : A boolean value, `false` by default. If `true`, canonicalization corresponds to [Exclusive XML Canonicalization Version 1.0](http://www.w3.org/2001/10/xml-exc-c14n#WithComments). Returns a Buffer object that contains canonicalized output.
  <br/>
  `prefix_list`
  : An optional string with 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.
  <br/>
  > `doc.$root`
  > : The document's root by its name or undefined.
  <br/>
  > `doc.abc`
  > : The first root tag named `abc` as an `XMLNode` wrapper object.

`XMLNode`
: An XMLNode wrapper object around an XML tag node.
  <br/>
  > `node.abc`
  > : The same as `node.$tag$abc`.
  <br/>
  > `node.$attr$abc`
  > : The node's attribute value of `abc`, writable since 0.7.11.
  <br/>
  > `node.$attr$abc=xyz`
  > : The same as `node.setAttribute('abc', xyz)` (since 0.7.11).
  <br/>
  > `node.$attrs`
  > : An `XMLAttr` wrapper object for all attributes of the node.
  <br/>
  > `node.$name`
  > : The name of the node.
  <br/>
  > `node.$ns`
  > : The namespace of the node.
  <br/>
  > `node.$parent`
  > : The parent node of the current node.
  <br/>
  > `node.$tag$abc`
  > : The first child tag of the node named `abc`, writable since 0.7.11.
  <br/>
  > `node.$tags`
  > : An array of all child tags.
  <br/>
  > `node.$tags = [node1, node2, ...]`
  > : The same as `node.removeChildren()`; `node.addChild(node1)`; `node.addChild(node2)` (since 0.7.11).
  <br/>
  > `node.$tags$abc`
  > : All child tags named `abc` of the node, writable since 0.7.11.
  <br/>
  > `node.$text`
  > : The content of the node, writable since 0.7.11.
  <br/>
  > `node.$text = 'abc'`
  > : The same as `node.setText('abc')` (since 0.7.11).
  <br/>
  > `node.addChild(nd)`
  > : Adds an XMLNode as a child to the node (since 0.7.11). `nd` is recursively copied before adding to the node.
  <br/>
  > `node.removeAllAttributes()`
  > : Removes all attributes of the node (since 0.7.11).
  <br/>
  > `node.removeAttribute(attr_name)`
  > : Removes the attribute named `attr_name` (since 0.7.11).
  <br/>
  > `node.removeChildren(tag_name)`
  > : Removes all child tags named `tag_name` (since 0.7.11). If `tag_name` is absent, all child tags are removed.
  <br/>
  > `node.removeText()`
  > : Removes the node's text value (0.7.11).
  <br/>
  > `node.setAttribute(attr_name, value)`
  > : Sets a value for `attr_name` (since 0.7.11). When the value is `null`, the attribute named `attr_name` is deleted.
  <br/>
  > `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.
  <br/>
  > `attr.abc`
  > : The attribute value of `abc`.

<a id="njs-zlib"></a>

### 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:

```javascript
import zlib from 'zlib';

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

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