Reference

nginx objects
     HTTP Request
     Stream Session
Core
     Global
     Object
     String
     TypedArray
     JSON
     Crypto
     Timers
     File System

njs provides objects, methods and properties for extending nginx functionality.

nginx objects

HTTP Request

The HTTP request object is available only in the ngx_http_js_module module. All string properties of the object are byte strings.

r.args{}
request arguments object, read-only
r.error(string)
writes a string to the error log on the error level of logging
r.finish()
finishes sending a response to the client
r.headersIn{}
incoming headers object, read-only.

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

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

r.headersOut{}
outgoing headers object, writable.

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

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

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

where the output will be:

Foo: a
Foo: b

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

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

r.httpVersion
HTTP version, read-only
r.internalRedirect(uri)
performs an internal redirect to the specified uri. If the uri starts with the “ @” prefix, it is considered a named location. The actual redirect happens after the handler execution is completed.
r.log(string)
writes a string to the error log on the info level of logging
r.method
HTTP method, read-only
r.parent
references the parent request object
r.remoteAddress
client address, read-only
r.rawHeadersIn{}
returns an array of key-value pairs exactly as they were received from the client ( 0.4.1).

For example, with the following request headers:

Host: localhost
Foo:  bar
foo:  bar2

the output of r.rawHeadersIn will be:

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

All foo headers can be collected with the syntax:

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

the output will be:

['bar', 'bar2']

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

r.rawHeadersOut{}
returns an array of key-value pairs of response headers ( 0.4.1). Header field names are not converted to lower case, duplicate field values are not merged.
r.requestBody
returns the client request body if it has not been written to a temporary file. To ensure that the client request body is in memory, its size should be limited by client_max_body_size, and a sufficient buffer size should be set using client_body_buffer_size. The property is available only in the js_content directive.
r.responseBody
holds the subrequest response body, read-only. The size of r.responseBody is limited by the subrequest_output_buffer_size directive.
r.return(status[, string])
sends the entire response with the specified status to the client

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

r.send(string)
sends a part of the response body to the client
r.sendHeader()
sends the HTTP headers to the client
r.status
status, writable
r.subrequest(uri[, options[, callback]])
creates a subrequest with the given uri and options, and installs an optional completion callback.

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

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

args
arguments string, by default an empty string is used
body
request body, by default the request body of the parent request object is used
method
HTTP method, by default the GET method is used
detached
boolean flag ( 0.3.9), if true, the created subrequest is a detached subrequest. Responses to detached subrequests are ignored. Unlike ordinary subrequests, a detached subrequest can be created inside a variable handler. The detached flag and callback argument are mutually exclusive.

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

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

r.uri
current URI in request, normalized, read-only
r.variables{}
nginx variables object, writable (since 0.2.8)
r.warn(string)
writes a string to the error log on the warning level of logging

Stream Session

The stream session object is available only in the ngx_stream_js_module module. All string properties of the object are byte strings.

s.allow()
successfully finalizes the phase handler ( 0.2.4)
s.decline()
finalizes the phase handler and passes control to the next handler ( 0.2.4)
s.deny()
finalizes the phase handler with the access error code ( 0.2.4)
s.done( [code])
successfully finalizes the current phase handler or finalizes it with the specified numeric code ( 0.2.4).
s.error(string)
writes a sent string to the error log on the error level of logging
s.log(string)
writes a sent string to the error log on the info level of logging
s.off(eventName)
unregisters the callback set by the s.on() method ( 0.2.4)
s.on(event, callback)
registers a callback for the specified event ( 0.2.4).

An event may be one of the following strings:

upload
new data from a client
download
new data to a client

The completion callback has the following prototype: callback(data, flags), where data is string, flags is an object with the following properties:

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

s.remoteAddress
client address, read-only
s.send(data[, options])
sends the data to the client ( 0.2.4). The options is an object used to override nginx buffer flags derived from an incoming data chunk buffer. The flags can be overriden with the following flags:

last
boolean, true if the buffer is the last buffer
flush
boolean, true if the buffer should have the flush flag

The method can be called multiple times per callback invocation.
s.variables{}
nginx variables object, writable (since 0.2.8)
s.warn(string)
writes a sent string to the error log on the warning level of logging

Core

Global

Process

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.
By default, nginx 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.pid
Returns the PID of the current process.
process.ppid
Returns the PID of the current parent process.

Object

The Object constructor corresponds to a standard JS object.

Object.entries(object)
returns an array of all enumerable property [key, value] pairs of the given object ( 0.2.7).
Object.values(object)
returns an array of all enumerable property values of the given object ( 0.2.7).

String

There are two types of strings in njs: a Unicode string (default) and a byte string.

A Unicode string corresponds to an ECMAScript string which contains Unicode characters.

Byte strings contain a sequence of bytes and are used to serialize Unicode strings to external data and deserialize from external sources. For example, the toUTF8() method serializes a Unicode string to a byte string using UTF8 encoding:

>> '£'.toUTF8().toString('hex')
'c2a3'  /* C2 A3 is the UTF8 representation of 00A3 ('£') code point */

The toBytes() method serializes a Unicode string with code points up to 255 into a byte string, otherwise, null is returned:

>> '£'.toBytes().toString('hex')
'a3'  /* a3 is a byte equal to 00A3 ('£') code point  */

Only byte strings can be converted to different encodings. For example, a string cannot be encoded to hex directly:

>> 'αβγδ'.toString('base64')
TypeError: argument must be a byte string
    at String.prototype.toString (native)
    at main (native)

To convert a Unicode string to hex, first, it should be converted to a byte string and then to hex:

>> 'αβγδ'.toUTF8().toString('base64')
'zrHOss6zzrQ='

String.bytesFrom(array | string, encoding)
(njs specific) Creates a byte string either from an array that contains octets, or from an encoded string ( 0.2.3). The encoding can be hex, base64, and base64url.
>> String.bytesFrom([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
'buffer'

>> String.bytesFrom('YnVmZmVy', 'base64')
'buffer'
String.fromCharCode(CharCode1[, ...[, CharCodeN]])
Returns a string from one or more Unicode code points.
>> String.fromCharCode(97, 98, 99, 100)
'abcd'
String.fromCodePoint(codePoint1[, ...[, codePoint2]])
Returns a string from one or more Unicode code points.
>> String.fromCodePoint(97, 98, 99, 100)
'abcd'
String.prototype.charAt(index)
Returns a string representing one Unicode code unit at the specified index; empty string if index is out of range. The index can be an integer between 0 and 1-less-than the length of the string. If no index is provided, the default is 0, so the first character in the string is returned.
String.prototype.CodePointAt(position)
Returns a number representing the code point value of the character at the given position; undefined if there is no element at position.
>> 'ABCD'.codePointAt(3);
68
String.prototype.concat(string1[, ..., stringN])
Returns a string that contains the concatenation of specified strings.
>> "a".concat("b", "c")
'abc'
String.prototype.endsWith(searchString[, length])
Returns true if a string ends with the characters of a specified string, otherwise false. The optional length parameter is the the length of string. If omitted, the default value is the length of the string.
>> 'abc'.endsWith('abc')
true
>> 'abca'.endsWith('abc')
false
String.prototype.fromBytes(start[, end])
(njs specific) Returns a new Unicode string from a byte string where each byte is replaced with a corresponding Unicode code point.
String.prototype.fromUTF8(start[, end])
(njs specific) Converts a byte string containing a valid UTF8 string into a Unicode string, otherwise null is returned.
String.prototype.includes(searchString[, position]))
Returns true if a string is found within another string, otherwise false. The optional position parameter is the position within the string at which to begin search for searchString. Default value is 0.
>> 'abc'.includes('bc')
true
String.prototype.indexOf(searchString[, fromIndex])
Returns the position of the first occurrence of the searchString. The search is started at fromIndex. Returns -1 if the value is not found. The fromIndex is an integer, default value is 0. If fromIndex is lower than 0 or greater than String.prototype.length , the search starts at index 0 and String.prototype.length.
>> 'abcdef'.indexOf('de', 2)
3
String.prototype.lastIndexOf(searchString[, fromIndex])
Returns the position of the last occurrence of the searchString, searching backwards from fromIndex. Returns -1 if the value is not found. If searchString is empty, then fromIndex is returned.
>> "nginx".lastIndexOf("gi")
1
String.prototype.length
Returns the length of the string.
>> 'αβγδ'.length
4
String.prototype.match([regexp])
Matches a string against a regexp.
>> 'nginx'.match( /ng/i )
'ng'
String.prototype.padEnd(length [, string])
Returns a string of a specified length with the pad string applied to the end of the specified string ( 0.2.3).
>> '1234'.padEnd(8, 'abcd')
'1234abcd'
String.prototype.padStart(length [, string])
Returns a string of a specified length with the pad string applied to the start of the specified string ( 0.2.3).
>> '1234'.padStart(8, 'abcd')
'abcd1234'
String.prototype.repeat(number)
Returns a string with the specified number of copies of the string.
>> 'abc'.repeat(3)
'abcabcabc'
String.prototype.replace([regexp|string[, string|function]])
Returns a new string with matches of a pattern ( string or a regexp) replaced by a string or a function.
>> 'abcdefgh'.replace('d', 1)
'abc1efgh'
Searches for a string using a regexp
>> 'abcdefgh'.search('def')
3
String.prototype.slice(start[, end])
Returns a new string containing a part of an original string between start and end or from start to the end of the string.
>> 'abcdefghijklmno'.slice(NaN, 5)
'abcde'
String.prototype.split(([string|regexp[, limit]]))
Returns match of a string against a regexp. The optional limit parameter is an integer that specifies a limit on the number of splits to be found.
>> 'abc'.split('')
[
 'a',
 'b',
 'c'
]
String.prototype.startsWith(searchString[, position])
Returns true if a string begins with the characters of a specified string, otherwise false. The optional position parameter is the position in this string at which to begin search for searchString. Default value is 0.
>> 'abc'.startsWith('abc')
true
> 'aabc'.startsWith('abc')
false
String.prototype.substr(start[, length])
Returns the part of the string of the specified length from start or from start to the end of the string.
>>  'abcdefghijklmno'.substr(3, 5)
'defgh'
String.prototype.substring(start[, end])
Returns the part of the string between start and end or from start to the end of the string.
>> 'abcdefghijklmno'.substring(3, 5)
'de'
String.prototype.toBytes(start[, end])
(njs specific) Serializes a Unicode string to a byte string. Returns null if a character larger than 255 is found in the string.
String.prototype.toLowerCase()
Converts a string to lower case. The method supports only simple Unicode folding.
>> 'ΑΒΓΔ'.toLowerCase()
'αβγδ'
String.prototype.toString([encoding])

If no encoding is specified, returns a specified Unicode string or byte string as in ECMAScript.

(njs specific) If encoding is specified, encodes a byte string to hex, base64, or base64url.

>>  'αβγδ'.toUTF8().toString('base64url')
'zrHOss6zzrQ'
String.prototype.toUpperCase()
Converts a string to upper case. The method supports only simple Unicode folding.
>> 'αβγδ'.toUpperCase()
'ΑΒΓΔ'
String.prototype.toUTF8(start[, end])
(njs specific) Serializes a Unicode string to a byte string using UTF8 encoding.
>> 'αβγδ'.toUTF8().length
8
>> 'αβγδ'.length
4
String.prototype.trim()
Removes whitespaces from both ends of a string.
>> '   abc  '.trim()
'abc'
String.prototype.trimEnd()
Removes whitespaces from the end of a string ( 0.3.4).
>> '   abc  '.trimEnd()
'   abc'
String.prototype.trimStart()
Removes whitespaces from the beginning of a string ( 0.3.4).
>> '   abc  '.trimStart()
'abc  '
encodeURI(URI)
Encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character
>> encodeURI('012αβγδ')
'012%CE%B1%CE%B2%CE%B3%CE%B4'
encodeURIComponent(encodedURIString)
Encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.
>> encodeURIComponent('[@?=')
'%5B%40%3F%3D'
decodeURI(encodedURI)
Decodes a previously encoded URI.
>> decodeURI('012%CE%B1%CE%B2%CE%B3%CE%B4')
'012αβγδ'
decodeURIComponent(decodedURIString)
Decodes an encoded component of a previously encoded URI.
>> decodeURIComponent('%5B%40%3F%3D')
'[@?='

TypedArray

TypedArray is a number of different global properties whose values are typed array constructors for specific element types.

TypedArray.prototype.sort()
sorts the elements of a typed array numerically and returns the updated typed array ( 0.4.2).

JSON

The JSON object (ES 5.1) provides functions to convert njs values to and from JSON format.

JSON.parse(string[, reviver])
Converts a string that represents JSON data into an njs object ( {...}) or array ( [...]). The optional reviver parameter is a function (key, value) that will be called for each (key,value) pair and can transform the value.
JSON.stringify(value[, replacer] [, space])
Converts an njs object back to JSON. The obligatory value parameter is generally a JSON object or array that will be converted. If the value has a toJSON() method, it defines how the object will be serialized. The optional replacer parameter is a function or array that transforms results. The optional space parameter is a string or number. If it is a number, it indicates the number of white spaces placed before a result (no more than 10). If it is a string, it is used as a white space (or first 10 characters of it). If omitted or is null, no white space is used.

>> var json = JSON.parse('{"a":1, "b":true}')
>> json.a
1

>> JSON.stringify(json)
'{"a":1,"b":true}'

>> JSON.stringify({ x: [10, undefined, function(){}] })
'{"x":[10,null,null]}'

>> JSON.stringify({"a":1, "toJSON": function() {return "xxx"}})
'"xxx"'

# Example with function replacer

>> function replacer(key, value) {return (typeof value === 'string') ? undefined : value}
>>JSON.stringify({a:1, b:"b", c:true}, replacer)
'{"a":1,"c":true}'

Crypto

The Crypto module provides cryptographic functionality support. The Crypto module object is returned by require('crypto').

crypto.createHash(algorithm)
Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. The algorithm can be md5, sha1, and sha256.
crypto.createHmac(algorithm, secret key)
Creates and returns an HMAC object that uses the given algorithm and secret key. The algorithm can be md5, sha1, and sha256.

Hash

hash.update(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 byte string is returned.

>> var cr = require('crypto')
undefined

>> cr.createHash('sha1').update('A').update('B').digest('base64url')
'BtlFlCqiamG-GMPiK_GbvKjdK10'

HMAC

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 byte string is returned.

>> var cr = require('crypto')
undefined

>> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url')
'Oglm93xn23_MkiaEq_e9u8zk374'

Timers

clearTimeout(timeout)
Cancels a timeout object created by setTimeout().
setTimeout(function, ms[, arg1, argN])
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.
function handler(v)
{
    // ...
}

t = setTimeout(handler, 12);

// ...

clearTimeout(t);

File System

The File System module provides operations with files.

The module object is returned by require('fs'). Since 0.3.9, promissified versions of file system methods are available through require('fs').promises object:

> var fs = require('fs').promises;
undefined
> fs.readFile("/file/path").then((data)=>console.log(data))
<file data>

accessSync(path[, mode])
Synchronously tests permissions for a file or directory specified in the path ( 0.3.9). If the check fails, an error will be returned, otherwise, the method will return undefined.
mode
by default is fs.constants.F_OK. The mode argument is an optional integer that specifies the accessibility checks to be performed.
try {
    fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK);
    console.log('has access');
} catch (e) {
    console.log('no access');)
}
appendFileSync(filename, data[, options])
Synchronously appends specified data to a file with provided filename. If the file does not exist, it will be created. The options parameter is expected to be an object with the following keys:
mode
mode option, by default is 0o666
flag
file system flag, by default is a
mkdirSync(path[, options])
Synchronously creates a directory at the specified path ( 0.4.2). The options parameter is expected to be an integer that specifies the mode, or an object with the following keys:
mode
mode option, by default is 0o777.
readdirSync(path[, options])
Synchronously reads the contents of a directory at the specified path ( 0.4.2). The options parameter is expected to be a string that specifies encoding or an object with the following keys:
encoding
encoding, by default is not specified. The encoding can be utf8.
withFileTypes
if set to true, the files array will contain fs.Dirent objects, by default is false.
readFileSync(filename[, options])
Synchronously returns the contents of the file with provided filename. The options parameter holds string that specifies encoding. If not specified, a byte string is returned. If utf8 encoding is specified, a Unicode string is returned. Otherwise, options is expected to be an object with the following keys:
encoding
encoding, by default is not specified. The encoding can be utf8
flag
file system flag, by default is r
>> var fs = require('fs')
undefined
>> var file = fs.readFileSync('/file/path.tar.gz')
undefined
>> var gzipped = /^\x1f\x8b/.test(file); gzipped
true
realpathSync(path[, options])
Synchronously computes the canonical pathname by resolving ., .. and symbolic links using realpath(3) . The options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback ( 0.3.9).
renameSync(oldPath, newPath)
Synchronously changes the name or location of a file from oldPath to newPath ( 0.3.4).
>> var fs = require('fs')
undefined
>> var file = fs.renameSync('hello.txt', 'HelloWorld.txt')
undefined
rmdirSync(path)
Synchronously removes a directory at the specified path ( 0.4.2).
symlinkSync(target, path)
Synchronously creates the link called path pointing to target using symlink(2) ( 0.3.9). Relative targets are relative to the link’s parent directory.
unlinkSync(path)
Synchronously unlinks a file by path ( 0.3.9).
writeFileSync(filename, data[, options])
Synchronously writes data to a file with provided filename. If the file does not exist, it will be created, if the file exists, it will be replaced. The options parameter is expected to be an object with the following keys:
mode
mode option, by default is 0o666
flag
file system flag, by default is w
>> var fs = require('fs')
undefined
>> var file = fs.writeFileSync('hello.txt', 'Hello world')
undefined

fs.Dirent

fs.Dirent is a representation of a directory entry — a file or a subdirectory. When readdirSync() is called with the withFileTypes option, the resulting array contains fs.Dirent objects.

  • dirent.isBlockDevice() — returns true if the fs.Dirent object describes a block device.
  • dirent.isCharacterDevice() — returns true if the fs.Dirent object describes a character device.
  • dirent.isDirectory() — returns true if the fs.Dirent object describes a file system directory.
  • dirent.isFIFO() — returns true if the fs.Dirent object describes a first-in-first-out (FIFO) pipe.
  • dirent.isFile() — returns true if the fs.Dirent object describes a regular file.
  • dirent.isSocket() — returns true if the fs.Dirent object describes a socket.
  • dirent.isSymbolicLink() — returns true if the fs.Dirent object describes a symbolic link.
  • dirent.name — the name of the file fs.Dirent object refers to.

File Access Constants

The access() method can accept the following flags. These flags are exported by fs.constants:

  • F_OK — indicates that the file is visible to the calling process, used by default if no mode is specified
  • R_OK — indicates that the file can be read by the calling process
  • W_OK — indicates that the file can be written by the calling process
  • X_OK — indicates that the file can be executed by the calling process

File System Flags

The flag option can accept the following values:

  • a — open a file for appending. The file is created if it does not exist
  • ax — the same as a but fails if the file already exists
  • a+ — open a file for reading and appending. If the file does not exist, it will be created
  • ax+ — the same as a+ but fails if the file already exists
  • as — open a file for appending in synchronous mode. If the file does not exist, it will be created
  • as+ — open a file for reading and appending in synchronous mode. If the file does not exist, it will be created
  • r — open a file for reading. An exception occurs if the file does not exist
  • r+ — open a file for reading and writing. An exception occurs if the file does not exist
  • rs+ — open a file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache
  • w — open a file for writing. If the file does not exist, it will be created. If the file exists, it will be replaced
  • wx — the same as w but fails if the file already exists
  • w+ — open a file for reading and writing. If the file does not exist, it will be created. If the file exists, it will be replaced
  • wx+ — the same as w+ but fails if the file already exists