njs provides objects, methods and properties for extending nginx 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. List of all njs properties and methods can be found in Compatibility.
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{}r.error(string)string to the error log on the error level of logging r.finish()r.headersIn{} 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{} 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.httpVersionr.internalRedirect(uri)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)string to the error log on the info level of logging r.methodr.parentr.remoteAddressr.rawHeadersIn{}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{}r.requestBodyr.responseBodyr.responseBody is limited by the subrequest_output_buffer_size directive. r.return(status[, string])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)r.sendHeader()r.statusr.subrequest(uri[,
options[, callback]])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:
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. 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.urir.variables{}r.warn(string)string to the error log on the warning level of logging 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()s.decline()s.deny()s.done([code])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(event,
callback)callback for the specified event (0.2.4). An event may be one of the following strings:
uploaddownload The completion callback has the following prototype: callback(data, flags), where data is string, flags is an object with the following properties:
lasts.remoteAddresss.send(data[,
options])options is an object used to override nginx buffer flags derived from an incoming data chunk buffer. The flags can be overridden with the following flags: lastflushflush flag s.variables{}s.warn(string)string to the error log on the warning level of logging The process object is a global object that provides information about the current process (0.3.3).
process.argvprocess.envBy 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.pidprocess.ppidThere 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 */
String.bytesFrom(array
| string, encoding)hex, base64, and base64url. The method is deprecated since 0.4.4, the Buffer.from method should be used instead:
>> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString()
'buffer'
>> Buffer.from('YnVmZmVy', 'base64').toString()
'buffer'
String.prototype.fromBytes(start[,
end])String.prototype.fromUTF8(start[,
end])null is returned. String.prototype.toBytes(start[,
end])null if a character larger than 255 is found in the string. String.prototype.toString(encoding) Encodes a string to hex, base64, or base64url:
>> 'αβγδ'.toString('base64url')
'zrHOss6zzrQ'
Before version 0.4.3, only a byte string could be encoded:
>> 'αβγδ'.toUTF8().toString('base64url')
'zrHOss6zzrQ'
String.prototype.toUTF8(start[,
end])>> 'αβγδ'.toUTF8().length 8 >> 'αβγδ'.length 4
The 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])) αβ
The 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.encodingutf-8”, read-only. 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 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);
Buffer.alloc(size[,
fill[,
encoding]])) Allocates a new Buffer of a specified size. If fill is not specified, the Buffer will be zero-filled. If fill is specified, the allocated Buffer will be initialized by calling buf.fill(fill). If fill and encoding are specified, the allocated Buffer will be initialized by calling buf.fill(fill,
encoding).
The fill parameter may be a string, Buffer, Uint8Array, or integer.
Buffer.allocUnsafe(size) The same as Buffer.alloc(), with the difference that the memory allocated for the buffer is not initialized, the contents of the new buffer is unknown and may contain sensitive data.
Buffer.byteLength(value[,
encoding])encoding. The value can be a string, Buffer, TypedArray, DataView, or ArrayBuffer. If the value is a string, the encoding parameter is its encoding, can be utf-8, hex, base64, base64url; by default is utf-8. Buffer.compare(buffer1,
buffer2)buffer1 with buffer2 when sorting arrays of Buffer instances. Returns 0 if buffer1 is the same as buffer2, 1 if buffer2 should come before buffer1 when sorted, or -1 if buffer2 should come after buffer1 when sorted. Buffer.concat(list[,
totalLength])totalLength is not specified, it is calculated from the Buffer instances in list by adding their lengths. If totalLength is specified, it is coerced to an unsigned integer. If the combined length of the Buffers in list exceeds totalLength, the result is truncated to totalLength. Buffer.from(array)0 – 255. Array entries outside that range will be truncated. Buffer.from(arrayBuffer,
byteOffset[,
length]])ArrayBuffer without copying the underlying memory. The optional byteOffset and length arguments specify a memory range within the arrayBuffer that will be shared by the Buffer. Buffer.from(buffer)Buffer.from(object[,
offsetOrEncoding[,
length]])valueOf() function returns a value not strictly equal to object, returns Buffer.from(object.valueOf(), offsetOrEncoding, length). Buffer.from(string[,
encoding])string. The encoding parameter identifies the character encoding to be used when converting a string into bytes. The encoding can be utf-8, hex, base64, base64url; by default is utf-8. Buffer.isBuffer(object)true if object is a Buffer. Buffer.isEncoding(encoding)true if encoding is the name of a supported character encoding. buffer[index]index can be used to get and set the octet at position index in buffer. The values refer to individual bytes, so the legal value range is between 0 and 255 (decimal). buf.bufferArrayBuffer object based on which this Buffer object is created. buf.byteOffsetbyteOffset of the Buffers underlying ArrayBuffer object. buf.compare(target[,
targetStart[,
targetEnd[,
sourceStart[,
sourceEnd]]]])targetStart is an integer specifying the offset within target at which to begin comparison, by default is 0. The targetEnd is an integer specifying the offset within target at which to end comparison, by default is target.length. The sourceStart is an integer specifying the offset within buffer at which to begin comparison, by default is 0. The sourceEnd is an integer specifying the offset within buffer at which to end comparison (not inclusive), by default is buf.length. buf.copy(target[,
targetStart[,
sourceStart[,
sourceEnd]]])target parameter is a Buffer or Uint8Array to copy into. The targetStart is an integer specifying the offset within target at which to begin writing, by default is 0. The sourceStart is an integer specifying the offset within buffer from which to begin copying, by default is 0. The sourceEnd is an integer specifying the offset within buffer at which to stop copying (not inclusive) by default is buf.length.
buf.equals(otherBuffer)true if both Buffer and otherBuffer have exactly the same bytes. buf.fill(value[,
offset[,
end]][,
encoding])value. If the offset and end are not specified, the entire Buffer will be filled. The value is coerced to uint32 if it is not a string, Buffer, or integer. If the resulting integer is greater than 255, the Buffer will be filled with value and 255. buf.includes(value[,
byteOffset][,
encoding])buf.indexOf() !== -1, returns true if the value was found in Buffer. buf.indexOf(value[,
byteOffset][,
encoding])value in Buffer, or -1 if Buffer does not contain value. The value can be a string with specified encoding (by default utf-8), Buffer, Unit8Array, or a number between 0 and 255. buf.lastIndexOf(value[,
byteOffset][,
encoding])buf.indexOf(), except the last occurrence of the value is found instead of the first occurrence. The value can be a string, Buffer, or integer between 1 and 255. If the value is an empty string or empty Buffer, byteOffset will be returned. buf.lengthbuf.readIntBE(offset,
byteLength)byteLength from buf at the specified offset and interprets the result as a big-endian, two's complement signed value supporting up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The similar methods are also supported: buf.readInt8([offset]), buf.readInt16BE([offset]), buf.readInt32BE([offset]).
buf.readIntLE(offset,
byteLength)byteLength from buf at the specified offset and interprets the result as a little-endian, two's complement signed value supporting up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The similar methods are also supported: buf.readInt8([offset]), buf.readInt16LE([offset]), buf.readInt32LE([offset]).
buf.readUIntBE(offset,
byteLength)byteLength from buf at the specified offset and interprets the result as a big-endian integer supporting up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The similar methods are also supported: buf.readUInt8([offset]), buf.readUInt16BE([offset]), buf.readUInt32BE([offset]).
buf.readUIntLE(offset,
byteLength)byteLength from buf at the specified offset and interprets the result as a little-endian integer supporting up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The similar methods are also supported: buf.readUInt8([offset]), buf.readUInt16LE([offset]), buf.readUInt32LE([offset]).
buf.readDoubleBE([offset])buf at the specified offset. buf.readDoubleLE([offset])buf at the specified offset. buf.readFloatBE([offset])buf at the specified offset. buf.readFloatLE([offset])buf at the specified offset. buf.subarray[start[,
end]])buf that references the same memory as the original, but offset and cropped by start and end. If end is greater than buf.length, the same result as that of end equal to buf.length is returned. buf.slice[start[,
end]])buf that references the same memory as the original, but offset and cropped by the start and end values. The method is not compatible with the Uint8Array.prototype.slice(), which is a superclass of Buffer. To copy the slice, use Uint8Array.prototype.slice(). buf.swap16()buf as an array of unsigned 16-bit numbers and swaps the byte order in-place. Throws an error if buf.length is not a multiple of 2. buf.swap32()buf as an array of unsigned 32-bit numbers and swaps the byte order in-place. Throws an error if buf.length is not a multiple of 4. buf.swap64()buf as an array of 64-bit numbers and swaps byte order in-place. Throws an error if buf.length is not a multiple of 8. buf.toJSON()buf. JSON.stringify() implicitly calls this function when stringifying a Buffer instance. buf.toString([encoding[,
start[,
end]]])buf to a string according to the specified character encoding. which can be utf-8, hex, base64, base64url. The start and end parameters may be passed to decode only a subset of Buffer. buf.write(string[,
offset[,
length]][,
encoding])string to buf at offset according to the character encoding. The length parameter is the number of bytes to write. If Buffer did not contain enough space to fit the entire string, only part of string will be written, however, partially encoded characters will not be written. The encoding can be utf-8, hex, base64, base64url. buf.writeIntBE(value,
offset,
byteLength)byteLength bytes of value to buf at the specified offset as big-endian. Supports up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The following similar methods are also supported: buf.writeInt8, buf.writeInt16BE, buf.writeInt32BE.
buf.writeIntLE(value,
offset,
byteLength)byteLength bytes of value to buf at the specified offset as little-endian. Supports up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The following similar methods are also supported: buf.writeInt8, buf.writeInt16LE, buf.writeInt32LE.
buf.writeUIntBE(value,
offset,
byteLength)byteLength bytes of value to buf at the specified offset as big-endian. Supports up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The following similar methods are also supported: buf.writeUInt8, buf.writeUInt16BE, buf.writeUInt32BE.
buf.writeUIntLE(value,
offset,
byteLength)byteLength bytes of value to buf at the specified offset as little-endian. Supports up to 48 bits of accuracy. The byteLength parameter is an integer between 1 and 6 specifying the number of bytes to read. The following similar methods are also supported: buf.writeUInt8, buf.writeUInt16LE, buf.writeUInt32LE.
buf.writeDoubleBE(value,
[offset])value to buf at the specified offset as big-endian. buf.writeDoubleLE(value,
[offset])value to buf at the specified offset as little-endian. buf.writeFloatBE(value,
[offset])value to buf at the specified offset as big-endian. buf.writeFloatLE(value,
[offset])value to buf at the specified offset as little-endian. The Crypto module provides cryptographic functionality support. The Crypto module object is returned by require('crypto').
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.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. Before version (0.4.4), a byte string was returned instead of a Buffer object.
>> var cr = require('crypto')
undefined
>> cr.createHash('sha1').update('A').update('B').digest('base64url')
'BtlFlCqiamG-GMPiK_GbvKjdK10'
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. Before version 0.4.4, a byte string was returned instead of a Buffer object.
>> var cr = require('crypto')
undefined
>> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url')
'Oglm93xn23_MkiaEq_e9u8zk374'
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])path (0.3.9). If the check fails, an error will be returned, otherwise, the method will return undefined. modefs.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])data to a file with provided filename. The data is expected to be a string or a Buffer object (0.4.4). If the file does not exist, it will be created. The options parameter is expected to be an object with the following keys: mode0o666 flaga mkdirSync(path[,
options])path (0.4.2). The options parameter is expected to be an integer that specifies the mode, or an object with the following keys: mode0o777. readdirSync(path[,
options])path (0.4.2). The options parameter is expected to be a string that specifies encoding or an object with the following keys: readFileSync(filename[,
options])filename. The options parameter holds string that specifies encoding. If an encoding is specified, a string is returned, otherwise, a Buffer object (0.4.4) is returned. Before version 0.4.4, a byte string was returned if encoding was not specified.Otherwise,
options is expected to be an object with the following keys: encodingutf8, hex (0.4.4), base64 (0.4.4), base64url (0.4.4). flagr
>> var fs = require('fs')
undefined
>> var file = fs.readFileSync('/file/path.tar.gz')
undefined
>> var gzipped = file.slice(0,2).toString('hex') === '1f8b'; gzipped
true
realpathSync(path[,
options])., .. 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)oldPath to newPath (0.3.4).
>> var fs = require('fs')
undefined
>> var file = fs.renameSync('hello.txt', 'HelloWorld.txt')
undefined
rmdirSync(path)path (0.4.2). symlinkSync(target,
path)path pointing to target using symlink(2) (0.3.9). Relative targets are relative to the link’s parent directory. unlinkSync(path)path (0.3.9). writeFileSync(filename,
data[,
options])data to a file with provided filename. The data is expected to be a string or a Buffer object (0.4.4). 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: mode0o666 flagw
>> var fs = require('fs')
undefined
>> var file = fs.writeFileSync('hello.txt', 'Hello world')
undefined
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. 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 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 The Query String module provides support for parsing and formatting URL query strings (0.4.3). The Query String module object is returned by require('querystring').
querystring.decode()querystring.parse(). querystring.encode()querystring.stringify(). querystring.escape(string) Performs URL encoding of the given string, returns an escaped query string. The method is used by querystring.stringify() and should not be used directly.
querystring.parse(string[,
separator[,
equal[,
options]]])Parses the query string URL and returns an object.
The separator parameter is a substring for delimiting key and value pairs in the query string, by default is “&”.
The equal parameter is a substring for delimiting keys and values in the query string, by default is “=”.
The options parameter is expected to be an object with the following keys:
decodeURIComponent function
querystring.unescape() maxKeys number
1000. The 0 value removes limitations for counting keys. By default, percent-encoded characters within the query string are assumed to use the UTF-8 encoding, invalid UTF-8 sequences will be replaced with the U+FFFD replacement character.
For example, for the following query string
'foo=bar&abc=xyz&abc=123'
the output will be:
{
foo: 'bar',
abc: ['xyz', '123']
}
querystring.stringify(object[,
separator[,
equal[,
options]]])Serializes an object and returns a URL query string.
The separator parameter is a substring for delimiting key and value pairs in the query string, by default is “&”.
The equal parameter is a substring for delimiting keys and values in the query string, by default is “=”.
The options parameter is expected to be an object with the following keys:
encodeURIComponent function
querystring.escape(). By default, characters that require percent-encoding within the query string are encoded as UTF-8. If other encoding is required, then encodeURIComponent option should be specified.
For example, for the following command
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], 123: '' });
the query string will be:
'foo=bar&baz=qux&baz=quux&123='
querystring.unescape(string) Performs decoding of URL percent-encoded characters of the string, returns an unescaped query string. The method is used by querystring.parse() and should not be used directly.
© 2002-2020 Igor Sysoev
© 2011-2020 Nginx, Inc.
Licensed under the BSD License.
https://nginx.org/en/docs/njs/reference.html