njs provides objects, methods and properties for extending nginx functionality.
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{} For example, the Foo header can be accessed with the syntax headersIn.foo or headersIn['Foo']
r.headersOut{} For example, the Foo header can be accessed with the syntax headersOut.foo or headersOut['Foo']
r.httpVersionr.log(string)string to the error log on the info level of logging r.internalRedirect(uri)uri. If the uri starts with the “@” prefix, it is considered a named location. r.methodr.parentr.remoteAddressr.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.variables{}r.warn(string)string to the error log on the warning level of logging r.urir.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 The completion callback receives a subrequest response object with methods and properties identical to the parent request object.
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 overriden 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.ppid The Object constructor corresponds to a standard JS object.
Object.entries(object)[key, value] pairs of the given object (0.2.7). Object.values(object)object (0.2.7). 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)hex, base64, and base64url.
>> String.bytesFrom([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
'buffer'
>> String.bytesFrom('YnVmZmVy', 'base64')
'buffer'
String.fromCharCode(CharCode1[, ...[,
CharCodeN]])>> String.fromCharCode(97, 98, 99, 100) 'abcd'
String.fromCodePoint(codePoint1[, ...[,
codePoint2]])>> String.fromCodePoint(97, 98, 99, 100) 'abcd'
String.prototype.charAt(index)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)position; undefined if there is no element at position. >> 'ABCD'.codePointAt(3); 68
String.prototype.concat(string1[, ...,
stringN])strings.
>> "a".concat("b", "c")
'abc'
String.prototype.endsWith(searchString[,
length])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])String.prototype.fromUTF8(start[,
end])null is returned. String.prototype.includes(searchString[,
position]))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])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])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>> 'αβγδ'.length 4
String.prototype.match([regexp])regexp. >> 'nginx'.match( /ng/i ) 'ng'
String.prototype.padEnd(length
[, string])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])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)number of copies of the string. >> 'abc'.repeat(3) 'abcabcabc'
String.prototype.replace([regexp|string[,
string|function]])string or a regexp) replaced by a string or a function.
>> 'abcdefgh'.replace('d', 1)
'abc1efgh'
String.prototype.search([regexp])regexp
>> 'abcdefgh'.search('def')
3
String.prototype.slice(start[,
end])start and end or from start to the end of the string. >> 'abcdefghijklmno'.slice(NaN, 5) 'abcde'
String.prototype.split(([string|regexp[,
limit]]))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])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])length from start or from start to the end of the string. >> 'abcdefghijklmno'.substr(3, 5) 'defgh'
String.prototype.substring(start[,
end])start and end or from start to the end of the string. >> 'abcdefghijklmno'.substring(3, 5) 'de'
String.prototype.toBytes(start[,
end])null if a character larger than 255 is found in the string. String.prototype.toLowerCase()>> 'ΑΒΓΔ'.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()>> 'αβγδ'.toUpperCase() 'ΑΒΓΔ'
String.prototype.toUTF8(start[,
end])>> 'αβγδ'.toUTF8().length 8 >> 'αβγδ'.length 4
String.prototype.trim()>> ' abc '.trim() 'abc'
encodeURI(URI)
>> encodeURI('012αβγδ')
'012%CE%B1%CE%B2%CE%B3%CE%B4'
encodeURIComponent(encodedURIString)
>> encodeURIComponent('[@?=')
'%5B%40%3F%3D'
decodeURI(encodedURI)
>> decodeURI('012%CE%B1%CE%B2%CE%B3%CE%B4')
'012αβγδ'
decodeURIComponent(decodedURIString)
>> decodeURIComponent('%5B%40%3F%3D')
'[@?='
The JSON object (ES 5.1) provides functions to convert njs values to and from JSON format.
JSON.parse(string[,
reviver])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])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}'
The Crypto module provides cryptographic functionality support. The Crypto module object is returned by require('crypto').
crypto.createHash(algorithm)algorithm. The algorighm can be md5, sha1, and sha256. crypto.createHmac(algorithm,
secret key)algorithm and secret key. The algorighm 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 byte string is returned.
>> 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 byte string is returned.
>> var cr = require('crypto')
undefined
>> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url')
'Oglm93xn23_MkiaEq_e9u8zk374'
clearTimeout(timeout)timeout object created by setTimeout(). setTimeout(function,
ms[, arg1, argN])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);
The File System module provides operations with files. The module object is returned by require('fs').
appendFileSync(filename,
data[, options])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: mode0o666 flaga readFileSync(filename[,
options])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: encodingutf8 flagr
>> var fs = require('fs')
undefined
>> var file = fs.readFileSync('/file/path.tar.gz')
undefined
>> var gzipped = /^\x1f\x8b/.test(file); gzipped
true
writeFileSync(filename,
data[,
options])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: mode0o666 flagw
>> var fs = require('fs')
undefined
>> var file = fs.writeFileSync('hello.txt', 'Hello world')
undefined
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
© 2002-2019 Igor Sysoev
© 2011-2019 Nginx, Inc.
Licensed under the BSD License.
https://nginx.org/en/docs/njs/reference.html