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. 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. 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 is converted to More advanced parsing scenarios can be achieved with the Query String module and with the The argument object is evaluated at the first access to Here, Angie variables object returns the first value for a given key, case-insensitive, without percent-decoding. To convert After calling this function, the next data chunks will be passed to the client without calling Writes a Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. Finishes sending a response to the client. Incoming headers object, read-only. The The Outgoing headers object for the main request, writable. If The Outgoing headers should be set before a response header is sent to a client; otherwise, the header update will be ignored. This means that the the Field values of multi-value response headers (0.4.0) can be set with the syntax: where the output will be: All previous field values of the For standard response headers that accept only a single field value such as HTTP version, read-only. Boolean value, Performs an internal redirect to the specified 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 Note Since 0.7.4, the method accepts escaped URIs. Writes a Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. HTTP method, read-only. References the parent request object. Client address, read-only. The property was made obsolete in 0.5.0 and was removed in 0.8.0. The 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 The same as 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: the output of All the output will be: Header field names are not converted to lower case, duplicate field values are not merged. 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. The property was made obsolete in 0.5.0 and was removed in 0.8.0. The Holds the subrequest response body, read-only (since 0.5.0). The size of The same as Sends the entire response with the specified 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. Sends a part of the response body to the client. The data sent can be a string or Buffer (0.5.0). 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 Boolean, Boolean, The method may be called only from the Sends the HTTP headers to the client. Sets the return value of the Status, writable. Creates a subrequest with the given A subrequest shares its input headers with the client request. To send headers different from original headers to a proxied server, the If Arguments string, by default an empty string is used. Request body, by default the request body of the parent request object is used. HTTP method, by default the Boolean flag (0.3.9); if The completion Since 0.3.8, if a For example, to view all response headers in the subrequest: Current URI in request, normalized, read-only. Angie variables as Buffers, writable (since 0.5.0). Angie variables object, writable (since 0.2.8). For example, to get the Since 0.8.6, regular expression captures can be accessed using the following syntax: Angie treats variables referenced in the A variable is writable if: it was created using the it is referenced in Angie configuration file Even so, some embedded variables still cannot be assigned a value (for example, Writes a Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. 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. An alias to An alias to An alias to Sets an exit Possible code values: May be called only from a phase handler function: Writes a sent Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. Writes a sent Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. Unregisters the callback set by the Registers a An New data (string) from a client. New data (string) to a client. New data (Buffer) from a client (since 0.5.0). New data (Buffer) to a client (since 0.5.0). The completion callback has the following prototype: A boolean value, Client address, read-only. Angie variables as Buffers, writable (since 0.5.0). 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 Boolean, Boolean, The method can be called multiple times per callback invocation. Identical to Identical to Session status code, an alias to the Sets the return value of the 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. Writes a sent Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. The Angie variables as Buffers, writable. Angie variables object, writable. The A new An object containing HTTP headers for prepopulating the A new Appends a new value into an existing header in the Deletes a header from the Returns a string containing the values of all headers with the specified name separated by a comma and a space. Returns an array containing the values of all headers with the specified name. Executes a provided function once for each key/value pair in the Returns a boolean value indicating whether a header with the specified name exists. Sets a new value for an existing header inside the The A new Creates a The request body, by default is empty. The response headers object — the object containing HTTP headers for prepopulating the The HTTP method, by default the GET method is used. A new Returns a A boolean value, Contains the cache mode of the request. Contains the credentials of the request, by default is The Returns a Contains the request method. Contains the mode of the request. Returns a Contains the URL of the request. The A new Creates a The response headers object — the object containing HTTP headers for prepopulating the The status code of the response. The status message corresponding to the status code. A new Takes a A boolean value, The Takes a A boolean value, A boolean value, The status code of the response. The status message corresponding to the status code. Takes a The type of the response. The URL of the response. The A string containing an optional Angie build name, corresponds to the A string containing the file path to current Angie configuration file (0.8.0). A string containing the file path to Angie configuration prefix — the directory where Angie is currently looking for configuration (0.7.8). A string containing the file path to the current error log file (0.8.0). Makes a request to fetch a If the URL in the The Request body, by default is empty. The buffer size for reading the response, by default is Request headers object. The maximum size of the response body in bytes, by default is HTTP method, by default the Enables or disables verification of the HTTPS server certificate, by default is Example: Writes a message to the error log with the specified level of logging. The Note As Angie has a hardcoded maximum line length limit, only the first 2048 bytes of the string can be logged. A string containing the file path to Angie prefix — a directory that keeps server files (0.8.0). A string containing Angie version, for example: A number containing Angie version, for example: A number that corresponds to Angie internal worker ID, the value is between The Outputs one or more error messages. The message may be a string or an object. Outputs one or more info messages. The message may be a string or an object. Outputs one or more log messages. The message may be a string or an object. Starts a timer that can track how long an operation takes. The Stops a timer previously started by Outputs one or more warning messages. The message may be a string or an object. The Gets cryptographically strong random values. Returns the same array passed as Can be Encrypts An object that specifies the algorithm to be used and any extra parameters if required: For A string, should be set to For A string, should be set to An 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 A string, should be set to Or the initialization vector, is an For A string, should be set to Or the initialization vector, is an (optional) is an (optional, default is A An Decrypts encrypted data. Returns a 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 For A string, should be set to For A string, should be set to An 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 A string, should be set to Or the initialization vector, is an For A string, should be set to Or the initialization vector, is an (optional) is an (optional, default is A An Derives an array of bits from a base key. Returns a Is an object that defines the derivation algorithm to use: For A string, should be set to A string with the digest algorithm to use: An An For A string, should be set to A string with the digest algorithm to use: An A For A string, should be set to A Is a Is a number representing the number of bits to derive. For browser compatibility, the number should be a multiple of Derives a secret key from a master key. Possible values: Is an object that defines the derivation algorithm to use: For A string, should be set to A string with the digest algorithm to use: An An For A string, should be set to A string with the digest algorithm to use: An A For A string, should be set to A Is a Is an object that defines the algorithm the derived key will be used for: For A string, should be set to A string with the name of the digest function to use: (optional) is a For A string, should be set to A Is a boolean value that indicates whether it will be possible to export the key. Is an Key for encrypting messages. Key for decrypting messages. Key for signing messages. Key for verifying signatures. Key for deriving a new key. Key for deriving bits. Key for wrapping a key. Key for unwrapping a key. 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 Is a string that defines the hash function to use: Is an Exports a key: takes a key as a A string that describes the data format in which the key should be exported, can be the following: The raw data format. The PKCS #8 format. The SubjectPublicKeyInfo format. The JSON Web Key (JWK) format (since 0.7.10). The Generates a new key for symmetric algorithms or key pair for public-key algorithms (since 0.7.10). Returns a A dictionary object that defines the type of key to generate and provides extra algorithm-specific parameters: For A string, should be set to A string that represents the name of the For A string, should be set to A string that represents the name of the elliptic curve to use, may be For A string, should be set to A string that represents the name of the (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 For A string, should be set to A string that represents the name of the elliptic curve to use, may be Boolean value that indicates if it is possible to export the key. An Key for encrypting messages. Key for decrypting messages. Key for signing messages. Key for verifying signatures. Key for deriving a new key. Key for deriving bits. Key for wrapping a key. Key for unwrapping a key. Imports a key: takes as input a key in an external, portable format and gives a A string that describes the data format of the key to import, can be the following: The raw data format. The PKCS #8 format. The SubjectPublicKeyInfo format. The JSON Web Key (JWK) format (since 0.7.10). The A dictionary object that defines the type of key to import and provides extra algorithm-specific parameters: For A string, should be set to A string that represents the name of the For A string, should be set to A string that represents the name of the elliptic curve to use, may be For A string, should be set to A string that represents the name of the (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 For For For A string, should be set to A string that represents the name of the elliptic curve to use, may be Boolean value that indicates if it is possible to export the key. An Key for encrypting messages. Key for decrypting messages. Key for signing messages. Key for verifying signatures. Key for deriving a new key. Key for deriving bits. Key for wrapping a key. Key for unwrapping a key. Returns Is a string or object that specifies the signature algorithm to use and its parameters: For For A string, should be set to A long For A string, should be set to An identifier for the digest algorithm to use, can be For Is a Is an Verifies a digital signature; returns a Is a string or object that specifies the algorithm to use and its parameters: For For A string, should be set to A long For A string, should be set to An identifier for the digest algorithm to use, can be For Is a Is an Is an The Returns an object describing the algorithm for which this key can be used and any associated extra parameters (since 0.8.0), read-only. A boolean value, A string value that indicates which kind of key is represented by the object, read-only. Possible values: This key is a secret key for use with a symmetric algorithm. This key is the private half of an asymmetric algorithm's This key is the public half of an asymmetric algorithm's An array of strings indicating what this key can be used for (since 0.8.0), read-only. Possible array values: Key for encrypting messages. Key for decrypting messages. Key for signing messages. Key for verifying signatures. Key for deriving a new key. Key for deriving bits. The A A The Returns a string with the current version of NJS (for example, "0.7.4"). Returns a number with the current version of NJS. For example, "0.7.4" is returned as Returns the pretty-print string representation for a value. Object containing memory statistics for the current VM instance (since 0.7.8). Amount of memory in bytes NJS memory pool claimed from the operating system. Registers a callback for the specified VM event (since 0.5.2). An event may be one of the following strings: Is called before the VM is destroyed. The callback is called without arguments. The Returns an array that contains the command-line arguments passed when the current process was launched. 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 Sends the signal to the process identified by Returns the PID of the current process. Returns the PID of the current parent process. 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. 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 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 The following methods were made obsolete and removed in 0.8.0: The Creates a new Boolean flag indicating if Returns a string with the name of the encoding used by Boolean flag, Boolean flag, Returns a string with the text decoded from the Boolean flag indicating if additional data will follow in subsequent calls to Example: The Returns a newly constructed Encodes Encodes a The number of UTF-16 units of code from the source The number of bytes modified in the destination Cancels a Calls a Example: Decodes a string of data which has been encoded using The similar Example: Creates a Base64-encoded ASCII string from a binary string. The The method can be used to encode data which may otherwise cause communication problems, transmit it, then use the Example: The For detailed documentation of Buffer methods, please refer to Node.js Buffer documentation. The Crypto module provides cryptographic functionality support. The Crypto module object is imported using Note Since 0.7.0, extended crypto API is available as a global crypto object. Creates and returns a Hash object that can be used to generate hash digests using the given Creates and returns an HMAC object that uses the given Updates the hash content with the given Calculates the digest of all of the data passed using Note Before version (0.4.4), a byte string was returned instead of a Buffer object. Makes a copy of the current state of the hash (since 0.7.12). Example: Updates the HMAC content with the given Calculates the HMAC digest of all of the data passed using Note Before version 0.4.4, a byte string was returned instead of a Buffer object. The For detailed documentation of fs methods, please refer to Node.js fs documentation. The Query String module provides methods for parsing and formatting URL query strings. The module object is imported using An alias to An alias to Performs URL percent-encoding of the Parses the Function to use when decoding percent-encoded characters in the query string, default: The maximum number of keys to parse, default: Example: Produces a URL query string from the Function to use when converting URL-unsafe characters to percent-encoding in the query string, default: Example: Performs decoding of URL percent-encoded characters in the The XML module allows working with XML documents (since 0.7.10). The XML module object is imported using Example: Parses a string or Buffer for an XML document; returns an Canonicalizes Allows omitting from the output a part of the document. Canonicalizes Is Allows omitting from the output a part of the document corresponding to the node and its children. A boolean value, An optional string with a space-separated namespace prefixes for namespaces that should also be included in the output. The same as The same as An XMLDoc wrapper object around XML structure, the root node of the document. The document's root by its name or undefined. The first root tag named An XMLNode wrapper object around XML tag node. The same as The node's attribute value of The same as An The name of the node. The namespace of the node. The parent node of the current node. The first child tag of the node named An array of all children tags. The same as All children tags named The content of the node, writable since 0.7.11. The same as Adds XMLNode as a child to node (since 0.7.11). Removes all attributes of the node (since 0.7.11). Removes the attribute named Removes all the children tags named Removes the node's text value (0.7.11). Sets a value for an Sets a text value for the node (since 0.7.11). When the value is An XMLAttrs wrapper object around XML node attributes. The attribute value of The Returns a dictionary of zlib constants. Compresses Compresses Decompresses Decompresses The Compression level (default: Specifies how much memory should be allocated for the compression state (default: Tunes the compression algorithm (default: Sets the window size (default: Buffer containing the predefined compression dictionary. A boolean value, if Chunk size for compression (default: Example:Angie Objects#
HTTP Request#
r.args{}r.done()r.error()r.finish()r.headersIn{}r.headersOut{}r.httpVersionr.internalr.internalRedirect()r.log()r.methodr.parentr.remoteAddressr.requestBodyr.requestBufferr.requestTextr.rawHeadersIn[]r.rawHeadersOut[]r.responseBodyr.responseBufferr.responseTextr.return()r.send()r.sendBuffer()r.sendHeader()r.setReturnValue()r.statusr.subrequest()r.urir.rawVariables{}r.variables{}r.warn()r.args{}a=1&b=%32&A=3&b=4&B=two%20words
r.args as:{a: "1", b: ["2", "4"], A: "3", B: "two words"}
$args variable, for example:import qs from 'querystring';
function args(r) {
return qs.parse(r.variables.args);
}
r.args. If only a single argument is needed, for example foo, Angie variables can be used:r.variables.arg_foo
r.args back to a string, the Query String stringify method can be used.r.done()js_body_filter (0.5.2). May be called only from the js_body_filter function.r.error(string)string to the error log on the error level of logging.r.finish()r.headersIn{}Foo request header can be accessed with the syntax: headersIn.foo or headersIn['Foo'].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{}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.Foo response header can be accessed with the syntax: headersOut.foo or headersOut['Foo'].r.headersOut{} is effectively writable in:js_content handler before r.sendHeader() or r.return() are calledjs_header_filter handlerr.headersOut['Foo'] = ['a', 'b']
Foo: a
Foo: b
Foo response header will be deleted.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.httpVersionr.internaltrue for internal locations.r.internalRedirect(uri)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.js_var directive for HTTP or Stream can be used.r.log(string)string to the error log on the info level of logging.r.methodr.parentr.remoteAddressr.requestBodyr.requestBuffer or r.requestText property should be used instead.r.requestBufferclient_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.requestTextr.requestBuffer, but returns a string. Note that it may convert bytes invalid in UTF-8 encoding into the replacement character.r.rawHeadersIn[]Host: localhost
Foo: bar
foo: bar2
r.rawHeadersIn will be:[
['Host', 'localhost'],
['Foo', 'bar'],
['foo', 'bar2']
]
foo headers can be collected with the syntax:r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1])
['bar', 'bar2']
r.rawHeadersOut[]r.responseBodyr.responseBuffer or the r.responseText property should be used instead.r.responseBufferr.responseBuffer is limited by the subrequest_output_buffer_size directive.r.responseTextr.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])status to the client. The response can be a string or Buffer (0.5.0).r.send(string | Buffer)r.sendBuffer(data[, options])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:lasttrue if the buffer is the last buffer.flushtrue if the buffer should have the flush flag.js_body_filter function.r.sendHeader()r.setReturnValue(value)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.statusr.subrequest(uri[, options[, callback]])uri and options, and installs an optional completion callback.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.options is a string, then it holds the subrequest arguments string. Otherwise, options is expected to be an object with the following keys:argsbodymethodGET method is used.detachedtrue, 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.callback receives a subrequest response object with methods and properties identical to the parent request object.callback is not provided, the Promise object that resolves to the subrequest response object is returned.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.urir.rawVariables{}r.variables{}$foo variable, one of the following syntax can be used:r.variables['foo']
r.variables.foo
r.variables['1']
r.variables[1]
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;
r.variables.request_id returns the same value every time.js_var directive for HTTP or Stream (since 0.5.3)$http_).r.warn(string)string to the error log on the warning level of logging.Stream Session#
s.allow()s.decline()s.deny()s.done()s.error()s.log()s.off()s.on()s.remoteAddresss.rawVariables{}s.send()s.sendDownstream()s.sendUpstream()s.statuss.setReturnValue()s.variables{}s.warn()s.allow()s.done(0) (0.2.4).s.decline()s.done(-5) (0.2.4).s.deny()s.done(403) (0.2.4).s.done([code])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).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 forbiddenjs_access or js_preread.s.error(string)string to the error log on the error level of logging.s.log(string)string to the error log on the info level of logging.s.off(eventName)s.on() method (0.2.4).s.on(event, callback)callback for the specified event (0.2.4).event may be one of the following strings:uploaddownloadupstreamdownstreamcallback(data, flags), where data is string or Buffer (depending on the event type); flags is an object with the following properties:lasttrue if data is a last buffer.s.remoteAddresss.rawVariabless.send(data[, options])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:lasttrue if the buffer is the last buffer.flushtrue if the buffer should have the flush flag.s.sendDownstream()s.send(), except for it always sends data to a client (since 0.7.8).s.sendUpstream()s.send(), except for it always sends data from a client (since 0.7.8).s.status$status variable, read-only (since 0.5.2).s.setReturnValue(value)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{}s.warn(string)string to the error log on the warning level of logging.Periodic Session#
PeriodicSession.rawVariables{}PeriodicSession.variables{}Periodic Session object is provided as the first argument for the js_periodic handler for HTTP and Stream (since 0.8.1).PeriodicSession.rawVariables{}PeriodicSession.variables{}Headers#
Headers()Headers.append()Headers.delete()Headers.get()Headers.getAll()Headers.forEach()Headers.has()Headers.set()Headers interface of the Fetch API is available since 0.5.1.Headers object can be created using the Headers() constructor (since 0.7.10):Headers([init])initHeaders object, can be a string, an array of name-value pairs, or an existing Headers object.Headers object can be created with the following properties and methods:append()Headers object, or adds the header if it does not already exist (since 0.7.10).delete()Headers object (since 0.7.10).get()getAll(name)forEach()Headers object (since 0.7.10).has()set()Headers object, or adds the header if it does not already exist (since 0.7.10).Request#
Request()Request.arrayBuffer()Request.bodyUsedRequest.cacheRequest.credentialsRequest.headersRequest.json()Request.methodRequest.modeRequest.text()Request.urlRequest interface of the Fetch API is available since 0.7.10.Request object can be created using the Request() constructor:Request[resource[, options]])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:bodyheadersHeaders object, can be a string, an array of name-value pairs, or an existing Headers object.methodRequest object can be created with the following properties and methods:arrayBuffer()Promise that resolves with an ArrayBuffer.bodyUsedtrue if the body was used in the request.cachecredentialssame-origin.headersHeaders read-only object associated with the Request.json()Promise that resolves with the result of parsing the request body as JSON.methodmodetext()Promise that resolves with a string representation of the request body.urlResponse#
Response()Response.arrayBuffer()Response.bodyUsedResponse.headersResponse.json()Response.okResponse.redirectedResponse.statusResponse.statusTextResponse.text()Response.typeResponse.urlResponse interface is available since 0.5.1.Response object can be created using the Response() constructor (since 0.7.10):Response[body[, options]])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:headersHeaders object, can be a string, an array of name-value pairs, or an existing Headers object.statusstatusTextResponse() object can be created with the following properties and methods:arrayBuffer()Response stream and reads it to completion. Returns a Promise that resolves with an ArrayBuffer.bodyUsedtrue if the body was read.headersHeaders read-only object associated with the Response.json()Response stream and reads it to completion. Returns a Promise that resolves with the result of parsing the body text as JSON.oktrue if the response was successful (status codes between 200–299).redirectedtrue if the response is the result of a redirect.statusstatusTexttext()Response stream and reads it to completion. Returns a Promise that resolves with a string.typeurlngx#
ngx.buildngx.conf_file_pathngx.conf_prefixngx.error_log_pathngx.fetch()ngx.log()ngx.prefixngx.versionngx.version_numberngx.worker_idngx global object is available since 0.5.0.ngx.build--build=name argument of the configure script, by default is "" (0.8.0).ngx.conf_file_pathngx.conf_prefixngx.error_log_pathngx.fetch(resource, [options])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.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.options parameter is expected to be an object with the following keys:bodybuffer_size4096.headersmax_response_body_size32768.methodGET method is used.verifytrue (0.7.0).let reply = await ngx.fetch('http://example.com/');
let body = await reply.text();
r.return(200, body);
ngx.log(level, message)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.ngx.prefixngx.version1.25.0 (0.8.0).ngx.version_number1025000 (0.8.0).ngx.worker_id0 and the value specified in the worker_processes directive (0.8.0).Built-in Objects#
console#
console.error()console.info()console.log()console.time()console.timeEnd()console.warn()console object is available in Angie since 0.8.2, in CLI since 0.2.6.console.error(msg[, msg2 ...])console.info(msg[, msg2 ...])console.log(msg[, msg2 ...])console.time(label)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)console.time(). The label parameter allows naming different timers.console.warn(msg[, msg2 ...])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()crypto object is a global object that allows using cryptographic functionality (since 0.7.0).crypto.getRandomValues(typedArray)typedArray but with its contents replaced with the newly generated random numbers. Possible values:typedArrayInt8Array, Int16Array, Uint16Array, Int32Array, or Uint32Array.crypto.subtle.encrypt(algorithm, key, data)data using the provided algorithm and key. Returns a Promise that fulfills with an ArrayBuffer containing the ciphertext. Possible values:algorithmRSA-OAEP, pass the object with the following keys:nameRSA-OAEP:crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
AES-CTR, pass the object with the following keys:nameAES-CTR.counterArrayBuffer, 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.lengthAES-CBC, pass the object with the following keys:nameAES-CBC.ivArrayBuffer, 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.AES-GCM, pass the object with the following keys:nameAES-GCM.ivArrayBuffer, TypedArray, or DataView, must be 16 bytes, and must be unique for every encryption operation carried out with a given key.additionalDataArrayBuffer, 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.tagLength128) - 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.keyCryptoKey that contains the key to be used for encryption.dataArrayBuffer, TypedArray, or DataView that contains the data to be encrypted (also known as the plaintext).crypto.subtle.decrypt(algorithm, key, data)Promise with the decrypted data. Possible values:algorithmencrypt() call.RSA-OAEP, pass the object with the following keys:nameRSA-OAEP:crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
AES-CTR, pass the object with the following keys:nameAES-CTR.counterArrayBuffer, 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.lengthAES-CBC, pass the object with the following keys:nameAES-CBC.ivArrayBuffer, 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).AES-GCM, pass the object with the following keys:nameAES-GCM.ivArrayBuffer, TypedArray, or DataView, must be 16 bytes, and must be unique for every encryption operation carried out with a given key.additionalDataArrayBuffer, 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.tagLength128) - 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.keyCryptoKey that contains the key to be used for decryption. If RSA-OAEP is used, this is the privateKey property of the CryptoKeyPair object.dataArrayBuffer, TypedArray, or DataView that contains the data to be decrypted (also known as ciphertext).crypto.subtle.deriveBits(algorithm, baseKey, length)Promise which will be fulfilled with an ArrayBuffer that contains the derived bits. Possible values:algorithmHKDF, pass the object with the following keys:nameHKDF.hashSHA-1, SHA-256, SHA-384, or SHA-512.saltArrayBuffer, 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.infoArrayBuffer, 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.PBKDF2, pass the object with the following keys:namePBKDF2.hashSHA-1, SHA-256, SHA-384, or SHA-512.saltArrayBuffer, 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.iterationsnumber that represents the number of times the hash function will be executed in deriveKey().ECDH, pass the object with the following keys (since 0.9.1):nameECDH.publicCryptoKey that represents the public key of the other party. The key must be generated using the same curve as the base key.baseKeyCryptoKey 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().length8.crypto.subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)algorithmHKDF, pass the object with the following keys:nameHKDF.hashSHA-1, SHA-256, SHA-384, or SHA-512.saltArrayBuffer, 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.infoArrayBuffer, 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.PBKDF2, pass the object with the following keys:namePBKDF2.hashSHA-1, SHA-256, SHA-384, or SHA-512.saltArrayBuffer, 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.iterationsnumber that represents the number of times the hash function will be executed in deriveKey().ECDH, pass the object with the following keys (since 0.9.1):nameECDH.publicKeyCryptoKey that represents the public key of the other party. The key must be generated using the same curve as the base key.baseKeyCryptoKey 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().derivedKeyAlgorithmHMAC, pass the object with the following keys:nameHMAC.hashSHA-1, SHA-256, SHA-384, or SHA-512.lengthnumber 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.AES-CTR, AES-CBC, or AES-GCM, pass the object with the following keys:nameAES-CTR, AES-CBC, or AES-GCM, depending on the algorithm used.lengthnumber that represents the length in bits of the key to generate: 128, 192, or 256.extractablekeyUsagesArray that indicates what can be done with the derived key. The key usages must be allowed by the algorithm set in derivedKeyAlgorithm. Possible values:encryptdecryptsignverifyderiveKeyderiveBitswrapKeyunwrapKeycrypto.subtle.digest(algorithm, data)Promise which will be fulfilled with the digest. Possible values:algorithmSHA-1 (not for cryptographic applications), SHA-256, SHA-384, or SHA-512.dataArrayBuffer, TypedArray, or DataView that contains the data to be digested.crypto.subtle.exportKey(format, key)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:formatrawpkcs8spkijwkkeyCryptoKey that contains the key to be exported.crypto.subtle.generateKey(algorithm, extractable, usage)Promise that fulfills with the generated key as a CryptoKey or CryptoKeyPair object. Possible values:algorithmRSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, pass the object with the following keys:nameRSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, depending on the used algorithm.hashdigest function to use, can be SHA-256, SHA-384, or SHA-512.ECDSA, pass the object with the following keys:nameECDSA.namedCurveP-256, P-384, or P-521.HMAC, pass the object with the following keys:nameHMAC.hashdigest function to use, can be SHA-256, SHA-384, or SHA-512.lengthAES-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.ECDH, pass the object with the following keys (since 0.9.1):nameECDH.namedCurveP-256, P-384, or P-521.extractableusagearray that indicates possible actions with the key:encryptdecryptsignverifyderiveKeyderiveBitswrapKeyunwrapKeycrypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages)CryptoKey object. Returns a Promise that fulfills with the imported key as a CryptoKey object. Possible values:formatrawpkcs8spkijwkkeyDataArrayBuffer, TypedArray, or DataView object that contains the key in the given format.algorithmRSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, pass the object with the following keys:nameRSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP, depending on the used algorithm.hashdigest function to use, can be SHA-1, SHA-256, SHA-384, or SHA-512.ECDSA, pass the object with the following keys:nameECDSA.namedCurveP-256, P-384, or P-521.HMAC, pass the object with the following keys:nameHMAC.hashdigest function to use, can be SHA-256, SHA-384, or SHA-512.lengthAES-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.PBKDF2, pass the PBKDF2 string.HKDF, pass the HKDF string.ECDH, pass the object with the following keys (since 0.9.1):nameECDH.namedCurveP-256, P-384, or P-521.extractablekeyUsagesarray that indicates possible actions with the key:encryptdecryptsignverifyderiveKeyderiveBitswrapKeyunwrapKeycrypto.subtle.sign(algorithm, key, data)signature as a Promise that fulfills with an ArrayBuffer containing the signature. Possible values:algorithmRSASSA-PKCS1-v1_5, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .RSA-PSS, pass the object with the following keys:nameRSA-PSS.saltLengthinteger that represents the length of the random salt to use, in bytes.ECDSA, pass the object with the following keys:nameECDSA.hashSHA-256, SHA-384, or SHA-512.HMAC, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .keyCryptoKey object that the key to be used for signing. If algorithm identifies a public-key cryptosystem, this is the private key.dataArrayBuffer, TypedArray, or DataView object that contains the data to be signed.crypto.subtle.verify(algorithm, key, signature, data)Promise that fulfills with a boolean value: true if the signature is valid, otherwise false. Possible values:algorithmRSASSA-PKCS1-v1_5, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .RSA-PSS, pass the object with the following keys:nameRSA-PSS.saltLengthinteger that represents the length of the random salt to use, in bytes.ECDSA, pass the object with the following keys:nameECDSA.hashSHA-256, SHA-384, or SHA-512.HMAC, pass the string identifying the algorithm or an object of the form "name": "ALGORITHM" .keyCryptoKey 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.signatureArrayBuffer, TypedArray, or DataView that contains the signature to verify.dataArrayBuffer, TypedArray, or DataView object that contains the data whose signature is to be verified.CryptoKey#
CryptoKey.algorithmCryptoKey.extractableCryptoKey.typeCryptoKey.usagesCryptoKey object represents a cryptographic key obtained from one of the SubtleCrypto methods: crypto.subtle.generateKey(), crypto.subtle.deriveKey(), crypto.subtle.importKey().CryptoKey.algorithmCryptoKey.extractabletrue if the key can be exported (since 0.8.0), read-only.CryptoKey.typesecretprivateCryptoKeyPair.publicCryptoKeyPair.CryptoKey.usagesencryptdecryptsignverifyderiveKeyderiveBitsCryptoKeyPair#
CryptoKeyPair.privateKeyCryptoKeyPair.publicKeyCryptoKeyPair is a dictionary object of the WebCrypto API that represents an asymmetric key pair.CryptoKeyPair.privateKeyCryptoKey object representing the private key.CryptoKeyPair.publicKeyCryptoKey object representing the public key.njs#
njs.versionnjs.version_numbernjs.dump()njs.memoryStatsnjs.on()njs object is a global object that represents the current VM instance (since 0.2.0).njs.versionnjs.version_number0x000704 (since 0.7.4).njs.dump(value)njs.memoryStatssizenjs.on(event, callback)exitprocess#
process.argvprocess.envprocess.kill()process.pidprocess.ppidprocess object is a global object that provides information about the current process (0.3.3).process.argvprocess.envenv directive to preserve some of the inherited variables.process.kill(pid, number | string)pid. Signal names are numbers or strings such as 'SIGINT' or 'SIGHUP'. See kill(2) for more information.process.pidprocess.ppidString#
Byte Strings (Removed)#
r.requestBuffer, r.rawVariables, should be used.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.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.encodingTextDecoder.prototype.fatalTextDecoder.prototype.ignoreBOMTextDecoder.prototype.decode()TextDecoder produces a stream of code points from a stream of bytes (0.4.3).TextDecoder([[encoding], options])TextDecoder object for specified encoding; currently, only UTF-8 is supported. The options is TextDecoderOptions dictionary with the property:fatalTextDecoder.decode() must throw the TypeError exception when a coding error is found, by default is false.TextDecoder.prototype.encodingTextDecoder(), read-only.TextDecoder.prototype.fataltrue if the error mode is fatal, read-only.TextDecoder.prototype.ignoreBOMtrue if the byte order marker is ignored, read-only.TextDecoder.prototype.decode(buffer, [options])buffer by TextDecoder(). The buffer can be ArrayBuffer. The options is TextDecodeOptions dictionary with the property:streamdecode(): true if processing the data in chunks, and false for the final chunk or if the data is not chunked. By default is false.>> (new TextDecoder()).decode(new Uint8Array([206,177,206,178]))
αβ
TextEncoder#
TextEncoder()TextEncoder.prototype.encode()TextEncoder.prototype.encodeInto()TextEncoder object produces a byte stream with UTF-8 encoding from a stream of code points (0.4.3).TextEncoder()TextEncoder that will generate a byte stream with UTF-8 encoding.TextEncoder.prototype.encode(string)string into a Uint8Array with UTF-8 encoded text.TextEncoder.prototype.encodeInto(string, uint8Array)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:readstring converted to UTF-8.writtenUint8Array.Timers#
clearTimeout()setTimeout()clearTimeout(timeout)timeout object created by setTimeout().setTimeout(function, milliseconds[, argument1, argumentN])function after a specified number of milliseconds. One or more optional arguments can be passed to the specified function. Returns a timeout object.function handler(v)
{
// ...
}
t = setTimeout(handler, 12);
// ...
clearTimeout(t).
Global Functions#
atob()btoa()atob(encodedData)Base64 encoding. The encodedData parameter is a binary string that contains Base64-encoded data. Returns a string that contains decoded data from encodedData.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.const encodedData = btoa("text to encode"); // encode a string
const decodedData = atob(encodedData); // decode the string
btoa(stringToEncode)stringToEncode parameter is a binary string to encode. Returns an ASCII string containing the Base64 representation of stringToEncode.atob() method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.const encodedData = btoa("text to encode"); // encode a string
const decodedData = atob(encodedData); // decode the string
Built-in Modules#
Buffer#
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.bufferbuf.byteOffsetbuf.compare()buf.copy()buf.equals()buf.fill()buf.includes()buf.indexOf()buf.lastIndexOf()buf.lengthbuf.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()Crypto#
import crypto from 'crypto'.crypto.createHash()crypto.createHmac()crypto.createHash(algorithm)algorithm. The algorithm can be md5, sha1, and sha256.crypto.createHmac(algorithm, secret key)algorithm and secret key. The algorithm can be md5, sha1, and sha256.Hash#
hash.update()hash.digest()hash.update(data)data.hash.digest([encoding])hash.update(). The encoding can be hex, base64, and base64url. If encoding is not provided, a Buffer object (0.4.4) is returned.hash.copy()import crypto from 'crypto';
crypto.createHash('sha1').update('A').update('B').digest('base64url');
/* BtlFlCqiamG-GMPiK_GbvKjdK10 */
HMAC#
hmac.update()hmac.digest()hmac.update(data)data.hmac.digest([encoding])hmac.update(). The encoding can be hex, base64, and base64url. If encoding is not provided, a Buffer object (0.4.4) is returned.fs#
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()Query String#
import qs from 'querystring'.querystring.decode()querystring.encode()querystring.escape()querystring.parse()querystring.stringify()querystring.unescape()querystring.decode()querystring.parse().querystring.encode()querystring.stringify().querystring.escape(string)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]]])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:decodeURIComponentquerystring.unescape().maxKeys1000. The 0 value removes limitations for counting keys.>> qs.parse('foo=bar&abc=xyz&abc=123')
{
foo: 'bar',
abc: ['xyz', '123']
}
querystring.stringify(object[, separator[, equal[, options]]])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:encodeURIComponentquerystring.escape().>> qs.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
'foo=bar&baz=qux&baz=quux&corge='
querystring.unescape(string)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()XMLDocXMLNodeXMLAttrimport xml from 'xml'.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)XMLDoc wrapper object representing the parsed XML document.c14n(root_node[, excluding_node])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_nodeexclusiveC14n(root_node[, excluding_node[, withComments[,prefix_list]]])root_node and its children according to Exclusive XML Canonicalization Version 1.0.root_nodeXMLNode or XMLDoc wrapper object around XML structure.excluding_nodewithCommentsfalse by default. If true, canonicalization corresponds to Exclusive XML Canonicalization Version 1.0. Returns Buffer object that contains canonicalized output.prefix_listserialize()xml.c14n() (since 0.7.11).serializeToString()xml.c14n() except it returns the result as a string (since 0.7.11).XMLDocdoc.$rootdoc.abcabc as XMLNode wrapper object.XMLNodenode.abcnode.$tag$abc.node.$attr$abcabc, writable since 0.7.11.node.$attr$abc=xyznode.setAttribute('abc', xyz) (since 0.7.11).node.$attrsXMLAttr wrapper object for all attributes of the node.node.$namenode.$nsnode.$parentnode.$tag$abcabc, writable since 0.7.11.node.$tagsnode.$tags = [node1, node2, ...]node.removeChildren(); node.addChild(node1); node.addChild(node2) (since 0.7.11).node.$tags$abcabc of the node, writable since 0.7.11.node.$textnode.$text = 'abc'node.setText('abc') (since 0.7.11).node.addChild(nd)nd is recursively copied before adding to the node.node.removeAllAttributes()node.removeAttribute(attr_name)attr_name (since 0.7.11).node.removeChildren(tag_name)tag_name (since 0.7.11). If tag_name is absent, all children tags are removed.node.removeText()node.setAttribute(attr_name, value)attr_name (since 0.7.11). When the value is null, the attribute named attr_name is deleted.node.setText(value)null, the text of the node is deleted.XMLAttrattr.abcabc.zlib#
zlib module (0.5.2) provides compression and decompression functionality using zlib. The module object is imported using import zlib from 'zlib'.zlib.constantszlib.deflateRawSync()zlib.deflateSync()zlib.inflateRawSync()zlib.inflateSync()zlib.constantszlib.deflateRawSync(data[, options])data using the Deflate algorithm without the zlib header.zlib.deflateSync(data[, options])data using the Deflate algorithm.zlib.inflateRawSync(data[, options])data using the Deflate algorithm without the zlib header.zlib.inflateSync(data[, options])data using the Deflate algorithm.options parameter is an object that may contain the following properties:levelzlib.constants.Z_DEFAULT_COMPRESSION).memLevelzlib.constants.Z_DEFAULT_MEMLEVEL).strategyzlib.constants.Z_DEFAULT_STRATEGY).windowBitszlib.constants.Z_DEFAULT_WINDOWBITS).dictionaryinfotrue, returns an object with buffer and engine.chunkSizezlib.constants.Z_DEFAULT_CHUNK).import zlib from 'zlib';
const deflated = zlib.deflateSync('Hello World!');
const inflated = zlib.inflateSync(deflated);
console.log(inflated.toString()); // 'Hello World!'