Reference

njs提供用于扩展 nginx 功能的对象,方法和属性。

nginx objects

HTTP Request

HTTP 请求对象仅在ngx_http_js_module模块中可用。对象的所有字符串属性均为byte strings

r.args{}

r.headersIn{}

可以使用以下语法访问Foo请求 Headers:headersIn.fooheadersIn['Foo']

“授权”,“内容长度”,“内容范围”,“Content Type”,“ ETag”,“期望”,“来自”,“主机”,“ If-Match”,“ If-Modified-从”,“如果没有匹配”,“如果范围”,“如果未经修改以来”,“最大转发”,“代理授权”,“推荐人”,“传输编码”和“用户” -Agent”请求 Headers 只能有一个字段值(0.4.1)。 “ Cookie”标题中重复的字段值用分号(;)分隔。所有其他请求 Headers 中的重复字段值均以逗号分隔。

r.headersOut{}

可以使用以下语法访问“ Foo”响应头:headersOut.fooheadersOut['Foo']

可以使用以下语法设置多值响应 Headers(0.4.0)的字段值:

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

输出将是:

Foo: a
Foo: b

“ Foo”响应标题的所有先前字段值将被删除。

对于仅接受单个字段值(例如“ Content-Type”)的标准响应 Headers,只有数组的最后一个元素才会生效。 “ Set-Cookie”响应 Headers 的字段值始终以数组形式返回。 “ Age”,“ Content-Encoding”,“ Content-Length”,“ Content-Type”,“ ETag”,“ Expires”,“ Last-Modified”,“ Location”,“ Retry-After”响应中的字段值重复 Headers 将被忽略。所有其他响应 Headers 中的重复字段值均以逗号分隔。

r.internalRedirect(uri)

r.parent

r.rawHeadersIn{}

例如,具有以下请求 Headers:

Host: localhost
Foo:  bar
foo:  bar2

r.rawHeadersIn的输出为:

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

可以使用以下语法收集所有fooHeaders:

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

输出将是:

['bar', 'bar2']

标题字段名称不会转换为小写,重复的字段值不会合并。

r.rawHeadersOut{}

r.requestBody

r.responseBody

可以指定重定向 URL(对于代码 301、302、303、307 和 308)或响应正文(对于其他代码)作为第二个参数

r.subrequest(uri[, options[, callback]])

subrequest与客户端请求共享其输入 Headers。要将不同于原始头的头发送到代理服务器,可以使用proxy_set_header指令。要将全新的 Headers 集发送到代理服务器,可以使用proxy_pass_request_headers指令。

如果options是字符串,则它包含子请求参数字符串。否则,options应该是具有以下键的对象:

完成callback接收一个子请求响应对象,该对象的方法和属性与父请求对象相同。

由于0.3.8,如果未提供callback,则返回解析为子请求响应对象的Promise对象。

r.uri

r.variables{}

Stream Session

流会话对象仅在ngx_stream_js_module模块中可用。对象的所有字符串属性均为byte strings

s.allow()

s.decline()

s.deny()

s.done( [code])

s.off(eventName)

s.on(event, callback)

event可能是以下字符串之一:

完成回调具有以下原型:callback(data, flags),其中data是字符串,flags是具有以下属性的对象:

last

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

s.send(data[, options])

每次回调调用可以多次调用该方法。

s.variables{}

Core

Global

Process

process对象是一个全局对象,提供有关当前进程(0.3.3)的信息。

process.argv

process.env

Note

默认情况下,nginx 会删除从其父进程继承的所有环境变量(TZ 变量除外)。使用env指令保留一些继承的变量。

process.pid

process.ppid

Object

Object构造函数对应于标准 JS 对象。

Object.entries(object)

Object.values(object)

String

njs 中有两种类型的字符串:Unicode 字符串(默认)和字节字符串。

Unicode 字符串对应于包含 Unicode 字符的 ECMAScript 字符串。

字节字符串包含一个字节序列,用于将 Unicode 字符串序列化为外部数据并从外部源反序列化。例如,toUTF8()方法使用 UTF8 编码将 Unicode 字符串序列化为字节字符串:

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

toBytes()方法将代码点最多为 255 的 Unicode 字符串序列化为字节字符串,否则返回null

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

只能将字节字符串转换为不同的编码。例如,字符串不能直接编码为hex

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

要将 Unicode 字符串转换为十六进制,首先,应将其转换为字节字符串,然后再转换为十六进制:

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

String.bytesFrom(数组|字符串,编码)

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

String.prototype.CodePointAt(position)

>> 'ABCD'.codePointAt(3);
68

String.prototype.concat(string1[,...,字符串 N])

>> "a".concat("b", "c")
'abc'

String.prototype.endsWith(searchString[, length])

>> 'abc'.endsWith('abc')
true
>> 'abca'.endsWith('abc')
false

String.prototype.fromBytes(start[, end])

String.prototype.fromUTF8(start[, end])

String.prototype.includes(searchString[, position]))

>> 'abc'.includes('bc')
true

String.prototype.indexOf(searchString[, fromIndex])

>> 'abcdef'.indexOf('de', 2)
3

String.prototype.lastIndexOf(searchString[, fromIndex])

>> "nginx".lastIndexOf("gi")
1

String.prototype.length

>> 'αβγδ'.length
4

String.prototype.match([regexp])

>> 'nginx'.match( /ng/i )
'ng'

String.prototype.padEnd(length [, string])

>> '1234'.padEnd(8, 'abcd')
'1234abcd'

String.prototype.padStart(length [, string])

>> '1234'.padStart(8, 'abcd')
'abcd1234'

String.prototype.repeat(number)

>> 'abc'.repeat(3)
'abcabcabc'

String.prototype.replace([regexp|string[, string|function]])

>> 'abcdefgh'.replace('d', 1)
'abc1efgh'

String.prototype.search([regexp])

>> 'abcdefgh'.search('def')
3

String.prototype.slice(start[, end])

>> 'abcdefghijklmno'.slice(NaN, 5)
'abcde'

String.prototype.split(([string|regexp[, limit]]))

>> 'abc'.split('')
[
 'a',
 'b',
 'c'
]

String.prototype.startsWith(searchString[, position])

>> 'abc'.startsWith('abc')
true
> 'aabc'.startsWith('abc')
false

String.prototype.substr(start[, length])

>>  'abcdefghijklmno'.substr(3, 5)
'defgh'

String.prototype.substring(start[, end])

>> 'abcdefghijklmno'.substring(3, 5)
'de'

String.prototype.toBytes(start[, end])

String.prototype.toLowerCase()

>> 'ΑΒΓΔ'.toLowerCase()
'αβγδ'

(特定于 njs)如果指定encoding,则将byte string编码为hexbase64base64url

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

String.prototype.toUpperCase()

>> 'αβγδ'.toUpperCase()
'ΑΒΓΔ'

String.prototype.toUTF8(start[, end])

>> 'αβγδ'.toUTF8().length
8
>> 'αβγδ'.length
4

String.prototype.trim()

>> '   abc  '.trim()
'abc'

String.prototype.trimEnd()

>> '   abc  '.trimEnd()
'   abc'

String.prototype.trimStart()

>> '   abc  '.trimStart()
'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')
'[@?='

TypedArray

TypedArray是许多不同的全局属性,其值是特定元素类型的类型化数组构造函数。

TypedArray.prototype.sort()

JSON

JSON对象(ES 5.1)提供了用于将 njs 值与 JSON 格式相互转换的功能。

JSON.parse(string[, reviver])

JSON.stringify(value[, replacer] [, space])

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

加密模块提供加密功能支持。加密模块对象由require('crypto')返回。

crypto.createHash(algorithm)

crypto.createHmac(算法,密钥)

Hash

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

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

HMAC

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

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

Timers

clearTimeout(timeout)

setTimeout(function, ms[,arg1,argN])

function handler(v)
{
    // ...
}

t = setTimeout(handler, 12);

// ...

clearTimeout(t);

File System

文件系统模块提供文件操作。

模块对象由require('fs')返回。由于0.3.9,因此可以通过require('fs').promises对象获得文件系统方法的授权版本:

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

accessSync(path[, mode])

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])

mkdirSync(path[, options])

mode

 - mode option, by default is  `0o777` \.

readdirSync(path[, options])

encoding

 - encoding, by default is not specified\. The encoding can be  `utf8` \.

withFileTypes

 - if set to  `true` , the files array will contain [fs\.Dirent](njs-reference.html#fs_dirent) objects, by default is  `false` \.

readFileSync(filename[, options])

>> 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])

renameSync(oldPath, newPath)

>> var fs = require('fs')
undefined
>> var file = fs.renameSync('hello.txt', 'HelloWorld.txt')
undefined

rmdirSync(path)

symlinkSync(target, path)

unlinkSync(path)

writeFileSync(filename, data[, options])

>> var fs = require('fs')
undefined
>> var file = fs.writeFileSync('hello.txt', 'Hello world')
undefined

fs.Dirent

fs.Dirent是目录条目(文件或子目录)的表示。当使用withFileTypes选项调用readdirSync()时,结果数组包含fs.Dirent个对象。

文件访问常量

access()方法可以接受以下标志。这些标志由fs.constants导出:

文件系统标志

flag选项可以接受以下值:

首页