# HG changeset patch # User Maxim Dounin # Date 1707930360 -10800 # Node ID 1bb11d9ca0ba95c2d21125d3b2b43ac528f5c209 # Parent 185dd0a00e10edfc19c56c7ec174f89e01c7a68c Free nginx: removed njs which is maintained separately. diff --git a/GNUmakefile b/GNUmakefile --- a/GNUmakefile +++ b/GNUmakefile @@ -271,7 +271,7 @@ rsync_gzip: do_gzip: $(addsuffix .gz, $(wildcard $(ZIP)/*.html)) \ $(addsuffix .gz, \ $(foreach lang, $(LANGS), \ - $(foreach dir, . docs docs/dev docs/faq docs/http docs/mail docs/njs docs/stream, \ + $(foreach dir, . docs docs/dev docs/faq docs/http docs/mail docs/stream, \ $(wildcard $(ZIP)/$(lang)/$(dir)/*.html)))) \ $(ZIP)/index.rss.gz \ $(ZIP)/LICENSE.gz \ diff --git a/xml/en/GNUmakefile b/xml/en/GNUmakefile --- a/xml/en/GNUmakefile +++ b/xml/en/GNUmakefile @@ -58,7 +58,6 @@ REFS = \ http/ngx_http_headers_module \ http/ngx_http_image_filter_module \ http/ngx_http_index_module \ - http/ngx_http_js_module \ http/ngx_http_limit_conn_module \ http/ngx_http_limit_req_module \ http/ngx_http_log_module \ @@ -99,7 +98,6 @@ REFS = \ stream/ngx_stream_core_module \ stream/ngx_stream_geo_module \ stream/ngx_stream_geoip_module \ - stream/ngx_stream_js_module \ stream/ngx_stream_limit_conn_module \ stream/ngx_stream_log_module \ stream/ngx_stream_map_module \ @@ -114,16 +112,6 @@ REFS = \ stream/stream_processing \ ngx_google_perftools_module \ dev/development_guide \ - njs/index \ - njs/changes \ - njs/cli \ - njs/compatibility \ - njs/install \ - njs/preload_objects \ - njs/reference \ - njs/security \ - njs/node_modules \ - njs/typescript \ TOP = \ download \ diff --git a/xml/en/docs/dev/development_guide.xml b/xml/en/docs/dev/development_guide.xml --- a/xml/en/docs/dev/development_guide.xml +++ b/xml/en/docs/dev/development_guide.xml @@ -7519,8 +7519,7 @@ Is it possible to implement a desired fe Is it possible to solve an issue using built-in scripting languages, -such as Perl -or njs? +such as Perl? diff --git a/xml/en/docs/http/ngx_http_js_module.xml b/xml/en/docs/http/ngx_http_js_module.xml deleted file mode 100644 --- a/xml/en/docs/http/ngx_http_js_module.xml +++ /dev/null @@ -1,812 +0,0 @@ - - - - - - - - -
- - -The ngx_http_js_module module is used to implement -location and variable handlers -in njs — -a subset of the JavaScript language. - - - -Download and install instructions are available -here. - - -
- - -
- - -The example works since -0.4.0. - -http { - js_import http.js; - - js_set $foo http.foo; - js_set $summary http.summary; - js_set $hash http.hash; - - resolver 10.0.0.1; - - server { - listen 8000; - - location / { - add_header X-Foo $foo; - js_content http.baz; - } - - location = /summary { - return 200 $summary; - } - - location = /hello { - js_content http.hello; - } - - # since 0.7.0 - location = /fetch { - js_content http.fetch; - js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; - } - - # since 0.7.0 - location = /crypto { - add_header Hash $hash; - return 200; - } - } -} - - - - -The http.js file: - -function foo(r) { - r.log("hello from foo() handler"); - return "foo"; -} - -function summary(r) { - var a, s, h; - - s = "JS summary\n\n"; - - s += "Method: " + r.method + "\n"; - s += "HTTP version: " + r.httpVersion + "\n"; - s += "Host: " + r.headersIn.host + "\n"; - s += "Remote Address: " + r.remoteAddress + "\n"; - s += "URI: " + r.uri + "\n"; - - s += "Headers:\n"; - for (h in r.headersIn) { - s += " header '" + h + "' is '" + r.headersIn[h] + "'\n"; - } - - s += "Args:\n"; - for (a in r.args) { - s += " arg '" + a + "' is '" + r.args[a] + "'\n"; - } - - return s; -} - -function baz(r) { - r.status = 200; - r.headersOut.foo = 1234; - r.headersOut['Content-Type'] = "text/plain; charset=utf-8"; - r.headersOut['Content-Length'] = 15; - r.sendHeader(); - r.send("nginx"); - r.send("java"); - r.send("script"); - - r.finish(); -} - -function hello(r) { - r.return(200, "Hello world!"); -} - -// since 0.7.0 -async function fetch(r) { - let results = await Promise.all([ngx.fetch('https://nginx.org/'), - ngx.fetch('https://nginx.org/en/')]); - - r.return(200, JSON.stringify(results, undefined, 4)); -} - -// since 0.7.0 -async function hash(r) { - let hash = await crypto.subtle.digest('SHA-512', r.headersIn.host); - r.setReturnValue(Buffer.from(hash).toString('hex')); -} - -export default {foo, summary, baz, hello, fetch, hash}; - - - -
- - -
- - -function | module.function -[buffer_type=string | buffer] - -location -if in location -limit_except -0.5.2 - - -Sets an njs function as a response body filter. -The filter function is called for each data chunk of a response body -with the following arguments: - - -r - -the HTTP request object - - -data - -the incoming data chunk, -may be a string or Buffer -depending on the buffer_type value, -by default is a string. - - -flags - -an object with the following properties: - -last - -a boolean value, true if data is a last buffer. - - - - - - - - - -The filter function can pass its own modified version -of the input data chunk to the next body filter by calling -r.sendBuffer(). -For example, to transform all the lowercase letters in the response body: - -function filter(r, data, flags) { - r.sendBuffer(data.toLowerCase(), flags); -} - -To stop filtering (following data chunks will be passed to client -without calling js_body_filter), -r.done() -can be used. - - - -If the filter function changes the length of the response body, then -it is required to clear out the
Content-Length
response header -(if any) in -js_header_filter -to enforce chunked transfer encoding. -
- - - -As the js_body_filter handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -r.subrequest() -or -setTimeout() -are not supported. - - - - - -The directive can be specified inside the -if block -since 0.7.7. - - - -
- - - -function | module.function - -location -if in location -limit_except - - -Sets an njs function as a location content handler. -Since 0.4.0, -a module function can be referenced. - - - - -The directive can be specified inside the -if block -since 0.7.7. - - - - - - - -size -16k -http -server -location -0.7.4 - - -Sets the size of the buffer used for reading and writing -with Fetch API. - - - - - - -ciphers -HIGH:!aNULL:!MD5 -http -server -location -0.7.0 - - -Specifies the enabled ciphers for HTTPS requests -with Fetch API. -The ciphers are specified in the format understood by the -OpenSSL library. - - - -The full list can be viewed using the -“openssl ciphers” command. - - - - - - -size -1m -http -server -location -0.7.4 - - -Sets the maximum size of the response received -with Fetch API. - - - - - - - - [TLSv1] - [TLSv1.1] - [TLSv1.2] - [TLSv1.3] -TLSv1 TLSv1.1 TLSv1.2 -http -server -location -0.7.0 - - -Enables the specified protocols for HTTPS requests -with Fetch API. - - - - - - -time -60s -http -server -location -0.7.4 - - -Defines a timeout for reading and writing -for Fetch API. -The timeout is set only between two successive read/write operations, -not for the whole response. -If no data is transmitted within this time, the connection is closed. - - - - - - -file - -http -server -location -0.7.0 - - -Specifies a file with trusted CA certificates in the PEM format -used to -verify -the HTTPS certificate -with Fetch API. - - - - - - -on | off -on -http -server -location -0.7.4 - - -Enables or disables verification of the HTTPS server certificate -with Fetch API. - - - - - - -number -100 -http -server -location -0.7.0 - - -Sets the verification depth in the HTTPS server certificates chain -with Fetch API. - - - - - - -function | module.function - -location -if in location -limit_except -0.5.1 - - -Sets an njs function as a response header filter. -The directive allows changing arbitrary header fields of a response header. - - - - -As the js_header_filter handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -r.subrequest() -or -setTimeout() -are not supported. - - - - - -The directive can be specified inside the -if block -since 0.7.7. - - - - - - - -module.js | -export_name from module.js - -http -server -location -0.4.0 - - -Imports a module that implements location and variable handlers in njs. -The export_name is used as a namespace -to access module functions. -If the export_name is not specified, -the module name will be used as a namespace. - -js_import http.js; - -Here, the module name http is used as a namespace -while accessing exports. -If the imported module exports foo(), -http.foo is used to refer to it. - - - -Several js_import directives can be specified. - - - - -The directive can be specified on the -server and location level -since 0.7.7. - - - - - - - -file - -http - - -Specifies a file that implements location and variable handlers in njs: - -nginx.conf: -js_include http.js; -location /version { - js_content version; -} - -http.js: -function version(r) { - r.return(200, njs.version); -} - - - - -The directive was made obsolete in version -0.4.0 -and was removed in version -0.7.1. -The directive should be used instead. - - - - - - - -path - -http -server -location -0.3.0 - - -Sets an additional path for njs modules. - - - - -The directive can be specified on the -server and location level -since 0.7.7. - - - - - - - -function | - module.function - [interval=time] - [jitter=number] - [worker_affinity=mask] - -location -0.8.1 - - -Specifies a content handler to run at regular interval. -The handler receives a -session object -as its first argument, -it also has access to global objects such as -ngx. - - - -The optional interval parameter -sets the interval between two consecutive runs, -by default, 5 seconds. - - - -The optional jitter parameter sets the time within which -the location content handler will be randomly delayed, -by default, there is no delay. - - - -By default, the js_handler is executed on worker process 0. -The optional worker_affinity parameter -allows specifying particular worker processes -where the location content handler should be executed. -Each worker process set is represented by a bitmask of allowed worker processes. -The all mask allows the handler to be executed -in all worker processes. - - - -Example: - -example.conf: - -location @periodics { - # to be run at 1 minute intervals in worker process 0 - js_periodic main.handler interval=60s; - - # to be run at 1 minute intervals in all worker processes - js_periodic main.handler interval=60s worker_affinity=all; - - # to be run at 1 minute intervals in worker processes 1 and 3 - js_periodic main.handler interval=60s worker_affinity=0101; - - resolver 10.0.0.1; - js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; -} - -example.js: - -async function handler(s) { - let reply = await ngx.fetch('https://nginx.org/en/docs/njs/'); - let body = await reply.text(); - - ngx.log(ngx.INFO, body); -} - - - - - - - -name.json | -name from file.json - -http -server -location -0.7.8 - - -Preloads an -immutable object -at configure time. -The name is used as a name of the global variable -though which the object is available in njs code. -If the name is not specified, -the file name will be used instead. - -js_preload_object map.json; - -Here, the map is used as a name -while accessing the preloaded object. - - - -Several js_preload_object directives can be specified. - - - - - - - -$variable function | -module.function - -http -server -location - - -Sets an njs function -for the specified variable. -Since 0.4.0, -a module function can be referenced. - - - -The function is called when -the variable is referenced for the first time for a given request. -The exact moment depends on a -phase -at which the variable is referenced. -This can be used to perform some logic -not related to variable evaluation. -For example, if the variable is referenced only in the - directive, -its handler will not be executed until the log phase. -This handler can be used to do some cleanup -right before the request is freed. - - - - -As the js_set handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -r.subrequest() -or -setTimeout() -are not supported. - - - - - -The directive can be specified on the -server and location level -since 0.7.7. - - - - - - - - - zone=name:size - [timeout=time] - [type=string|number] - [evict] - -http -0.8.0 - - -Sets the name and size of the shared memory zone -that keeps the -key-value dictionary -shared between worker processes. - - - -By default the shared dictionary uses a string as a key and a value. -The optional type parameter -allows redefining the value type to number. - - - -The optional timeout parameter sets -the time after which all shared dictionary entries are removed from the zone. - - - -The optional evict parameter removes the oldest -key-value pair when the zone storage is exhausted. - - - -Example: - -example.conf: - # Creates a 1Mb dictionary with string values, - # removes key-value pairs after 60 seconds of inactivity: - js_shared_dict_zone zone=foo:1M timeout=60s; - - # Creates a 512Kb dictionary with string values, - # forcibly removes oldest key-value pairs when the zone is exhausted: - js_shared_dict_zone zone=bar:512K timeout=30s evict; - - # Creates a 32Kb permanent dictionary with number values: - js_shared_dict_zone zone=num:32k type=number; - -example.js: - function get(r) { - r.return(200, ngx.shared.foo.get(r.args.key)); - } - - function set(r) { - r.return(200, ngx.shared.foo.set(r.args.key, r.args.value)); - } - - function del(r) { - r.return(200, ngx.shared.bar.delete(r.args.key)); - } - - function increment(r) { - r.return(200, ngx.shared.num.incr(r.args.key, 2)); - } - - - - - - - -$variable [value] - -http -server -location -0.5.3 - - -Declares -a writable -variable. -The value can contain text, variables, and their combination. -The variable is not overwritten after a redirect -unlike variables created with the - directive. - - - - -The directive can be specified on the -server and location level -since 0.7.7. - - - - - -
- - -
- - -Each HTTP njs handler receives one argument, a request -object. - - -
- -
diff --git a/xml/en/docs/index.xml b/xml/en/docs/index.xml --- a/xml/en/docs/index.xml +++ b/xml/en/docs/index.xml @@ -8,7 +8,7 @@
@@ -98,14 +98,6 @@ -Scripting with njs - - - - - - - Chapter “nginx” in “The Architecture of Open Source Applications” @@ -301,11 +293,6 @@ ngx_http_index_module - -ngx_http_js_module - - - ngx_http_limit_conn_module @@ -513,11 +500,6 @@ ngx_stream_geoip_module - -ngx_stream_js_module - - - ngx_stream_limit_conn_module diff --git a/xml/en/docs/njs/changes.xml b/xml/en/docs/njs/changes.xml deleted file mode 100644 --- a/xml/en/docs/njs/changes.xml +++ /dev/null @@ -1,6793 +0,0 @@ - - - - - - -
- -
- - -Release Date: -07 February 2024 - - - -nginx modules: - - - - -Bugfix: -fixed -Headers.set(). - - - - - -Bugfix: -fixed - -with Buffer values. - - - - - -Bugfix: -fixed -clear() -method of a shared dictionary when a timeout is not specified. - - - - - -Bugfix: -fixed -stub_status -statistics when -js_periodic -is enabled. - - - - - - - -Core: - - - - -Bugfix: -fixed building with -libxml2 2.12 -and later. - - - - - -Bugfix: -fixed Date constructor for overflows -and with NaN values. - - - - - -Bugfix: -fixed underflow in -querystring.parse(). - - - - - -Bugfix: -fixed potential buffer overread in -String.prototype.match(). - - - - - -Bugfix: -fixed parsing of for-in loops. - - - - - -Bugfix: -fixed parsing of -hexadecimal, octal, and binary literals with no digits. - - - - - - -
- - -
- - -Release Date: -24 October 2023 - - - -nginx modules: - - - - -Feature: -introduced -console object. -The following methods were introduced: -error(), -info(), -log(), -time(), -timeEnd(), -warn(). - - - - - -Bugfix: -fixed -HEAD response handling with large Content-Length in -Fetch API. - - - - - -Bugfix: -fixed -items() -method for a shared dictionary. - - - - - -Bugfix: -fixed -delete() -method for a shared dictionary. - - - - - - - -Core: - - - - -Feature: -extended -fs module. -Added -fs.existsSync(). - - - - - -Bugfix: -fixed -xml module. -Broken XML exception handling in -xml.parse() -method was fixed. - - - - - -Bugfix: -fixed -Regexp.prototype.exec() with global regexp and Unicode input. - - - - - - -
- - -
- - -Release Date: -12 September 2023 - - - -nginx modules: - - - - -Feature: -introduced the js_periodic directive for -http -and -stream -that allows specifying a JS handler to run at regular intervals. - - - - - -Feature: -implemented -items() -method of a -shared dictionary. -The method returns all the non-expired key-value pairs. - - - - - -Bugfix: -fixed -size() -and -keys() -methods of a -shared dictionary. - - - - - -Bugfix: -fixed erroneous exception in -r.internalRedirect() -introduced in 0.8.0. - - - - - - - -Core: - - - - -Bugfix: -fixed incorrect order of keys in -Object.getOwnPropertyNames(). - - - - - - -
- - -
- - -Release Date: -06 July 2023 - - - -nginx modules: - - - - -Change: -removed special treatment of forbidden headers in -Fetch API -introduced in 0.7.10. - - - - - -Change: -removed deprecated since 0.5.0 -r.requestBody -and -r.responseBody -in -http -module. - - - - - -Change: -throwing an exception in -r.internalRedirect() -while filtering in -http -module. - - - - - -Feature: -introduced more global -nginx properties: -ngx.build, -ngx.conf_file_path, -ngx.error_log_path, -ngx.prefix, -ngx.version, -ngx.version_number, -and -ngx.worker_id. - - - - - -Feature: -introduced the js_shared_dict_zone directive for -http -and -stream -that allows declaring a dictionary shared between worker processes. - - - - - -Feature: -introduced global -nginx.shared -methods and properties for working with shared dictionaries. - - - - - -Improvement: -added compile-time options to disable njs modules. -For example, to disable libxslt-related code: - -NJS_LIBXSLT=NO ./configure .. --add-module=/path/to/njs/module - - - - - - -Bugfix: -fixed -r.status -setter when filtering in -http -module. - - - - - -Bugfix: -fixed setting of Location header in -http -module. - - - - - - - -Core: - - - - -Change: -native methods are provided with retval argument. -This change breaks compatibility with C extension for njs -requiring the modification of the code. - - - - - -Change: -non-compliant deprecated String methods were removed. -The following methods were removed: -String.bytesFrom(), -String.prototype.fromBytes(), -String.prototype.fromUTF8(), -String.prototype.toBytes(), -String.prototype.toUTF8(), -String.prototype.toString(encoding). - - - - - -Change: -removed support for building with GNU readline. - - - - - -Feature: -added ES13-compliant Array methods: -Array.from(), -Array.prototype.toSorted(), -Array.prototype.toSpliced(), -Array.prototype.toReversed(). - - - - - -Feature: -added ES13-compliant TypedArray methods: -%TypedArray%.prototype.toSorted(), -%TypedArray%.prototype.toSpliced(), -%TypedArray%.prototype.toReversed(). - - - - - -Feature: -added -CryptoKey -properties in -WebCrypto API. -The following properties were added: -algorithm, -extractable, -type, -usages. - - - - - -Bugfix: -fixed retval of -сrypto.getRandomValues(). - - - - - -Bugfix: -fixed evaluation of computed property names with function expressions. - - - - - -Bugfix: -fixed implicit name for a function expression declared in arrays. - - - - - -Bugfix: -fixed parsing of for-in loops. - - - - - -Bugfix: -fixed -Date.parse() with ISO-8601 format and UTC time offset. - - - - - - -
- - -
- - -Release Date: -10 April 2023 - - - -nginx modules: - - - - -Bugfix: -fixed Headers() constructor in -Fetch API. - - - - - - - -Core: - - - - -Feature: -added -Hash.copy() -method in -crypto module. - - - - - -Feature: -added -zlib -module. - - - - - -Improvement: -added support for -export {name as default} statement. - - - - - -Bugfix: -fixed Number constructor according to the spec. - - - - - - -
- - -
- - -Release Date: -09 March 2023 - - - -nginx modules: - - - - -Bugfix: -added missed linking with -libxml2 -for the dynamic module. -The bug was introduced in 0.7.10. - - - - - - - -Core: - - - - -Feature: -added -XMLNode API -to modify XML documents. - - - - - -Change: -removed XML_PARSE_DTDVALID during parsing of an XML document -due to security implications. -The issue was introduced in 0.7.10. -When XML_PARSE_DTDVALID is enabled, -libxml2 -parses and executes external entities present inside an XML document. - - - - - -Bugfix: -fixed the detection of await in arguments. - - - - - -Bugfix: -fixed Error() instance dumping -when “name” prop is not primitive. - - - - - -Bugfix: -fixed array instance with a getter property dumping. - - - - - -Bugfix: -fixed njs_object_property() with -NJS_WHITEOUT properties. - - - - - -Bugfix: -fixed func instance dumping -with “name” as getter. - - - - - -Bugfix: -fixed attaching of a stack to an error object. - - - - - -Bugfix: -fixed String.prototype.replace() with replacement -containing “$'”, “$`”. - - - - - - -
- - -
- - -Release Date: -07 February 2023 - - - -nginx modules: - - - - -Feature: -added -Request, -Response, -and -Headers -ctors in -Fetch API. - - - - - -Bugfix: -fixed nginx logger callback for calls in the master process. - - - - - - - -Core: - - - - -Feature: -added signal support in CLI. - - - - - -Feature: -added -xml -module for working with XML documents. - - - - - -Feature: -extended support for symmetric and asymmetric keys in WebCrypto. -Most notably JWK format for -importKey() -was added. - - - - - -Feature: -extended support for symmetric and asymmetric keys in -WebCrypto API. -Most notably JWK format for -importKey() -was added. -generateKey() -and -exportKey() -were also implemented. - - - - - -Feature: -added -String.prototype.replaceAll(). - - - - - -Bugfix: -fixed for(expr1; conditional syntax error handling. - - - - - -Bugfix: -Object.values() -and -Object.entries() -with external objects. - - - - - -Bugfix: -fixed RegExp.prototype[@@replace](). - - - - - - -
- - -
- - -Release Date: -17 November 2022 - - - -nginx modules: - - - - -Bugfix: -fixed -Fetch -Response prototype reinitialization. -When at least one js_import directive was declared in both -HTTP -and -Stream, -ngx.fetch() -returned inapproriate response in Stream. -The bug was introduced in 0.7.7. - - - - - - - -Core: - - - - -Bugfix: -fixed String.prototype.replace(re) -if re.exec() returns non-flat array. - - - - - -Bugfix: -fixed Array.prototype.fill() -when start object changes this. - - - - - -Bugfix: -fixed description for -fs.mkdir() -and -fs.rmdir() -methods. - - - - - -Bugfix: -fixed %TypedArray%.prototype.set(s) -when s element changes this. - - - - - -Bugfix: -fixed Array.prototype.splice(s,d) -when d resizes this during eval. - - - - - -Bugfix: -fixed for-in loop with left and right hand side expressions. - - - - - - -
- - -
- - -Release Date: -25 October 2022 - - - -nginx modules: - - - - -Feature: -added - directive. - - - - - -Feature: -added -ngx.conf_prefix -property. - - - - - -Feature: -added -s.sendUpstream() -and -s.sendDownstream() -in -stream module. - - - - - -Feature: -added support for HEAD method in -Fetch API. - - - - - -Improvement: -improved async callback support for -s.send() -in -stream module. - - - - - - - -Core: - - - - -Feature: -added name instance property for a function object. - - - - - -Feature: -added -njs.memoryStats -object. - - - - - -Bugfix: -fixed -String.prototype.trimEnd() -with unicode string. - - - - - -Bugfix: -fixed Object.freeze() with fast arrays. - - - - - -Bugfix: -fixed Object.defineProperty() with fast arrays. - - - - - -Bugfix: -fixed async token as a property name of an object. - - - - - -Bugfix: -fixed property set instruction when key modifies base binding. - - - - - -Bugfix: -fixed complex assignments. - - - - - -Bugfix: -fixed handling of unhandled promise rejection. - - - - - -Bugfix: -fixed process.env -when duplicate environ variables are present. - - - - - -Bugfix: -fixed double declaration detection in modules. - - - - - -Bugfix: -fixed bound function calls according to the spec. - - - - - -Bugfix: -fixed break label for if statement. - - - - - -Bugfix: -fixed labeled empty statements. - - - - - - -
- - -
- - -Release Date: -30 August 2022 - - - -nginx modules: - - - - -Feature: -the number of nginx configuration contexts where -js directives can be specified is extended. - - - - - -HTTP: -the , -, -, and - directives -are allowed in -server and location contexts. -The , - and - -are allowed in - context. - - - - - -Stream: -the , -, -, and - -are allowed in -server context. - - - - - - - - - - -Feature: -added -r.internal -property. - - - - - -Bugfix: -fixed reading response body in -Fetch API. - - - - - -Bugfix: -fixed - -in stream. - - - - - -Bugfix: -fixed socket leak with 0 fetch timeout. - - - - - - - -Core: - - - - -Feature: -extended -fs module. -Added -fs.openSync(), -fs.promises.open(), -fs.fstatSync(), -fs.readSync(), -fs.writeSync(). - - - -The following properties of -FileHandle -are implemented: -fd, -read(), -stat(), -write(), -close(). - - - - - -Bugfix: -fixed parseInt(), -parseFloat(), -Symbol.for() -with no arguments. - - - - - - -
- - -
- - -Release Date: -19 July 2022 - - - -nginx modules: - - - - -Feature: -improved -r.args{} object. -Added support for multiple arguments with the same key. -Added case sensitivity for keys. -Keys and values are percent-decoded now. - - - - - -Bugfix: -fixed -r.headersOut{} -setter for special headers. - - - - - - - -Core: - - - - -Feature: -added Symbol.for() and Symbol.keyfor(). - - - - - -Feature: -added -atob() -and -btoa() -from -WHATWG spec. - - - - - -Bugfix: -fixed large non-decimal literals. - - - - - -Bugfix: -fixed Unicode argument trimming in parseInt(). - - - - - -Bugfix: -fixed break instruction -in try-catch block. - - - - - -Bugfix: -fixed async function declaration in CLI. - - - - - - -
- - -
- - -Release Date: -21 June 2022 - - - -nginx modules: - - - - -Change: -adapting to changes in nginx header structures. - - - - - -Bugfix: -fixed -r.headersOut{} -special getters when value is absent. - - - - - -Change: -returning undefined value instead of an empty string for -Content-Type when the header is absent. - - - - - - - -Core: - - - - -Bugfix: -fixed catching of the exception thrown from an awaited function. - - - - - -Bugfix: -fixed function value initialization. - - - - - -Bugfix: -fixed interpreter when await fails. - - - - - -Bugfix: -fixed typed-array constructor when source array is changed while iterating. - - - - - -Bugfix:fixed -String.prototype.replace() -with byte strings. - - - - - -Bugfix: -fixed template literal from producing byte-strings. - - - - - -Bugfix: -fixed array iterator with sparse arrays. - - - - - -Bugfix: -fixed memory free while converting a flat array to a slow array. - - - - - -Bugfix: -properly handling NJS_DECLINE in -promise native functions. - - - - - -Bugfix: -fixed working with an array-like object in -Promise.all() -and friends. - - - - - - -
- - -
- - -Release Date: -24 May 2022 - - - -nginx modules: - - - - -Feature: -added extended directives for configuring -Fetch API. -The following directives were added for -http and -stream: - - - - -, - - - - - -, - - - - - -, - - - - - -. - - - - - - - - - - -Change: -r.internalRedirect() now accepts escaped URIs. - - - - - -Bugfix: -fixed -Response parsing -with more than 8 headers in -Fetch API. - - - - - - - -Core: - - - - -Feature: -added -njs.version_number property. - - - - - -Feature: -added compatibility with BoringSSL for -WebCrypto API. - - - - - -Bugfix: -fixed -Array.prototype.sort() -when arr size is changed in a comparator. - - - - - -Bugfix: -fixed -Array.prototype.slice() -with slow this argument. - - - - - -Bugfix: -fixed aggregation methods of Promise ctor -with array-like object. - - - - - -Bugfix: -fixed String.prototype.lastIndexOf() -with Unicode string as this. - - - - - -Bugfix: -fixed -JSON.parse() -when reviver function is provided. - - - - - -Bugfix: -fixed -Object.defineProperty() -when a recursive descriptor is provided. - - - - - -Bugfix: -fixed Array.prototype.fill() for typed-arrays. - - - - - -Bugfix: -making function expression binding immutable according to the specs. - - - - - -Bugfix: -fixed redefinition of special props in -Object.defineProperty(). - - - - - - -
- - - -
- - -Release Date: -12 April 2022 - - - -Core: - - - - -Feature: -added support of module resolution callback. -This feature allows the host environment to control -how imported modules are loaded. - - - - - -Bugfix: -fixed backtraces while traversing imported user modules. - - - - - -Bugfix: -fixed -Array.prototype.concat() -when this is a slow array. - - - - - -Bugfix: -fixed frame allocation from an awaited frame. - - - - - -Bugfix: -fixed allocation of large array literals. - - - - - -Bugfix: -fixed interpreter when toString conversion fails. - - - - - - -
- - -
- - -Release Date: -25 January 2022 - - - -Core: - - - - -Bugfix: -fixed -Array.prototype.join() -when array is changed while iterating. - - - - - -Bugfix: -fixed -Array.prototype.slice() -when array is changed while iterating. - - - - - -Bugfix: -fixed -Array.prototype.concat() -when array is changed while iterating. - - - - - -Bugfix: -fixed -Array.prototype.reverse() -when array is changed while iterating. - - - - - -Bugfix: -fixed -Buffer.concat() -with subarrays. -Thanks to Sylvain Etienne. - - - - - -Bugfix: -fixed -type confusion bug while resolving promises. - - - - - -Bugfix: -fixed -Function.prototype.apply() -with large array arguments. - - - - - -Bugfix: -fixed recursive async function calls. - - - - - -Bugfix: -fixed function redeclaration. -The bug was introduced in -0.7.0. - - - - - - -
- - -
- - -Release Date: -28 December 2021 - - - -nginx modules: - - - - -Change: -the directive -deprecated since 0.4.0 was removed. - - - - - -Change: -PCRE/PCRE2-specific code was moved to the modules. -This ensures that njs uses the same RegExp library as nginx. - - - - - - - -Core: - - - - -Bugfix: -fixed -decodeURI() and -decodeURIComponent() -with invalid byte strings. -The bug was introduced in -0.4.3. - - - - - -Bugfix: -fixed heap-use-after-free in await frame. -The bug was introduced in -0.7.0. - - - - - -Bugfix: -fixed WebCrypto sign() and -verify() methods with OpenSSL 3.0. - - - - - -Bugfix: -fixed exception throwing when RegExp match fails. -The bug was introduced in -0.1.15. - - - - - -Bugfix: -fixed catching of exception thrown in try block -of async function. -The bug was introduced in -0.7.0. - - - - - -Bugfix: -fixed execution of async function in synchronous context. -The bug was introduced in -0.7.0. - - - - - -Bugfix: -fixed function redeclaration in CLI when interactive mode is on. -The bug was introduced in -0.6.2. - - - - - -Bugfix: -fixed typeof operator with -DataView object. - - - - - -Bugfix: eliminated information leak in Buffer.from(). - - - - - - - -
- - -
- - -Release Date: -19 October 2021 - - - -nginx modules: - - - - -Feature: -Added -HTTPS -support for -Fetch API. - - - - - -Feature: -Added -setReturnValue() method for -http and -stream. - - - - - - - -Core: - - - - -Feature: -introduced Async/Await implementation. - - - - - -Feature: -added -WebCrypto API -implementation. - - - - - -Bugfix: -fixed copying of closures for declared functions. -The bug was introduced in -0.6.0. - - - - - -Bugfix: -fixed unhandled promise rejection in handle events. - - - - - -Bugfix: -fixed Response.headers getter in Fetch API. - - - - - - - -
- - -
- - -Release Date: -31 August 2021 - - - -nginx modules: - - - - -Bugfix: -fixed CPU hog when -js_filter is registered in both directions. - - - - - - - -Core: - - - - -Feature: -introduced AggregateError implementation. - - - - - -Feature: -added remaining Promise constructor methods. -The following methods were added: -Promise.all(), -Promise.allSettled(), -Promise.any(), -Promise.race(). - - - - - -Improvement: -removed recursion from code generator. - - - - - -Bugfix: -fixed rest parameter parsing without binding identifier. - - - - - -Bugfix: -fixed resolve/reject callback for -Promise.prototype.finally() . - - - - - -Bugfix: -fixed %TypedArray%.prototype.join() -with detached buffer. - - - - - -Bugfix: -fixed memory leak in interactive shell. - - - - - - -
- - -
- - -Release Date: -29 June 2021 - - - - - - - -Bugfix: -fixed RegExpBuiltinExec() with UTF-8 only regexps. -The bug was introduced in 0.4.2. - - - - - -Bugfix: -fixed parsing of export default declaration with non-assignment expressions. -Thanks to Artem S. Povalyukhin. - - - - - - -
- - -
- - -Release Date: -15 June 2021 - - - -Core: - - - - -Feature: -added -let and -const declaration support. - - - - - -Feature: -added RegExp.prototype[Symbol.split]. - - - - - -Feature: -added sticky flag support for RegExp. - - - - - -Bugfix: -fixed heap-buffer-overflow in -String.prototype.lastIndexOf(). - - - - - -Bugfix: -fixed -RegExp.prototype.test() -according to the specification. - - - - - -Bugfix: -fixed -String.prototype.split() -according to the specification. - - - - - -Bugfix: -fixed use-of-uninitialized-value while tracking rejected promises. - - - - - -Bugfix: -fixed njs.dump() for objects with circular references. - - - - - - -
- - -
- - -Release Date: -30 March 2021 - - - -nginx modules: - - - - -Feature: -added the js_var directive for -http and -stream. - - - - - - -
- - -
- - -Release Date: -09 March 2021 - - - -nginx modules: - - - - -Feature: -added the -js_body_filter -directive. - - - - - -Feature: -introduced the -s.status -property for -Stream Session -object. - - - - - - - -Core: - - - - -Feature: -added -njs.on -(exit) callback support. - - - - - -Bugfix: -fixed property descriptor reuse for not extensible objects. -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed Object.freeze() and friends -according to the specification. -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed Function() in CLI mode. - - - - - -Bugfix: -fixed for-in iteration of typed array values. -Thanks to Artem S. Povalyukhin. - - - - - - -
- - -
- - -Release Date: -16 February 2021 - - - -nginx modules: - - - - -Feature: -introduced -ngx.fetch() -method implementing Fetch API. - - - -The following properties and methods of -Response -object are implemented: -arrayBuffer(), -bodyUsed, -json(), -headers, -ok, -redirect, -status, -statusText, -text(), -type, -url. - - - -Notable limitations: -only the http:// scheme is supported, -redirects are not handled. - - - -In collaboration with 洪志道 (Hong Zhi Dao). - - - - - -Feature: -added the -js_header_filter -directive. - - - - - -Bugfix: -fixed processing buffered data in body filter in -stream module. - - - - - - - -Core: - - - - -Bugfix: -fixed safe mode bypass in Function constructor. - - - - - -Bugfix: -fixed Date.prototype.toISOString() with invalid date values. - - - - - - -
- - -
- - -Release Date: -01 December 2020 - - - -nginx modules: - - - - -Feature: -introduced global -ngx object. - - - -The following methods were added: - - - - -ngx.log(level, -message) - - - - - - - -The following properties were added: - - - - -ngx.INFO, -ngx.WARN, -ngx.ERR. - - - - - - - - - - -Feature: -added support for -Buffer object where string is expected. - - - - - -Feature: -added Buffer version of existing properties. - - - -The following properties were added: - - - - -r.requestBuffer -(r.requestBody), -r.responseBuffer -(r.responseBody), -r.rawVariables -(r.variables), -s.rawVariables -(s.variables). - - - - - - - -The following events were added in the stream module: - - - - -upstream -(upload), -downstream -(download). - - - - - - - - - - -Improvement: -added aliases to existing properties. - - - -The following properties were added: - - - - -r.requestText -(r.requestBody), -r.responseText -(r.responseBody). - - - - - - - - - - -Improvement: -throwing an exception in -r.internalRedirect() -for a subrequest. - - - - - -Bugfix: -fixed promise -r.subrequest() -with -error_page -redirect. - - - - - -Bugfix: -fixed -promise events handling. - - - - - - - -Core: - - - - -Feature: -added -TypeScript definitions for built-in modules. -Thanks to Jakub Jirutka. - - - - - -Feature: -tracking unhandled promise rejection. - - - - - -Feature: -added initial iterator support. -Thanks to Artem S. Povalyukhin. - - - - - -Improvement: -TypeScript definitions are refactored. -Thanks to Jakub Jirutka. - - - - - -Improvement: -added forgotten support for -Object.prototype.valueOf() -in -Buffer.from(). - - - - - -Bugfix: -fixed heap-use-after-free in -JSON.parse(). - - - - - -Bugfix: -fixed heap-use-after-free in -JSON.stringify(). - - - - - -Bugfix: -fixed -JSON.stringify() for arrays resizable via getters. - - - - - -Bugfix: -fixed heap-buffer-overflow for -RegExp.prototype[Symbol.replace]. - - - - - -Bugfix: -fixed returned value for -Buffer.prototype.write* -functions. - - - - - -Bugfix: -fixed -querystring.stringify(). -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed the catch handler for -Promise.prototype.finally(). - - - - - -Bugfix: -fixed -querystring.parse(). - - - - - - -
- - -
- - -Release Date: -29 September 2020 - - - -nginx modules: - - - - -Bugfix: -fixed location merge. - - - - - -Bugfix: -fixed -r.httpVersion -for HTTP/2. - - - - - - - -Core: - - - - -Feature: -added support for numeric separators (ES12). - - - - - -Feature: -added remaining methods for -%TypedArray%.prototype. -The following methods were added: -every(), -filter(), -find(), -findIndex(), -forEach(), -includes(), -indexOf(), -lastIndexOf(), -map(), -reduce(), -reduceRight(), -reverse(), -some(). - - - - - -Feature: -added %TypedArray% remaining methods. -The following methods were added: -from(), -of(). - - - - - -Feature: -added DataView object. - - - - -Feature: -added Buffer object implementation. - - - - - -Feature: -added support for ArrayBuffer in -TextDecoder.prototype.decode() - - - - - -Feature: -added support for Buffer object in -crypto -methods. - - - - - -Feature: -added support for Buffer object in -fs -methods. - - - - - -Change: -Hash.prototype.digest() -and -Hmac.prototype.digest() -now return a Buffer instance instead of a byte string when -encoding is not provided. - - - - - -Change: -fs.readFile() -and friends now return a Buffer instance -instead of a byte string when encoding is not provided. - - - - - -Bugfix: -fixed function prototype property handler while setting. - - - - - -Bugfix: -fixed function constructor property handler while setting. - - - - - -Bugfix: -fixed String.prototype.indexOf() -for byte strings. - - - - - -Bugfix: -fixed RegExpBuiltinExec() -with a global flag and byte strings. - - - - - -Bugfix: -fixed RegExp.prototype[Symbol.replace] -the when replacement value is a function. - - - - - -Bugfix: -fixed -TextDecoder.prototype.decode() -with non-zero TypedArray offset. - - - - - - -
- - -
- - -Release Date: -11 August 2020 - - - -Core: - - - - -Feature: -added -Query String -module. - - - - - -Feature: -improved -fs.mkdir() -to support recursive directory creation. -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -improved -fs.rmdir() -to support recursive directory removal. -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -introduced UTF-8 decoder according to -WHATWG encoding spec. - - - - - -Feature: -added -TextDecoder() -and -TextEncoder() -implementation. - - - - - -Bugfix: -fixed parsing return statement without semicolon. - - - - - -Bugfix: -fixed njs_number_to_int32() for big-endian platforms. - - - - - -Bugfix: -fixed unit test on big-endian platforms. - - - - - -Bugfix: -fixed regexp-literals parsing with “=” characters. - - - - - -Bugfix: -fixed pre/post increment/decrement in assignment operations. - - - - - - -
- - -
- - -Release Date: -07 July 2020 - - - -Core: - - - - -Feature: -added RegExp.prototype[Symbol.replace]. - - - - - -Feature: -introduced line level backtrace. - - - - - -Feature: -added %TypedArray%.prototype.sort(). - - - - - -Feature: -extended -fs module. -Added -mkdir(), -readdir(), -rmdir(), -and friends. - - - - - -Improvement: -parser refactoring. - - - - - -Bugfix: -fixed TypedScript API description for HTTP headers. - - - - - -Bugfix: -fixed TypedScript API description for NjsByteString type. - - - - - -Bugfix: -fixed -String.prototype.repeat() -according to the specification. - - - - - -Bugfix: -fixed -String.prototype.replace() -according to the specification. - - - - - -Bugfix: -fixed parsing of flags for regexp literals. - - - - - -Bugfix: -fixed index generation for global objects in generator. - - - - - -Bugfix: -fixed %TypedArray%.prototype.copyWithin() -with nonzero byte offset. - - - - - -Bugfix: -fixed Array.prototype.splice() -for sparse arrays. - - - - - -Bugfix: -fixed Array.prototype.reverse() -for sparse arrays. - - - - - -Bugfix: -fixed Array.prototype.sort() -for sparse arrays. - - - - - - -
- - -
- - -Release Date: -19 May 2020 - - - -nginx modules: - - - - -Feature: -added support for multi-value headers in -r.headersIn{}. - - - - - -Feature: -introduced raw headers API: -r.rawHeadersIn[] -and -r.rawHeadersOut[]. - - - - - -Feature: -added TypeScript API description. - - - - - - - -Core: - - - - -Bugfix: -fixed Array.prototype.slice() for sparse arrays. - - - - - - -
- - -
- - -Release Date: -23 April 2020 - - - -nginx modules: - - - - -Feature: -added support for multi-value headers in -r.headersOut{}. - - - - - -Feature: -added js_import directive for -http and -stream. - - - - - -Improvement: -improved iteration over -r.headersOut{} -with special headers. - - - - - -Improvement: -improved iteration over -r.headersOut{} -with duplicates. - - - - - -Change: -r.responseBody -property handler now returns -undefined -instead of throwing an exception if the response body is not available. - - - - - - - -Core: - - - - -Feature: -added script arguments support in CLI. - - - - - -Feature: -converting externals values to native js objects. - - - - - -Bugfix: -fixed NULL-pointer dereference -in __proto__ property handler. - - - - - -Bugfix: -fixed handling of no-newline at the end of the script. - - - - - -Bugfix: -fixed RegExp() constructor -with empty pattern and non-empty flags. - - - - - -Bugfix: -fixed -String.prototype.replace() -when function returns non-string. - - - - - -Bugfix: -fixed reading of pseudofiles in -fs. - - - - - - -
- - -
- - -Release Date: -03 March 2020 - - - -nginx modules: - - - - -Feature: -added detached mode for -r.subrequest(). -Responses to detached subrequests are ignored. -Unlike ordinary subrequests, -a detached subrequest can be created inside a variable handler. - - - - - - - -Core: - - - - -Feature: -added promises API for -fs module. -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -extended fs -module. -Added -access(), -symlink(), -unlink(), -realpath(), -and friends. -Thanks to Artem S. Povalyukhin. - - - - - -Improvement: -introduced memory-efficient ordinary arrays. - - - - - -Improvement: -lexer refactoring. - - - - - -Bugfix: -fixed matching of native functions in backtraces. - - - - - -Bugfix: -fixed callback invocations in -fs module. -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed Object.getOwnPropertySymbols(). - - - - - -Bugfix: -fixed heap-buffer-overflow in -njs_json_append_string(). - - - - - -Bugfix: -fixed -encodeURI() -and -decodeURI() -according to the specification. - - - - - -Bugfix: -fixed Number.prototype.toPrecision(). - - - - - -Bugfix: -fixed handling of space argument in -JSON.stringify(). - - - - - -Bugfix: -fixed -JSON.stringify() -with -Number() and -String() -objects. - - - - - -Bugfix: -fixed Unicode Escaping in -JSON.stringify() -according to specification. - - - - - -Bugfix: -fixed non-native module importing. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Bugfix: -fixed -njs.dump() with the -Date() -instance in a container. - - - - - - -
- - -
- - -Release Date: -21 January 2020 - - - -nginx modules: - - - - -Feature: -added Promise support for -r.subrequest(). -If a callback is not provided, -r.subrequest() -returns an ordinary -Promise object -that resolves to a subrequest response object. - - - - - -Change: -r.parent -property handler now returns -undefined -instead of throwing an exception if a parent object is not available. - - - - - - - -Core: - - - - -Feature: -added Promise support. -Implemented according to the specification without: -Promise.all(), -Promise.allSettled(), -Promise.race(). - - - - - -Feature: -added initial Typed-arrays support. -Thanks to Tiago Natel de Moura. - - - - - -Feature: -added ArrayBuffer support. -Thanks to Tiago Natel de Moura. - - - - - -Feature: -added initial Symbol support. -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -added externals support for -JSON.stringify(). - - - - - -Feature: -added Object.is(). -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -added Object.setPrototypeOf(). -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -introduced nullish coalescing operator. - - - - - -Bugfix: -fixed -Object.getPrototypeOf() -according to the specification. - - - - - -Bugfix: -fixed -Object.prototype.valueOf() -according to the specification. - - - - - -Bugfix: -fixed -JSON.stringify() -with unprintable values and replacer function. - - - - - -Bugfix: -fixed operator in -according to the specification. - - - - - -Bugfix: -fixed -Object.defineProperties() -according to the specification. - - - - - -Bugfix: -fixed -Object.create() -according to the specification. -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed -Number.prototype.toString(radix) -when fast-math is enabled. - - - - - -Bugfix: -fixed RegExp() instance properties. - - - - - -Bugfix: -fixed import segfault. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - - -
- - -
- - -Release Date: -19 November 2019 - - - -nginx modules: - - - - -Improvement: -refactored iteration over external objects. - - - - - - - -Core: - - - - -Feature: -added Object.assign(). - - - - - -Feature: -added Array.prototype.copyWithin(). - - - - - -Feature: -added support for labels in console.time(). - - - - - -Change: -removed console.help() from CLI. - - - - - -Improvement: -moved constructors and top-level objects to global object. - - - - - -Improvement: -arguments validation for configure script. - - - - - -Improvement: -refactored JSON methods. - - - - - -Bugfix: -fixed heap-buffer-overflow in -njs_array_reverse_iterator() function. -The following functions were affected: -Array.prototype.lastIndexOf(), -Array.prototype.reduceRight(). - - - - - -Bugfix: -fixed -[[Prototype]] slot of NativeErrors. - - - - - -Bugfix: -fixed -NativeError.prototype.message properties. - - - - - -Bugfix: -added conversion of -this value to object in -Array.prototype functions. - - - - - -Bugfix: -fixed iterator for -Array.prototype.find() and -Array.prototype.findIndex() -functions. - - - - - -Bugfix: -fixed -Array.prototype.includes() and -Array.prototype.join() with -undefined argument. - - - - - -Bugfix: -fixed constructor property of -Hash and -Hmac -objects. - - - - - -Bugfix: -fixed __proto__ property of getters and setters. - - - - - -Bugfix: -fixed Date object string formatting. - - - - - -Bugfix: -fixed handling of -NaN and -0 arguments in -Math.min() and -Math.max(). - - - - - -Bugfix: -fixed Math.round() -according to the specification. - - - - - -Bugfix: -reimplemented bound functions -according to the specification. - - - - - - -
- - -
- - -Release Date: -22 October 2019 - - - -nginx modules: - - - - -Improvement: -getting special headers from -r.headersIn{}. - - - - - - - -Core: - - - - -Feature: -added new Function() support. - - - - - -Feature: -added Number.prototype.toFixed(). - - - - - -Feature: -added Number.prototype.toPrecision(). - - - - - -Feature: -added Number.prototype.toExponential(). - - - - - -Improvement: -making prototype property of function instances writable. - - - - - -Improvement: -limiting recursion depth while compiling. - - - - - -Improvement: -moving global functions to the global object. - - - - - -Bugfix: -fixed prototype mutation for object literals. - - - - - -Bugfix: -fixed heap-buffer-overflow while parsing regexp literals. - - - - - -Bugfix: -fixed integer-overflow while parsing exponent of number literals. - - - - - -Bugfix: -fixed parseFloat(). - - - - - -Bugfix: -fixed Array.prototype functions -according to the specification. -The following functions were fixed: -every, -includes, -indexOf, -filter, -find, -findIndex, -forEach, -lastIndexOf, -map, -pop, -push, -reduce, -reduceRight, -shift, -some, -unshift. - - - - - -Bugfix: -fixed handing of accessor descriptors in Object.freeze(). - - - - - -Bugfix: -fixed -String.prototype.replace() -when first argument is not a string. - - - - - -Bugfix: -fixed stack-use-after-scope in Array.prototype.map(). - - - - - -Bugfix: -Date.prototype.toUTCString() -format was aligned to ES9. - - - - - -Bugfix: -fixed buffer overflow in -Number.prototype.toString(radix). - - - - - -Bugfix: -fixed -Regexp.prototype.test() -for regexps with backreferences. - - - - - -Bugfix: -fixed -Array.prototype.map() -for objects with nonexistent values. - - - - - -Bugfix: -fixed -Array.prototype.pop() and -shift() for sparse objects. - - - - - -Bugfix: -fixed -Date.UTC() -according to the specification. - - - - - -Bugfix: -fixed -Date() constructor -according to the specification. - - - - - -Bugfix: -fixed type of -Date.prototype. -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed -Date.prototype.setTime(). -Thanks to Artem S. Povalyukhin. - - - - - -Bugfix: -fixed default number of arguments expected by built-in functions. - - - - - -Bugfix: -fixed -caller and -arguments -properties of a function instance. -Thanks to Artem S. Povalyukhin. - - - - - - -
- - -
- - -Release Date: -15 August 2019 - - - -Core: - - - - -Bugfix: -fixed module importing using require(). -The bug was introduced in . - - - - - -Bugfix: -fixed -[[SetPrototypeOf]]. - - - - - - -
- - -
- - -Release Date: -13 August 2019 - - - -Core: - - - - -Feature: -added -Object -shorthand methods and computed property names. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. - - - - - -Feature: -added getter/setter literal support. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. - - - - - -Feature: -added -fs.renameSync(). - - - - - -Feature: -added -String.prototype.trimEnd() -and -String.prototype.trimStart(). - - - - - -Improvement: -added memory-sanitizer support. - - - - - -Improvement: -Unicode case tables updated to version 12.1. - - - - - -Improvement: -added UTF8 validation for string literals. - - - - - -Bugfix: -fixed reading files with zero size in -fs.readFileSync(). - - - - - -Bugfix: -extended the list of space separators in -String.prototype.trim(). - - - - - -Bugfix: -fixed using of uninitialized value in -String.prototype.padStart(). - - - - - -Bugfix: -fixed -String.prototype.replace() -for $0 and $& replacement string. - - - - - -Bugfix: -fixed -String.prototype.replace() -for byte strings with regex argument. - - - - - -Bugfix: -fixed global match in -String.prototype.replace() -with regexp argument. - - - - - -Bugfix: -fixed -Array.prototype.slice() -for primitive types. - - - - - -Bugfix: -fixed heap-buffer-overflow while importing module. - - - - - -Bugfix: -fixed UTF-8 character escaping. - - - - - -Bugfix: -fixed -Object.values() -and -Object.entries() -for shared objects. - - - - - -Bugfix: -fixed uninitialized memory access in -String.prototype.match(). - - - - - -Bugfix: -fixed -String.prototype.match() -for byte strings with regex argument. - - - - - -Bugfix: -fixed -Array.prototype.lastIndexOf() -with undefined arguments. - - - - - -Bugfix: -fixed -String.prototype.substring() -with empty substring. - - - - - -Bugfix: -fixed invalid memory access in -String.prototype.substring(). - - - - - -Bugfix: -fixed -String.fromCharCode() -for code points more than 65535 and NaN. - - - - - -Bugfix: -fixed -String.prototype.toLowerCase() -and -String.prototype.toUpperCase(). - - - - - -Bugfix: -fixed -Error() -constructor with no arguments. - - - - - -Bugfix: -fixed -in -operator for values with accessor descriptors. - - - - - -Bugfix: -fixed -Object.defineProperty() -for non-boolean descriptor props. - - - - - -Bugfix: -fixed -Error.prototype.toString() -with UTF8 string properties. - - - - - -Bugfix: -fixed -Error.prototype.toString() -with non-string values for name and message. - - - - - - -
- - -
- - -Release Date: -25 June 2019 - - - -nginx modules: - - - - -Improvement: -getting of special response headers in -r.headersOut{}. - - - - - -Improvement: -working with unknown methods in -r.subrequest(). - - - - - -Improvement: -added support for null as a second argument of -r.subrequest(). - - - - - -Bugfix: -fixed processing empty output chain in stream body filter. - - - - - - - -Core: - - - - -Feature: -added runtime support for property getter/setter. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. - - - - - -Feature: -added -process -global object. - - - - - -Feature: -writable most of built-in properties and methods. - - - - - -Feature: -added generic implementation of -Array.prototype.fill(). - - - - - -Bugfix: -fixed integer-overflow in -String.prototype.concat(). - - - - - -Bugfix: -fixed setting of object properties. - - - - - -Bugfix: -fixed -Array.prototype.toString(). - - - - - -Bugfix: -fixed -Date.prototype.toJSON(). - - - - - -Bugfix: -fixed overwriting “constructor” property of built-in prototypes. - - - - - -Bugfix: -fixed processing of invalid surrogate pairs in strings. - - - - - -Bugfix: -fixed processing of invalid surrogate pairs in JSON strings. - - - - - -Bugfix: -fixed heap-buffer-overflow in -toUpperCase() -and -toLowerCase(). - - - - - -Bugfix: -fixed escaping lone closing square brackets in -RegExp() constructor. - - - - - -Bugfix: -fixed handling zero byte characters inside RegExp pattern strings. - - - - - -Bugfix: -fixed -String.prototype.toBytes() -for ASCII strings. - - - - - -Bugfix: -fixed truth value of JSON numbers in -JSON.parse(). - - - - - -Bugfix: -fixed use-of-uninitialized-value in -njs_string_replace_join(). - - - - - -Bugfix: -fixed parseInt('-0'). -Thanks to Artem S. Povalyukhin. - - - - - - -
- - -
- - -Release Date: -21 May 2019 - - - -Core: - - - - -Feature: -added support for template literals. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. - - - - - -Feature: -executing command from command line arguments. - - - - - -Feature: -added support for RegExp groups object (ES9). - - - - - -Feature: -added block scoped function definitions support. - - - - - -Feature: -added support for building with GNU Readline library. - - - - - -Feature: -made configurable -length, -name, -and most of built-in methods. - - - - - -Feature: -made all constructor properties configurable. - - - - - -Bugfix: -fixed -Regexp.prototype.exec() -for Unicode-only regexps. - - - - - -Bugfix: -fixed -njs_vm_value_dump() -for empty string values. - - - - - -Bugfix: -fixed RegExp constructor for regexp value arguments. - - - - - -Bugfix: -fixed walking over prototypes chain during iteration over an object. - - - - - -Bugfix: -fixed overflow in -Array.prototype.concat(). - - - - - -Bugfix: -fixed length calculation for UTF-8 string with escape characters. - - - - - -Bugfix: -fixed parsing surrogate pair presents as UTF-16 escape sequences. - - - - - -Bugfix: -fixed processing the “*” quantifier for -String.prototype.match(). - - - - - -Bugfix: -fixed -Date() -constructor with one argument. - - - - - -Bugfix: -fixed arrays expansion. - - - - - -Bugfix: -fixed heap-buffer-overflow in -String.prototype.replace(). - - - - - -Bugfix: -fixed heap-buffer-overflow in -String.prototype.lastIndexOf(). - - - - - -Bugfix: -fixed regexp literals parsing with escaped backslash -and backslash in square brackets. - - - - - -Bugfix: -fixed regexp literals with lone closing brackets. - - - - - -Bugfix: -fixed uninitialized-memory-access in -Object.defineProperties(). - - - - - -Bugfix: -fixed processing the “*” quantifier for -String.prototype.replace(). - - - - - -Bugfix: -fixed -Array.prototype.slice() -for UTF8-invalid byte strings. - - - - - -Bugfix: -fixed -String.prototype.split() -for UTF8-invalid byte strings. - - - - - -Bugfix: -fixed handling of empty block statements. - - - - - - -
- - -
- - -Release Date: -16 April 2019 - - - -Core: - - - - -Feature: -added arrow functions support. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. - - - - - -Feature: -added -Object.getOwnPropertyNames(). -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -added -Object.getOwnPropertyDescriptors(). -Thanks to Artem S. Povalyukhin. - - - - - -Feature: -making __proto__ accessor descriptor -of Object instances mutable. - - - - - -Feature: -added shebang support in CLI. - - - - - -Feature: -added support for module mode execution in CLI. -In module mode global, this is unavailable. - - - - - -Bugfix: -fixed editline detection. - - - - - -Bugfix: -fixed -Function.prototype.bind(). -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Bugfix: -fixed checking of duplication of parameters for functions. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Bugfix: -fixed function declaration with the same name as a variable. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Improvement: -code related to parsing of objects, variables and -functions is refactored. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Improvement: -large-value output improved in console.log(). - - - - - -Improvement: -string output improved in console.log() -in a compliant way (without escaping and quotes). - - - - - -Improvement: -using ES6 version of -ToInt32(), -ToUint32(), -ToLength(). - - - - - - -
- - -
- - -Release Date: -26 March 2019 - - - -nginx modules: - - - - -Feature: -added the js_path directive for -http and -stream. - - - - - -Change: -returning undefined value instead of empty strings -for absent properties in the following objects: -r.args{}, -r.headersIn{}, -r.headersOut{}, -r.variables{}, -s.variables{}. - - - - - -Change: -returning undefined value instead of throwing an exception for -r.requestBody -when request body is unavailable. - - - - - -Bugfix: -fixed crash while iterating over -r.args{} -when a value is absent in a key-value pair. - - - - - - - -Core: - - - - -Feature: -added initial ES6 modules support. -Default import and default export statements are supported. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Feature: -added -Object.prototype.propertyIsEnumerable(). - - - - - -Feature: -reporting file name and function name in disassembler output. - - - - - -Bugfix: -fixed function redeclarations in interactive shell. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Bugfix: -fixed RegExp literals parsing. - - - - - -Bugfix: -fixed setting length of UTF8 string in -fs.readFileSync(). - - - - - -Bugfix: -fixed -nxt_file_dirname() for paths with no dir component. - - - - - - -
- - -
- - -Release Date: -26 February 2019 - - - -nginx modules: - - - - -Change: -properties of HTTP request deprecated in 0.2.2 -are removed. - - - - - -Feature: -added support for delete operation in -r.headersOut{}. - - - - - -Feature: -added support for setting nginx variables. - - - - - -Bugfix: -fixed -r.subrequest() -for empty body value. - - - - - -Improvement: -setting special response headers in -r.headersOut{}. - - - - - - - -Core: - - - - -Feature: -added labels support. - - - - - -Feature: -added -setImmediate() method. - - - - - -Feature: -added support for shorthand property names for Object literals. - - - - - -Bugfix: -fixed -Function.prototype.bind(). - - - - - -Bugfix: -fixed parsing of string literals containing newline characters. - - - - - -Bugfix: -fixed line number in reporting variable reference errors. - - - - - -Bugfix: -fixed creation of long UTF8 strings. - - - - - -Bugfix: -fixed -setting special response headers in -String.prototype.split() -for Unicode strings. - - - - - -Bugfix: -fixed heap-buffer-overflow in -String.prototype.split(). - - - - - -Bugfix: -fixed -Array.prototype.fill(). -Thanks to Artem S. Povalyukhin. - - - - - -Improvement: -code related to function invocation is refactored. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Improvement: -code related to variables is refactored. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Improvement: parser is refactored. -Thanks to 洪志道 (Hong Zhi Dao). - - - - - -Improvement: -reporting filenames in exceptions. - - - - - - -
- - -
- - -Release Date: -25 December 2018 - - - -Core: - - - - -Feature: -rest parameters syntax (destructuring is not supported). -Thanks to Alexander Pyshchev. - - - - - -Feature: -added -Object.entries() -method. - - - - - -Feature: -added -Object.values() -method. - - - - - -Improvement: -code generator refactored and simplified. - - - - - -Bugfix: -fixed automatic semicolon insertion. - - - - - -Bugfix: -fixed assignment expression from compound assignment. - - - - - -Bugfix: -fixed comparison of Byte and UTF8 strings. - - - - - -Bugfix: -fixed type of iteration variable in for-in with array values. - - - - - -Bugfix: -fixed building on platforms without librt. - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -27 November 2018 - - - -Core: - - - - -Feature: -making built-in prototypes mutable. - - - - - -Feature: -making global object mutable. - - - - - -Feature: -console.time() -and -console.timeEnd() -methods. - - - - - -Feature: -allowing variables and functions to be redeclared. - - - - - -Feature: -extending Object.defineProperty() spec conformance. - - - - - -Feature: -introduced quiet mode for CLI to handle simple expressions from stdin. - - - - - -Feature: -introduced compact form of backtraces to handle stack overflows. - - - - - -Improvement: -improved wording for various exceptions. - - - - - -Bugfix: -fixed closure values handling. - - - - - -Bugfix: -fixed equality operator for various value types. - - - - - -Bugfix: -fixed handling of this keyword in various scopes. - - - - - -Bugfix: -fixed handling non-object values in -Object.keys(). - - - - - -Bugfix: -fixed parsing of throw statement inside -if statement. - - - - - -Bugfix: -fixed parsing of newline after throw statement. - - - - - -Bugfix: -fixed parsing of statements in if statement without newline. - - - - - -Bugfix: -fixed size uint32_t overflow -in njs_array_expand(). - - - - - -Bugfix: -fixed typeof operator -for object_value type. - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -30 October 2018 - - - -nginx modules: - - - - -Bugfix: -fixed counting pending events in stream module. - - - - - -Bugfix: -fixed -s.off() in stream module. - - - - - -Bugfix: -fixed processing of data chunks in -js_filter in stream module. - - - - - -Bugfix: -fixed http -status and -contentType -getter in http module. - - - - - -Bugfix: -fixed http response and parent getters in http module. - - - - - - - -Core: - - - - -Feature: -arguments object support. - - - - - -Feature: -non-integer fractions support. - - - - - -Improvement: -handling non-array values in -Array.prototype.slice(). - - - - - -Bugfix: -fixed -Array.prototype.length setter - - - - - -Bugfix: -fixed -njs_array_alloc() for length > 2**31. - - - - - -Bugfix: -handling int overflow in -njs_array_alloc() on 32bit archs. - - - - - -Bugfix: -fixed code size mismatch error message. - - - - - -Bugfix: -fixed delete operator in a loop. - - - - - -Bugfix: -fixed -Object.getOwnPropertyDescriptor() -for complex object (inherited from -Array and -string values). - - - - - -Bugfix: -fixed -Object.prototype.hasOwnProperty() -for non-object properties - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -18 September 2018 - - - -nginx modules: - - - - -Change: -stream module handlers refactored. - - - -New methods and properties: -s.on(), -s.off(), -s.allow(), -s.done(), -s.decline(), -s.deny(). - - - -Removed properties of the -Stream object: -s.OK, -s.ABORT, -s.AGAIN, -s.DECLINED, -s.ERROR -(replaced with -s.allow(), -s.done(), -s.deny()). - - - -s.buffer -(for reading replaced with data argument of -the corresponding callback, for writing use -s.send()). - - - -s.fromUpstream -(replaced with a callback for a corresponding event). - - - -s.eof -(replaced with -flags.last). - - - - - - - - -Core: - - - - -Feature: -added -Function.prototype.length. - - - - - -Feature: -introduced sandboxing mode. - - - - - -Improvement: -added exception strings where appropriate. - - - - - -Improvement: -improved wording for primitive type conversion exception. - - - - - -Bugfix: -throwing TypeError -for attempts to change frozen properties. - - - - - -Bugfix: -fixed -Object.defineProperty() for existing properties. - - - - - -Bugfix: -respecting the enumerable attribute while iterating by for in. - - - - - -Bugfix: -respecting writable attribute for property handlers. - - - - - -Bugfix: -fixed exception handling in arguments of a function. - - - - - -Bugfix: -fixed -Object.prototype.toString -for different value types. - - - - - -Bugfix: -fixed -Object() -constructor for object types arguments. - - - - - -Bugfix: -fixed comparison of objects and strings. - - - - - -Bugfix: -fixed -String.slice() -for undefined arguments. - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -31 July 2018 - - - -nginx modules: - - - - -Bugfix: -making a subrequest from a -Reply -object caused a segmentation fault. - - - - - -Bugfix: -getting the parent property of the main -HTTP Request -object caused a segmentation fault. - - - - - - - -Core: - - - - -Feature: -added the pretty string representation for values. - - - - - -Feature: -correctly printing floating point numbers. - - - - - -Feature: -correctly parsing floating point numbers. - - - - - -Feature: -String.bytesFrom() method -(decoding hex, -base64, -base64url into a byte string). - - - - - -Feature: -String.padStart() and -String.padEnd() -methods. - - - - - -Feature: -added support of binary literals. - - - - - -Improvement: -added information about illegal token in number parsing. - - - - - -Improvement: -allowed uppercased O in octal literal values. - - - - - -Improvement: -added support for multiple arguments in console.log(). - - - - - -Bugfix: -fixed applying call() to methods of external values. - - - - - -Bugfix: -fixed addition operator applied to an object. - - - - - -Bugfix: -fixed exception handling in -njs_vm_value_to_ext_string(). - - - - - -Bugfix: -fixed -Number() with boolean, null and undefined arguments. - - - - - -Bugfix: -fixed error handling of setting non-numeric Array.length. - - - - - -Bugfix: -fixed autocompletion for global objects. - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -19 June 2018 - - - -nginx modules: - - - - -Change: -merged HTTP Response and Reply -into HTTP Request. -New members of Request: - - - - - -req.status (res.status) - - - - - -req.parent (reply.parent) - - - - - -req.requestBody (req.body) - - - - - -req.responseBody (reply.body) - - - - - -req.headersIn (req.headers) - - - - - -req.headersOut (res.headers) - - - - - -req.sendHeader() (res.sendHeader()) - - - - - -req.send() (res.send()) - - - - - -req.finish() (res.finish()) - - - - - -req.return() (res.return()) - - - - -Deprecated members of Request: - - - - - -req.body (use req.requestBody -or req.responseBody) - - - - - -req.headers (use req.headersIn -or req.headersOut) - - - - - -req.response - - - - -Deprecated members of Response: - - - - - -res.contentLength (use -req.headersOut['Content-Length']) - - - - - -res.contentType (use req.headersOut['Content-Type']) - - - - -The deprecated properties will be removed in -next releases. - - - - - -Feature: -HTTP internalRedirect() -method. - - - - - - - -Core: - - - - -Bugfix: -fixed heap-buffer-overflow in -crypto.createHmac(). - - - - - - -
- - -
- - -Release Date: -31 May 2018 - - - -nginx modules: - - - - -Feature: -HTTP request body getter. - - - - - -Improvement: -moved njs vm to the main configuration. - - - - - -Improvement: -improved logging for - and - directives. - - - - - -Improvement: -setting status code to 500 by default in the - handler - - - - - -Improvement: -added the debug for the returned status code in - handler - - - - - -Bugfix: fixed error logging in -. - - - - - - - -Core: - - - - -Feature: -added array length setter. - - - - - -Improvement: -public header cleanup. njscript.h is renamed to -njs.h. - - - - - -Bugfix: -fixed crypto update() method after -digest() is called. - - - - - -Bugfix: -fixed crypto.createHmac() for keys with size <= alg size -and > 64. - - - - - -Bugfix: -fixed JSON.stringify() for arrays with empty cells. - - - - - -Bugfix: -fixed exception type for unsupported types in -JSON.stringify(). - - - - - -Bugfix: -fixed handling of undefined arguments of functions. - - - - - -Bugfix: -fixed handling of missing arg of -Object.getOwnPropertyDescriptor(). - - - - - -Bugfix: -fixed handling of properties in -Object.getOwnPropertyDescriptor(). - - - - - -Bugfix: -fixed the writeable flag of Array.length property. - - - - - -Bugfix: fixed return value type of clearTimeout(). - - - - - -Bugfix: -fixed njs_vm_external_bind(). - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -03 April 2018 - - - - - - - -Feature: -reporting njs version by CLI. - - - - - -Feature: -textual description for type converting exceptions. - - - - -Feature: -setTimeout() and -clearTimeout() methods. - - - - -Feature: -Byte string to -hex, -base64, -base64url encodings. - - - - - -Feature: -Node.js style -Crypto methods. - - - - - -Feature: -HTTP and stream -warn() and -error() methods. - - - - - -Feature: -HTTP subrequest() method. - - - - - -Feature: -HTTP return() method. - - - - - -Bugfix: -miscellaneous bugs have been fixed in the core and -interactive shell. - - - - - - -
- -
- - -Release Date: -20 November 2017 - - - - - - - -Feature: -Error, -EvalError, -InternalError, -RangeError, -ReferenceError, -SyntaxError, -TypeError, -URIError objects. - - - - - -Feature: -octal literals support. - - - - - -Feature: -Node.js style -File system access methods: -fs.readFile(), -fs.readFileSync(), -fs.appendFile(), -fs.appendFileSync(), -fs.writeFile(), -fs.writeFileSync(). - - - - - -Feature: -nginx modules print backtrace on exception. - - - - - -Bugfix: -miscellaneous bugs have been fixed. - - - - - - -
- - -
- - -Release Date: -09 October 2017 - - - - - - - -Feature: -JSON object. - - - - - -Feature: -object level completions in interactive shell. - - - - - -Feature: -various configure improvements. - - - - - -Bugfix: -miscellaneous bugs have been fixed in the core and -interactive shell. - - - - - - -
- - -
- - -Release Date: -31 August 2017 - - - - - - - -Feature: -console.log() and -console.help() -methods in interactive shell. - - - - - -Feature: -interactive shell prints backtrace on exception. - - - - - -Feature: -interactive shell by default -if libedit is available. - - - - - -Bugfix: -processing of large files from -stdin in command line mode. - - - - - -Bugfix: -improved editline detection. - - - - - - -
- - -
- - -Release Date: -08 August 2017 - - - - - - - -Feature: -Interactive shell. - - - - - -Bugfix: -in Object.isSealed(). - - - - - - -
- - -
- - -Release Date: -27 June 2017 - - - - - - - -Feature: -Object.keys(), -Object.prototype.hasOwnProperty() -methods. - - - - - -Feature: -Object.defineProperty(), -Object.defineProperties(), -Object.getOwnPropertyDescriptor() -methods. - - - - - -Feature: -Object.getPrototypeOf(), -Object.prototype.isPrototypeOf() -methods. - - - - - -Feature: -Object.preventExtensions(), -Object.isExtensible(), -Object.freeze(), -Object.isFrozen(), -Object.seal(), -Object.isSealed() -methods. - - - - - -Feature: -scientific notation (3.35e10) literals support. - - - - - -Feature: -hexadecimal (0x1123) literals support. - - - - - -Bugfix: -processing of large array indexes. - - - - - -Bugfix: -in parseInt() and -Date.parse(). - - - - - - -
- - -
- - -Release Date: -04 April 2017 - - - - - - - -Feature: -nested functions and function closures. - - - - - -Feature: -Array.of(), -Array.prototype.fill(), -Array.prototype.find(), -Array.prototype.findIndex() -methods. - - - - - -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. - - - - - - -
- - -
- - -Release Date: -01 February 2017 - - - - - - - -Bugfix: -global variables were not initialized when njs was used -in nginx. - - - - - - -
- - -
- - -Release Date: -24 January 2017 - - - - - - - -Change: -the strict mode is enforced, -variables must be explicitly declared. - - - - - - -Feature: -for and -for-in loops support variable declaration. - - - - - -Bugfix: -global and function scopes have been fixed. - - - - - -Bugfix: -now for-in loop does not discard the last value -of property variable. - - - - - -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. - - - - - - -
- - -
- - -Release Date: -27 December 2016 - - - - - - - -Change: -the directive -has been disabled at server and location levels. - - - - - -Feature: -exponentiation operators. - - - - - -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. - - - - - - -
- - -
- - -Release Date: -13 December 2016 - - - - - - - -Change: -the directive -has been disabled at server and location levels. - - - - - -Feature: -ES6 Math methods. - - - - - -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. - - - - - - -
- -
diff --git a/xml/en/docs/njs/cli.xml b/xml/en/docs/njs/cli.xml deleted file mode 100644 --- a/xml/en/docs/njs/cli.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - -
- -
- -njs scripts development and debugging can be performed -from the command-line. -The command-line utility is available after the installation of -the Linux package -or after building from the -sources. -Compared to njs running inside nginx, -nginx objects -(HTTP and -Stream) -are not available in the utility. - -$ echo "2**3" | njs -q -8 - -$ njs ->> globalThis -global { - njs: njs { - version: '0.3.9' - }, - global: [Circular], - process: process { - argv: [ - '/usr/bin/njs' - ], - env: { - PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - HOSTNAME: 'f777c149d4f8', - TERM: 'xterm', - NGINX_VERSION: '1.17.9', - NJS_VERSION: '0.3.9', - PKG_RELEASE: '1~buster', - HOME: '/root' - } - }, - console: { - log: [Function: native], - dump: [Function: native], - time: [Function: native], - timeEnd: [Function: native] - }, - print: [Function: native] -} ->> - - - -
- -
diff --git a/xml/en/docs/njs/compatibility.xml b/xml/en/docs/njs/compatibility.xml deleted file mode 100644 --- a/xml/en/docs/njs/compatibility.xml +++ /dev/null @@ -1,1266 +0,0 @@ - - - - - - -
- -
- - -njs is created in compliance with -ECMAScript 5.1 -(strict mode) with some -ECMAScript 6 -and later extensions. -The compliance is still evolving. - - - -Definitions of njs specific properties and methods -not compliant with ECMAScript can be found in -Reference. -Definitions of njs properties and methods -compliant with ECMAScript can be found in -ECMAScript -specification. - - -
- - -
- - - - - -Boolean values, numbers, strings, objects, arrays, -functions, function constructors -(0.3.6), -and regular expressions - - - -ES5.1 operators, ES7 exponentiation operators - - - -ES5.1 statements: -break, -catch, -continue, -do while, -else, -finally, -for, -for in, -if, -return, -switch, -throw, -try, -var, -while, -labeled statements (0.2.8) - - - -ES6 statements: -let (0.6.0), -const (0.6.0), -async (0.7.0), -await (0.7.0) - - - -Math properties: - - - -ES6: -E, -LN10, -LN2, -LOG10E, -LOG2E, -PI, -SQRT1_2, -SQRT2 - - - - - -Math methods: - - - -ES6: -abs, -acos, -acosh, -asin, -asinh, -atan, -atan2, -atanh, -cbrt, -ceil, -clz32, -cos, -cosh, -exp, -expm1, -floor, -fround, -hypot, -imul, -log, -log10, -log1p, -log2, -max, -min, -pow, -random, -round, -sign, -sin, -sinh, -sqrt, -tan, -tanh, -trunc - - - - - -Number properties: - - - -ES6: -EPSILON, -MAX_SAFE_INTEGER, -MAX_VALUE, -MIN_SAFE_INTEGER, -MIN_VALUE, -NEGATIVE_INFINITY, -NaN, -POSITIVE_INFINITY - - - - - - -Number methods: - - - -ES6: -isFinite, -isInteger, -isNaN, -isSafeInteger, -parseFloat, -parseInt - - - - - - -Number prototype methods: - - - -ES6: -toExponential -(0.3.6), -toFixed -(0.3.6), -toPrecision -(0.3.6) - - - - - - -String methods: - - - -ES5.1: -fromCharCode - - - -ES6: -fromCodePoint - - - - - - -String prototype methods: - - - -ES5.1: -charAt, -concat, -indexOf, -lastIndexOf, -match, -replace, -search, -slice, -split, -substr, -substring, -toLowerCase, -trim, -toUpperCase - - - -ES6: -codePointAt, -endsWith, -includes, -repeat, -startsWith - - - -ES8: -padEnd, -padStart - - - -ES9: -trimEnd -(0.3.4), -trimStart -(0.3.4) - - - -ES12: -replaceAll -(0.7.10) - - - - - - - -Object methods: - - -ES5.1: -create (support without properties list), -defineProperties (accessor descriptors support -since 0.3.3), -defineProperty (accessor descriptors support -since 0.3.3), -freeze, -getOwnPropertyDescriptor, -getOwnPropertyDescriptors -(0.3.1), -getOwnPropertyNames -(0.3.1), -getPrototypeOf, -isExtensible, -isFrozen, -isSealed, -keys, -preventExtensions, -seal - - - -ES6: -assign -(0.3.7) - - - -ES8: -entries -(0.2.7), -values -(0.2.7) - - - - - - -Object prototype methods: - - -ES5.1: -hasOwnProperty, -isPrototypeOf, -(0.3.0), -propertyIsEnumerable, -toString, -valueOf - - - -ES6: -is -(0.3.8), -setPrototypeOf -(0.3.8) - - - - - - -Array methods: - - -ES5.1: -isArray - - - -ES6: -of - - - -ES13: -from -(0.8.0), - - - - - - -Array prototype methods: - - -ES5.1: -concat, -every, -filter, -forEach, -indexOf, -join, -lastIndexOf, -map, -pop, -push, -reduce, -reduceRight, -reverse, -shift, -slice, -some, -sort, -splice, -unshift - - - -ES6: -copyWithin -(0.3.7), -fill, -find, -findIndex - - - -ES7: includes - - - -ES13: -toReversed -(0.8.0), -toSorted -(0.8.0), -toSpliced -(0.8.0) - - - - - - -ArrayBuffer methods -(0.3.8): - - -ES6: -isView - - - - - - -ArrayBuffer prototype methods -(0.3.8): - - -ES6: -slice - - - - - - -Typed-array constructors -(0.3.8): - - -ES6: -Int8Array, -Uint8Array, -Uint8ClampedArray, -Int16Array, -Uint16Array, -Int32Array, -Uint32Array, -Float32Array, -Float64Array - - - - - - -Typed-array prototype methods -(0.3.8): - - -ES6: -copyWithin, -every -(0.4.4), -fill, -filter -(0.4.4), -find -(0.4.4), -findIndex -(0.4.4), -forEach -(0.4.4), -includes -(0.4.4), -indexOf -(0.4.4), -join, -lastIndexOf -(0.4.4), -map -(0.4.4), -reduce -(0.4.4), -reduceRight -(0.4.4), -reverse -(0.4.4), -set, -slice, -some -(0.4.4), -sort -(0.4.2), -subarray, -toString - - - -ES13: -toReversed -(0.8.0) -toSorted -(0.8.0) - - - - - - - -Buffer methods -(0.4.4): - - -alloc, -allocUnsafe, -byteLength, -compare, -concat, -from, -isBuffer, -isEncoding - - - - - - -Buffer prototype methods: -(0.4.4): - - -compare, -copy, -equals, -fill, -includes, -indexOf, -lastIndexOf, -readIntBE, -readInt8, -readInt16BE, -readInt32BE, -readIntLE, -readInt8, -readInt16LE, -readInt32LE, -readUIntBE, -readUInt8, -readUInt16BE, -readUInt32BE, -readUIntLE, -readUInt8, -readUInt16LE, -readUInt32LE, -readDoubleBE, -readDoubleLE, -readFloatBE, -readFloatLE, -subarray, -slice, -swap16, -swap32, -swap64, -toJSON, -toString, -write, -writeIntBE, -writeInt8, -writeInt16BE, -writeInt32BE, -writeIntLE, -writeInt8, -writeInt16LE, -writeInt32LE, -writeUIntBE, -writeUInt8, -writeUInt16BE, -writeUInt32BE, -writeUIntLE, -writeUInt8, -writeUInt16LE, -writeUInt32LE, -writeDoubleBE, -writeDoubleLE, -writeFloatBE, -writeFloatLE - - - - - - -Promise methods -(0.3.8): - - -ES6: -any -(0.6.2), - all -(0.6.2), - allSettled -(0.6.2), -reject, -resolve, -race (0.6.2) - - - - - - -Promise prototype methods -(0.3.8): - - -ES6: -catch, -finally, -then - - - - - - -Function prototype methods: - - - -ES5.1: -apply, -bind, -call - - - - - - -RegExp prototype accessor properties: - - - -flags (0.6.0), -global, -ignoreCase, -multiline, -source, -sticky (0.6.0) - - - - - - -RegExp prototype methods: - - - -[@@replace] -(0.4.2), -[@@split] -(0.6.0) - - - -ES5.1: -exec, -test, -toString - - - - - - -RegExp instance properties: - - - -lastIndex - - - - - - -RegExp -ES9 named capture groups (0.3.2) - - - -DataView prototype methods -(0.4.4): - - - -ES6: -getFloat32, -getFloat64, -getInt16, -getInt32, -getInt8, -getUint16, -getUint32, -getUint8, -setFloat32, -setFloat64, -setInt16, -setInt32, -setInt8, -setUint16, -setUint32, -setUint8 - - - - - - -Date methods: - - - -ES5.1: -now, -parse, -UTC - - - - - - -Date prototype methods: - - - -ES5.1: -getDate, -getDay, -getFullYear, -getHours, -getMilliseconds, -getMinutes, -getMonth, -getSeconds, -getTime, -getTimezoneOffset, -getUTCDate, -getUTCDay, -getUTCFullYear, -getUTCHours, -getUTCMilliseconds, -getUTCMinutes, -getUTCMonth, -getUTCSeconds, -toDateString, -toISOString, -toLocaleDateString, -toLocaleString, -toLocaleTimeString, -toTimeString, -toUTCString, -setDate, -setFullYear, -setHours, -setMinutes, -setMilliseconds, -setMonth, -setSeconds, -setTime, -setUTCDate, -setUTCFullYear, -setUTCHours, -setUTCMilliseconds, -setUTCMinutes, -setUTCMonth, -setUTCSeconds - - - - - - -JSON methods: - - - -ES5.1: -parse, -stringify - - - - - - -Symbol methods -(0.7.6): - - - -for, -keyfor - - - - - - -ES5.1 arguments object -(0.2.5) - - - -ES6 rest parameters syntax (without destructuring support) -(0.2.7) - - - -ES5.1 global functions: -decodeURI, -decodeURIComponent, -encodeURI, -encodeURIComponent, -isFinite, -isNaN, -parseFloat, -parseInt - - - -Global functions (0.7.6): -atob, -btoa - - - -Error objects: -Error, -EvalError, -InternalError, -RangeError, -ReferenceError, -SyntaxError, -TypeError, -URIError - - - -clearTimeout -and -setTimeout -functions -(0.2.0) - - - -File system methods: -fs.accessSync -(0.3.9), -fs.appendFileSync, -fs.closeSync, -fs.existsSync -(0.8.2), -fs.FileHandle -(0.7.7), -fs.fstatSync -(0.7.7), -fs.lstatSync -(0.7.1), -fs.mkdirSync -(0.4.2), -fs.openSync -(0.7.7), -fs.promises.open -(0.7.7), -fs.readdirSync -(0.4.2), -fs.readFileSync, -fs.readSync -(0.7.7), -fs.realpathSync -(0.3.9), -fs.renameSync -(0.3.4), -fs.rmdirSync -(0.4.2), -fs.symlinkSync -(0.3.9), -fs.unlinkSync -(0.3.9), -fs.writeFileSync -fs.writeSync -(0.7.7) - - - -fs.promises API (0.3.9), -asynchronous version of file system methods. - - - -Crypto methods -(0.2.0): -crypto.createHash, -crypto.createHmac - - - -Query String -methods -(0.4.3): -querystring.decode, -querystring.encode, -querystring.escape, -querystring.parse, -querystring.stringify, -querystring.unescape - - - -TextDecoder -methods -(0.4.3): -encoding, -fatal, -ignoreBOM, -decode - - - -TextEncoder -methods -(0.4.3): -encode, -encodeInto - - - -XML -methods -(0.7.10): -parse, -xml.c14n, -xml.exclusiveC14n - - - -zlib -methods -(0.7.12): -deflateRawSync, -deflateSync, -inflateRawSync -inflateSync - - - -ES6 modules support: -default export and -default import -statements -(0.3.0) - - - -ES6 arrow functions -(0.3.1) - - - -Template literals: -multiline strings, expression interpolation, nesting templates -(0.3.2) - - - -Global objects -(0.3.3): - - - -console -(0.8.2): -error, -info, -log, -time, -timeEnd, -warn - - - -crypto -(0.7.0): -getRandomValues, -subtle.encrypt, -subtle.decrypt, -subtle.deriveBits, -subtle.deriveKey, -subtle.digest -subtle.exportKey -(0.7.10), -subtle.generateKey -(0.7.10), -subtle.importKey, -subtle.sign, -subtle.verify - - - -globalThis alias -(0.3.8), - - - -njs: -version, -version_number -(0.7.4), -dump, -memoryStats -(0.7.8), -on -(0.5.2) - - - -process: -argv, -env, -pid, -ppid - - - - - - -nginx object methods: - - - -HTTP Request: -r.done -(0.5.2), -r.error, -r.finish, -r.internalRedirect, -r.log, -r.return -(0.5.0), -r.send -(0.5.0), -r.sendBuffer -(0.5.2), -r.sendHeader, -r.setReturnValue -(0.7.0), -r.subrequest, -r.warn - - - -Stream Session: -s.allow -(0.2.4), -s.decline -(0.2.4), -s.deny -(0.2.4), -s.done -(0.2.4), -s.error, -s.log, -s.off -(0.2.4), -s.on -(0.2.4), -s.send -(0.2.4), -s.sendDownstream -(0.7.8), -s.sendUpstream -(0.7.8), -s.setReturnValue -(0.7.0), -s.warn - - - -Headers -(0.5.1): -append, -delete, -get, -getAll, -forEach, -has, -set - - - -Request -(0.7.10): -arrayBuffer, -headers, -json, -text - - - -Response -(0.5.1): -arrayBuffer, -headers, -json, -text - - - -ngx -(0.5.0): -fetch -(0.5.1), -log - - - -ngx.shared -(0.8.0): -add, -clear, -delete, -freeSpace, -get, -has, -incr, -items, -keys, -pop, -replace, -set, -size - - - - - - -nginx object properties: - - - -HTTP Request: -r.args, -r.headersIn, -r.headersOut, -r.httpVersion, -r.internal, -r.method, -r.parent, -r.rawHeadersIn -(0.4.1), -r.rawHeadersOut -(0.4.1), -r.rawVariables -(0.5.0), -r.remoteAddress, -r.requestBuffer -(0.5.0), -r.requestText, -r.responseBuffer -(0.5.0), -r.responseText -(0.5.0), -r.status, -r.uri, -r.variables -(0.2.8) - - - -Stream Session: -s.remoteAddress, -s.rawVariables -(0.5.0), -s.status -(0.5.2), -s.variables -(0.2.8) - - - -Periodic Session -(0.8.1): -PeriodicSession.rawVariables, -PeriodicSession.variables - - - - -Request -(0.7.10): -bodyUsed, -cache, -credentials, -method, -mode, -url - - - -Response -(0.5.1): -bodyUsed, -ok, -redirected, -status, -statusText, -type, -url - - - -ngx -(0.5.0): -build -(0.8.0), -conf_file_path -(0.8.0), -conf_prefix -(0.7.8), -error_log_path -(0.8.0), -prefix -(0.8.0), -version -(0.8.0), -version_number -(0.8.0), -worker_id -(0.8.0) - - - -ngx.shared -(0.8.0): -capacity, -name, -type - - - - - - - - -
- -
diff --git a/xml/en/docs/njs/examples.xml b/xml/en/docs/njs/examples.xml deleted file mode 100644 --- a/xml/en/docs/njs/examples.xml +++ /dev/null @@ -1,332 +0,0 @@ - - - - - - -
- -
- - -The examples work since -0.4.0. - - -
- - -
- - -nginx.conf: - -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} - - - - -http.js: - -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; - - - -
- - -
- - -
- - -nginx.conf: - -js_import http.js; - -js_set $jwt http.jwt; - - - - -http.js: - -function generate_hs256_jwt(claims, key, valid) { - var header = { typ: "JWT", alg: "HS256" }; - var claims = Object.assign(claims, {exp: Math.floor(Date.now()/1000) + valid}); - - var s = [header, claims].map(JSON.stringify) - .map(v=>v.toString('base64url')) - .join('.'); - - var h = require('crypto').createHmac('sha256', key); - - return s + '.' + h.update(s).digest('base64url'); -} - -function jwt(r) { - var claims = { - iss: "nginx", - sub: "alice", - foo: 123, - bar: "qq", - zyx: false - }; - - return generate_hs256_jwt(claims, 'foo', 600); -} - -export default {jwt}; - - - -
- - - - - -
- - -In the following example, the sub field -is extracted from JWT payload. -The JWT token is taken from the
Authorization
header. -
- - -nginx.conf: - -js_import http.js; - -js_set $jwt_payload_sub http.jwt_payload_sub; - -server { - #... - - location /jwt { - return 200 $jwt_payload_sub; - } -} - - - - -http.js: - -function jwt(data) { - var parts = data.split('.').slice(0,2) - .map(v=>Buffer.from(v, 'base64url').toString()) - .map(JSON.parse); - return { headers:parts[0], payload: parts[1] }; -} - -function jwt_payload_sub(r) { - return jwt(r.headersIn.Authorization.slice(7)).payload.sub; - // when the token is provided as the "myjwt" argument - // return jwt(r.args.myjwt).payload.sub; -} - -export default {jwt_payload_sub}; - - - -
- -
- - -
- - -
- - -nginx.conf: - -js_import http.js; - -location /start { - js_content http.content; -} - -location /foo { - proxy_pass http://backend1; -} - -location /bar { - proxy_pass http://backend2; -} - - - - -http.js: - -function content(r) { - var n = 0; - - function done(res) { - if (n++ == 0) { - r.return(res.status, res.responseBody); - } - } - - r.subrequest('/foo', r.variables.args, done); - r.subrequest('/bar', r.variables.args, done); -} - -export default {content}; - - - -
- - -
- - -nginx.conf: - -js_import http.js; - -location /start { - js_content http.content; -} - -location /auth { - proxy_pass http://auth_backend; -} - -location /backend { - proxy_pass http://backend; -} - - - - -http.js: - -async function content(r) { - try { - let reply = await r.subrequest('/auth'); - let response = JSON.parse(reply.responseBody); - let token = response['token']; - - if (!token) { - throw new Error("token is not available"); - } - - let backend_reply = await r.subrequest('/backend', `token=${token}`); - r.return(backend_reply.status, backend_reply.responseBody); - - } catch (e) { - r.error(e); - r.return(500); - } -} - -export default {content}; - - - -
- -
- - -
- - -
- - -nginx.conf: - -js_import http.js; - -location /redirect { - js_content http.redirect; -} - -location @named { - return 200 named; -} - - - - -http.js: - -function redirect(r) { - r.internalRedirect('@named'); -} - -export default {redirect}; - - - -
- -
- -
diff --git a/xml/en/docs/njs/index.xml b/xml/en/docs/njs/index.xml deleted file mode 100644 --- a/xml/en/docs/njs/index.xml +++ /dev/null @@ -1,233 +0,0 @@ - - - - - - -
- -
- - -njs is a subset of the JavaScript language that allows -extending nginx functionality. -njs is created in compliance with -ECMAScript 5.1 -(strict mode) with some -ECMAScript 6 -and later extensions. -The compliance is still evolving. - - -
- - - - - -
- - - - - -Complex access control and security checks in njs -before a request reaches an upstream server - - - -Manipulating response headers - - - -Writing flexible asynchronous content handlers and filters - - - -See examples and -blog posts -for more njs use cases. - - -
- - -
- - -To use njs in nginx: - - - - -install njs scripting language - - - - - -create an njs script file, for example, http.js. -See Reference -for the list of njs properties and methods. - -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; - - - - - - - -in the nginx.conf file, enable -ngx_http_js_module module -and specify the -js_import -directive -with the http.js script file: - -load_module modules/ngx_http_js_module.so; - -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} - - - - - -There is also a standalone command line utility -that can be used independently of nginx for njs development and debugging. - - -
- - -
- - - - - -FreeBSD / amd64; - - - -Linux / x86, amd64, arm64, ppc64el; - - - -Solaris 11 / amd64; - - - -macOS / x86_64; - - - - - -
- - -
- - - -
- -
diff --git a/xml/en/docs/njs/install.xml b/xml/en/docs/njs/install.xml deleted file mode 100644 --- a/xml/en/docs/njs/install.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - -
- -
- - -For Linux, njs modules -packages can be used: - - - -nginx-module-njs — njs -dynamic modules - - - -nginx-module-njs-dbg — debug symbols for the -nginx-module-njs package - - - - - - -After package installation, njs dynamic modules need to be loaded with the -load_module -directive: - -load_module modules/ngx_http_js_module.so; - -or - -load_module modules/ngx_stream_js_module.so; - - - -
- - -
- - -The repository -with njs sources can be cloned with the following command: -(requires Mercurial client): - -hg clone http://hg.nginx.org/njs - -Then the modules should be compiled from -nginx root directory using the ---add-module configuration parameter: - -./configure --add-module=path-to-njs/nginx - -The modules can also be built as -dynamic: - -./configure --add-dynamic-module=path-to-njs/nginx - - - - -To build only njs command-line utility, run -./configure and make njs commands -from njs root directory. -The utility is available as ./build/njs. - - -
- -
diff --git a/xml/en/docs/njs/node_modules.xml b/xml/en/docs/njs/node_modules.xml deleted file mode 100644 --- a/xml/en/docs/njs/node_modules.xml +++ /dev/null @@ -1,543 +0,0 @@ - - - - - - -
- -
- - -Often, a developer wants to use 3rd-party code, -usually available as a library of some kind. -In the JavaScript world, the concept of a module is relatively new, -so there was no standard until recently. -Many platforms (browsers) still don't support modules, which makes code -reuse harder. -This article describes ways to reuse -Node.js code in njs. - - - -Examples in this article use features that appeared in -njs -0.3.8 - - - -There is a number of issues -that may arise when 3rd-party code is added to njs: - - - - -Multiple files that reference each other and their dependencies - - - -Platform-specific APIs - - - -Modern standard language constructions - - - - - - -The good news is that such problems are not something new or specific to njs. -JavaScript developers face them daily -when trying to support multiple disparate platforms -with very different properties. -There are instruments designed to resolve the above-mentioned issues. - - - - -Multiple files that reference each other, and their dependencies - -This can be solved by merging all the interdependent code into a single file. -Tools like -browserify or -webpack -accept an entire project and produce a single file containing -your code and all the dependencies. - - - - -Platform-specific APIs - -You can use multiple libraries that implement such APIs -in a platform-agnostic manner (at the expense of performance, though). -Particular features can also be implemented using the -polyfill approach. - - - - -Modern standard language constructions - -Such code can be transpiled: -this means performing a number of transformations -that rewrite newer language features in accordance with an older standard. -For example, babel project -can be used to this purpose. - - - - - - - -In this guide, we will use two relatively large npm-hosted libraries: - - - - -protobufjs— -a library for creating and parsing protobuf messages used by the -gRPC protocol - - - -dns-packet— -a library for processing DNS protocol packets - - - - - -
- - -
- - - -This document mostly employs a generic approach -and avoids specific best practice advices concerning Node.js -and JavaScript. -Make sure to consult the corresponding package's manual -before following the steps suggested here. - -First (assuming Node.js is installed and operational), let's create an -empty project and install some dependencies; -the commands below assume we are in the working directory: - -$ mkdir my_project && cd my_project -$ npx license choose_your_license_here > LICENSE -$ npx gitignore node - -$ cat > package.json <<EOF -{ - "name": "foobar", - "version": "0.0.1", - "description": "", - "main": "index.js", - "keywords": [], - "author": "somename <some.email@example.com> (https://example.com)", - "license": "some_license_here", - "private": true, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - } -} -EOF -$ npm init -y -$ npm install browserify - - - -
- - -
- - -The library provides a parser -for the .proto interface definitions -and a code generator for message parsing and generation. - - - -In this example, we will use the -helloworld.proto -file -from the gRPC examples. -Our goal is to create two messages: -HelloRequest and -HelloResponse. -We will use the -static -mode of protobufjs instead of dynamically generating classes, because -njs doesn't support adding new functions dynamically -due to security considerations. - - - -Next, the library is installed and -the JavaScript code implementing message marshalling -is generated from the protocol definition: - -$ npm install protobufjs -$ npx pbjs -t static-module helloworld.proto > static.js - - - - -Thus, the static.js file becomes our new dependency, -storing all the code we need to implement message processing. -The set_buffer() function contains code that uses the -library to create a buffer with the serialized -HelloRequest message. -The code resides in the code.js file: - -var pb = require('./static.js'); - -// Example usage of protobuf library: prepare a buffer to send -function set_buffer(pb) -{ - // set fields of gRPC payload - var payload = { name: "TestString" }; - - // create an object - var message = pb.helloworld.HelloRequest.create(payload); - - // serialize object to buffer - var buffer = pb.helloworld.HelloRequest.encode(message).finish(); - - var n = buffer.length; - - var frame = new Uint8Array(5 + buffer.length); - - frame[0] = 0; // 'compressed' flag - frame[1] = (n & 0xFF000000) >>> 24; // length: uint32 in network byte order - frame[2] = (n & 0x00FF0000) >>> 16; - frame[3] = (n & 0x0000FF00) >>> 8; - frame[4] = (n & 0x000000FF) >>> 0; - - frame.set(buffer, 5); - - return frame; -} - -var frame = set_buffer(pb); - - - - -To ensure it works, we execute the code using node: - -$ node ./code.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] - -You can see that this got us a properly encoded gRPC frame. -Now let's run it with njs: - -$ njs ./code.js -Thrown: -Error: Cannot find module "./static.js" - at require (native) - at main (native) - - - - -Modules are not supported, so we've received an exception. -To overcome this issue, let's use browserify -or other similar tool. - - - -An attempt to process our existing code.js file will result -in a bunch of JS code that is supposed to run in a browser, -i.e. immediately upon loading. -This isn't something we actually want. -Instead, we want to have an exported function that -can be referenced from the nginx configuration. -This requires some wrapper code. - -In this guide, we use -njs cli in all examples for the sake of simplicity. -In real life, you will be using nginx njs module to run your code. - - - - -The load.js file contains the library-loading code that -stores its handle in the global namespace: - -global.hello = require('./static.js'); - -This code will be replaced with merged content. -Our code will be using the "global.hello" handle to access -the library. - - - -Next, we process it with browserify -to get all dependencies into a single file: - -$ npx browserify load.js -o bundle.js -d - -The result is a huge file that contains all our dependencies: - -(function(){function...... -... -... -},{"protobufjs/minimal":9}]},{},[1]) -//# sourceMappingURL.............. - -To get final "njs_bundle.js" file we concatenate -"bundle.js" and the following code: - -// Example usage of protobuf library: prepare a buffer to send -function set_buffer(pb) -{ - // set fields of gRPC payload - var payload = { name: "TestString" }; - - // create an object - var message = pb.helloworld.HelloRequest.create(payload); - - // serialize object to buffer - var buffer = pb.helloworld.HelloRequest.encode(message).finish(); - - var n = buffer.length; - - var frame = new Uint8Array(5 + buffer.length); - - frame[0] = 0; // 'compressed' flag - frame[1] = (n & 0xFF000000) >>> 24; // length: uint32 in network byte order - frame[2] = (n & 0x00FF0000) >>> 16; - frame[3] = (n & 0x0000FF00) >>> 8; - frame[4] = (n & 0x000000FF) >>> 0; - - frame.set(buffer, 5); - - return frame; -} - -// functions to be called from outside -function setbuf() -{ - return set_buffer(global.hello); -} - -// call the code -var frame = setbuf(); -console.log(frame); - -Let's run the file using node to make sure things still work: - -$ node ./njs_bundle.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] - -Now let's proceed further with njs: - -$ njs ./njs_bundle.js -Uint8Array [0,0,0,0,12,10,10,84,101,115,116,83,116,114,105,110,103] - -The last thing will be to use njs-specific API to convert -array into byte string, so it could be usable by nginx module. -We can add the following snippet before the line -return frame; }: - -if (global.njs) { - return String.bytesFrom(frame) -} - -Finally, we got it working: - -$ njs ./njs_bundle.js |hexdump -C -00000000 00 00 00 00 0c 0a 0a 54 65 73 74 53 74 72 69 6e |.......TestStrin| -00000010 67 0a |g.| -00000012 - -This is the intended result. -Response parsing can be implemented similarly: - -function parse_msg(pb, msg) -{ - // convert byte string into integer array - var bytes = msg.split('').map(v=>v.charCodeAt(0)); - - if (bytes.length < 5) { - throw 'message too short'; - } - - // first 5 bytes is gRPC frame (compression + length) - var head = bytes.splice(0, 5); - - // ensure we have proper message length - var len = (head[1] << 24) - + (head[2] << 16) - + (head[3] << 8) - + head[4]; - - if (len != bytes.length) { - throw 'header length mismatch'; - } - - // invoke protobufjs to decode message - var response = pb.helloworld.HelloReply.decode(bytes); - - console.log('Reply is:' + response.message); -} - - - -
- - -
- - -This example uses a library for generation and parsing of DNS packets. -This a case worth considering because the library and its dependencies -use modern language constructions not yet supported by njs. -In turn, this requires from us an extra step: transpiling the source code. - - - -Additional node packages are needed: - -$ npm install @babel/core @babel/cli @babel/preset-env babel-loader -$ npm install webpack webpack-cli -$ npm install buffer -$ npm install dns-packet - -The configuration file, webpack.config.js: - -const path = require('path'); - -module.exports = { - entry: './load.js', - mode: 'production', - output: { - filename: 'wp_out.js', - path: path.resolve(__dirname, 'dist'), - }, - optimization: { - minimize: false - }, - node: { - global: true, - }, - module : { - rules: [{ - test: /\.m?js$$/, - exclude: /(bower_components)/, - use: { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'] - } - } - }] - } -}; - -Note we are using "production" mode. -In this mode webpack does not use "eval" construction -not supported by njs. -The referenced load.js file is our entry point: - -global.dns = require('dns-packet') -global.Buffer = require('buffer/').Buffer - -We start the same way, by producing a single file for the libraries: - -$ npx browserify load.js -o bundle.js -d - -Next, we process the file with webpack, which itself invokes babel: - -$ npx webpack --config webpack.config.js - -This command produces the dist/wp_out.js file, which is a -transpiled version of bundle.js. -We need to concatenate it with code.js -that stores our code: - -function set_buffer(dnsPacket) -{ - // create DNS packet bytes - var buf = dnsPacket.encode({ - type: 'query', - id: 1, - flags: dnsPacket.RECURSION_DESIRED, - questions: [{ - type: 'A', - name: 'google.com' - }] - }) - - return buf; -} - -Note that in this example generated code is not wrapped into function and we -do not need to call it explicitly. -The result is in the "dist" directory: - -$ cat dist/wp_out.js code.js > njs_dns_bundle.js - -Let's call our code at the end of a file: - -var b = set_buffer(global.dns); -console.log(b); - -And execute it using node: - -$ node ./njs_dns_bundle_final.js -Buffer [Uint8Array] [ - 0, 1, 1, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 6, 103, 111, 111, - 103, 108, 101, 3, 99, 111, 109, 0, - 0, 1, 0, 1 -] - -Make sure this works as expected, and then run it with njs: - -$ njs ./njs_dns_bundle_final.js -Uint8Array [0,1,1,0,0,1,0,0,0,0,0,0,6,103,111,111,103,108,101,3,99,111,109,0,0,1,0,1] - - - - - -The response can be parsed as follows: - -function parse_response(buf) -{ - var bytes = buf.split('').map(v=>v.charCodeAt(0)); - - var b = global.Buffer.from(bytes); - - var packet = dnsPacket.decode(b); - - var resolved_name = packet.answers[0].name; - - // expected name is 'google.com', according to our request above -} - - - -
- -
diff --git a/xml/en/docs/njs/preload_objects.xml b/xml/en/docs/njs/preload_objects.xml deleted file mode 100644 --- a/xml/en/docs/njs/preload_objects.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - -
- -
- - -For each incoming request njs creates a separate virtual machine. -This brings a lot of benefits such as predictable memory consumption -or requests isolation. -However, as all requests are isolated, -if a request handler needs to access some data, -it has to read it by itself. -This is not efficient especially when the amount of data is large. - - - -To address this limitation, -a preloaded shared object was introduced. -Such objects are created immutable and do not have prototype chains: -their values cannot be changed, properties cannot be added or removed. - - -
- - -
- - -Here are some examples of how to work with a preload object in njs: - - - - -access properties by name: - -preloaded_object.prop_name -preloaded_object[prop_name] - - - - -enumerate properties: - -for (i in preloaded_object_name) { - ... -} - - - - -apply non-modifying built-in methods using call(): - -Array.prototype.filter.call(preloaded_object_name, ...) - - - - - - -
- -
diff --git a/xml/en/docs/njs/reference.xml b/xml/en/docs/njs/reference.xml deleted file mode 100644 --- a/xml/en/docs/njs/reference.xml +++ /dev/null @@ -1,6641 +0,0 @@ - - - - - - -
- -
- - -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. - - -
- - -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
r.args{}
r.done()
r.error()
r.finish()
r.headersIn{}
r.headersOut{}
r.httpVersion
r.internal
r.internalRedirect()
r.log()
r.method
r.parent
r.remoteAddress
r.requestBody
r.requestBuffer
r.requestText
r.rawHeadersIn[]
r.rawHeadersOut[]
r.responseBody
r.responseBuffer
r.responseText
r.return()
r.send()
r.sendBuffer()
r.sendHeader()
r.setReturnValue()
r.status
r.subrequest()
r.uri
r.rawVariables{}
r.variables{}
r.warn()
-
- - -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. - -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 - -'a=1&b=%32&A=3&b=4&B=two%20words' - -is converted to r.args as: - -{a: "1", b: ["2", "4"], A: "3", B: "two words"} - -More advanced parsing scenarios can be achieved with the -Query String module -and with the -$args -variable, for example: - - -import qs from 'querystring'; - -function args(r) { - return qs.parse(r.variables.args); -} - -The argument object -is evaluated at the first access to r.args. -If only a single argument is needed, for example foo, -nginx variables can be used: - -r.variables.arg_foo - -Here, nginx variables object -returns the first value for a given key, -case-insensitive, without percent-decoding. - - - -To convert r.args back to a string, -the Query String -stringify -method can be used. - - - -r.done() - -after calling this function, -next data chunks will be passed to client without calling - -(0.5.2). -May be called only from the - function - - -r.error(string) - -writes a string to the error log -on the error level of logging - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - -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 for the main request, writable. - - -If 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. -
- - -The
Foo
response header -can be accessed with the syntax: -headersOut.foo or headersOut['Foo']. -
- - -Outgoing headers should be set before a response header is sent to a client, -otherwise header update will be ignored. -This means that r.headersOut{} is effectively writable in: - - - - -the handler before -r.sendHeader() or -r.return() are called - - - -the handler - - - - - - -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.internal - -boolean value, true for -internal -locations - - -r.internalRedirect(uri) - -performs an -internal -redirect -to the specified uri. -If the uri starts with the “@” prefix, -it is considered a named location. -Redirected requests become internal and can access the -internal -locations. -The actual redirect happens after the handler execution is completed. - - -After redirect, -a new njs VM is started in the target location, -the VM in the original location is stopped. -Values of nginx variables are kept -and can be used to pass information to the target location. -Since 0.5.3, -the variable declared with the js_var directive for -http or -stream -can be used. - - - - - -Since 0.7.4, -the method accepts escaped URIs. - - - - - -r.log(string) - -writes a string to the error log -on the info level of logging - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - -r.method - -HTTP method, read-only - - -r.parent - -references the parent request object - - -r.remoteAddress - -client address, read-only - - -r.requestBody - -the property was made obsolete in -0.5.0 -and was removed in 0.8.0. -The r.requestBuffer or -r.requestText property -should be used instead. - - -r.requestBuffer - -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 -, -and a sufficient buffer size should be set using -. -The property is available only in the - directive. - - -r.requestText - -the same as r.requestBuffer, -but returns a string. -Note that -it may convert bytes invalid in UTF-8 encoding into the replacement character. - - -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.responseBody - -the property was made obsolete in -0.5.0 -and was removed in 0.8.0. -The r.responseBuffer -or -the r.responseText -property -should be used instead. - - -r.responseBuffer - -holds the subrequest response body, -read-only -(since 0.5.0). -The size of r.responseBuffer is limited by the - -directive. - - -r.responseText - -the same as r.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]) - -sends the entire response -with the specified status to the client. -The response can be a string or Buffer -(0.5.0). - -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 -| Buffer) - -sends a part of the response body to the client. -The data sent can be a string or Buffer -(0.5.0) - - -r.sendBuffer(data[, -options]) - -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 the all the data chunks of the current chain are processed. - -The data can be a string or Buffer. -The 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: - - -last - -boolean, -true if the buffer is the last buffer - - -flush - -boolean, -true if the buffer should have the flush flag - - - -The method may be called only from the - function. - - -r.sendHeader() - -sends the HTTP headers to the client - - -r.setReturnValue(value) - -sets the return value of the - handler -(0.7.0). -Unlike an ordinary return statement, -this method should be used when the handler is 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.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 - -directive can be used. -To send a completely new set of headers to a proxied server, the - -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. - - - -For example, to view all response headers in the subrequest: - -async function handler(r) [ - let reply = await r.subrequest('/path'); - - for (var h in reply.headersOut) { - r.log(`${h}: ${reply.headersOut[h]}`); - } - - r.return(200); -} - - - - - -r.uri - -current URI -in request, -normalized, -read-only - - -r.rawVariables{} - -nginx variables as Buffers, -writable -(since 0.5.0) - - -r.variables{} - -nginx variables object, writable -(since 0.2.8). - - -For example, to get the $foo variable, -one of the following syntax can be used: - -r.variables['foo'] -r.variables.foo - -nginx treats variables referenced in nginx.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; - -the r.variables.request_id returns the same value every time. - - - -A variable is writable if: - - - -it was created using the js_var directive for -http or -stream -(since 0.5.3) - - - -it is referenced in nginx configuration file - - - -Even so, some embedded variables still cannot be assigned a value (for example, -$http_). - - - -r.warn(string) - -writes a string to the error log -on the warning level of logging - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - -
-
- -
- - -
- - - - - - - - - - - - - - - - - - - - -
s.allow()
s.decline()
s.deny()
s.done()
s.error()
s.log()
s.off()
s.on()
s.remoteAddress
s.rawVariables{}
s.send()
s.sendDownstream()
s.sendUpstream()
s.status
s.setReturnValue()
s.variables{}
s.warn()
-
- - -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() - -an alias to -s.done(0) -(0.2.4) - - -s.decline() - -an alias to -s.done(-5) -(0.2.4) - - -s.deny() - -an alias to -s.done(403) -(0.2.4) - - -s.done([code]) - -sets an exit 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). - -Possible code values: - - - -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 forbidden - - - - -May be called only from a phase handler function: -js_access -or -js_preread. - - -s.error(string) - -writes a sent string to the error log -on the error level of logging - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - -s.log(string) - -writes a sent string to the error log -on the info level of logging - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - -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 (string) from a client - - -download - -new data (string) to a client - - -upstream - -new data (Buffer) from a client -(since 0.5.0) - - -downstream - -new data (Buffer) to a client -(since 0.5.0) - - - - - - -The completion callback has the following prototype: -callback(data, flags), where -data is string or Buffer (depending on the event type) -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.rawVariables - -nginx variables as Buffers, -writable -(since 0.5.0) - - -s.send(data[, -options]) - -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 the all the data chunks of the current chain are processed. - -The data can be a string or Buffer -(0.5.0). -The 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: - - -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.sendDownstream() - -is identical to s.send(), -except for it always sends data to a client -(since 0.7.8). - - -s.sendUpstream() - -is identical to s.send(), -except for it always sends data from a client -(since 0.7.8). - - -s.status - -session status code, an alias to the -$status -variable, -read only -(since 0.5.2) - - -s.setReturnValue(value) - -sets the return value of the - handler -(0.7.0). -Unlike an ordinary return statement, -this method should be used when the handler is 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{} - -nginx variables object, writable -(since 0.2.8). -A variable can be writable only -if it is referenced in nginx configuration file. -Even so, some embedded variables still cannot be assigned a value. - - -s.warn(string) - -writes a sent string to the error log -on the warning level of logging - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - - - - -
- - -
- - - - - -
PeriodicSession.rawVariables{}
PeriodicSession.variables{}
-
- - -The Periodic Session object is provided as the first argument -for the js_periodic handler for -http -and -stream -(since 0.8.1). - - - - - -PeriodicSession.rawVariables{} - -nginx variables as Buffers, -writable. - - -PeriodicSession.variables{} - -nginx variables object, writable. - - - - - -
- - -
- - - - - - - - - - - -
Headers()
Headers.append()
Headers.delete()
Headers.get()
Headers.getAll()
Headers.forEach()
Headers.has()
Headers.set()
-
- - -The Headers interface of the -Fetch API -is available since 0.5.1. - - - -A new Headers object can be created using the -Headers() constructor: -(since 0.7.10): - - - -Headers([init]) - - - - -init - -An object containing HTTP headers for -prepopulating the Headers object, -can be a string, -an array of name-value pairs, -or an existing Headers object. - - - - - - - - - -A new Headers object can be created -with the following properties and methods: - - - -append() - -Appends a new value into an existing header in the -Headers object, -or adds the header if it does not already exist -(since 0.7.10). - - -delete() - -Deletes a header from the Headers object -(since 0.7.10). - - -get() - -Returns a string containing the values of all headers with the specified name -separated by a comma and a space. - - -getAll(name) - -Returns an array containing the values of all headers with the specified name. - - -forEach() - -Executes a provided function once for each key/value pair -in the Headers object -(since 0.7.10). - - -has() - -Returns a boolean value -indicating whether a header with the specified name exists. - - -set() - -Sets a new value for an existing header inside -the Headers object, -or adds the header if it does not already exist -(since 0.7.10). - - - - - -
- - -
- - - - - - - - - - - - - - -
Request()
Request.arrayBuffer()
Request.bodyUsed
Request.cache
Request.credentials
Request.headers
Request.json()
Request.method
Request.mode
Request.text()
Request.url
-
- - -The Request interface of the -Fetch API -is available since 0.7.10. - - - -A new Request object can be created using the -Request() constructor: - - - -Request[resource[, -options]]) - - -Creates a 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: - - - -body - -The request body, by default is empty. - - -headers - -The response headers object— -the object containing HTTP headers for -prepopulating the Headers object, -can be a string, -an array of name-value pairs, -or an existing Headers object. - - -method - -The HTTP method, by default the GET method is used. - - - - - - - - - -A new Request object can be created -with the following properties and methods: - - - -arrayBuffer() - -Returns a Promise that resolves with -an ArrayBuffer. - - -bodyUsed - -A boolean value, true -if the body was used in the request. - - -cache - -Contains the cache mode of the request. - - -credentials - -Contains the credentials of the request, -by default is same-origin. - - -headers - -The Headers read-only object -associated with the -Request. - - -json() - -Returns a Promise that resolves with -the result of parsing the request body as JSON. - - -method - -Contains the request method. - - -mode - -Contains the mode of the request. - - -text() - -Returns a Promise that resolves with a -string representation of the request body. - - -url - -Contains the URL of the request. - - - - - -
- - -
- - - - - - - - - - - - - - - -
Response()
Response.arrayBuffer()
Response.bodyUsed
Response.headers
Response.json()
Response.ok
Response.redirected
Response.status
Response.statusText
Response.text()
Response.type
Response.url
-
- - -The Response interface is available since -0.5.1. - - - -A new Response object can be created using the -Response() constructor -(since 0.7.10): - - - -Response[body[, -options]]) - -Creates a 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: - - - -headers - -The response headers object— -the object containing HTTP headers for -prepopulating the Headers object, -can be a string, -an array of name-value pairs, -or an existing Headers object. - - -status - -The status code of the response. - - -statusText - -The status message corresponding to the status code. - - - - - - - - - -A new Response() object can be created -with the following properties and methods: - - - -arrayBuffer() - -Takes a Response stream and reads it to completion. -Returns a Promise that resolves with -an ArrayBuffer. - - -bodyUsed - -A boolean value, true -if the body was read. - - -headers - -The Headers read-only object -associated with the -Response. - - -json() - -Takes a Response stream and reads it to completion. -Returns a Promise that resolves with -the result of parsing the body text as JSON. - - -ok - -A boolean value, true -if the response was successful (status codes between 200–299). - - -redirected - -A boolean value, true -if the response is the result of a redirect. - - -status - -The status code of the response. - - -statusText - -The status message corresponding to the status code. - - -text() - -Takes a Response stream and reads it to completion. -Returns a Promise that resolves with a string. - - -type - -The type of the response. - - -url - -The URL of the response. - - - - - -
- - -
- - - - - - - - - - - - - -
ngx.build
ngx.conf_file_path
ngx.conf_prefix
ngx.error_log_path
ngx.fetch()
ngx.log()
ngx.prefix
ngx.version
ngx.version_number
ngx.worker_id
-
- - -The ngx global object is available -since 0.5.0. - - -ngx.build - -a string containing an optional nginx build name, corresponds to the ---build=name -argument -of the configure script, -by default is "" -(0.8.0) - - -ngx.conf_file_path - -a string containing the file path to current nginx configuration file -(0.8.0) - - -ngx.conf_prefix - -a string containing the file path to -nginx configuration prefix— -the directory where nginx is currently looking for configuration -(0.7.8) - - -ngx.error_log_path - -a string containing the file path to the current -error log file -(0.8.0) - - -ngx.fetch(resource, -[options]) - - -Makes a request to fetch a resource -(0.5.1), which can be an -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. - - - -If the URL in the resource is specified as a domain name, -it is determined using a -. -If the https:// scheme is specified, the - -directive should be configured -for the authentication of the resource's HTTPS server. - - - -The options parameter is expected to be an object -with the following keys: - - -body - -request body, -by default is empty - - -buffer_size - -the buffer size for reading the response, -by default is 4096 - - -headers - -request headers object - - -max_response_body_size - -the maximum size of the response body in bytes, -by default is 32768 - - -method - -HTTP method, -by default the GET method is used - - -verify - -enables or disables verification of the HTTPS server certificate, -by default is true -(0.7.0) - - - -Example: - -let reply = await ngx.fetch('http://nginx.org/'); -let body = await reply.text(); - -r.return(200, body); - - - - -ngx.log(level, -message) - -writes a message to the error log with the specified level of logging. -The 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. - - -As nginx has a -hardcoded -maximum line length limit, -only first 2048 bytes of the string can be logged. - - - - -ngx.prefix - -a string containing the file path to -nginx prefix— -a directory that keeps server files -(0.8.0) - - -ngx.version - -a string containing nginx version, -for example: 1.25.0 -(0.8.0) - - -ngx.version_number - -a number containing nginx version, -for example: 1025000 -(0.8.0) - - -ngx.worker_id - -a number that corresponds to nginx internal worker id, -the value is between 0 and the value specified in the - directive -(0.8.0) - - - - - -
- -
- - -The ngx.shared global object is available -since 0.8.0. - - - -
- - - - - - - - - - - - - - - - - - -
ngx.shared.SharedDict.add()
ngx.shared.SharedDict.capacity
ngx.shared.SharedDict.clear()
ngx.shared.SharedDict.delete()
ngx.shared.SharedDict.freeSpace()
ngx.shared.SharedDict.get()
ngx.shared.SharedDict.has()
ngx.shared.SharedDict.incr()
ngx.shared.SharedDict.items()
ngx.shared.SharedDict.keys()
ngx.shared.SharedDict.name
ngx.shared.SharedDict.pop()
ngx.shared.SharedDict.replace()
ngx.shared.SharedDict.set()
ngx.shared.SharedDict.size()
ngx.shared.SharedDict.type
-
- - -The shared dictionary object is available -since 0.8.0. -The shared dictionary name, type, and size -are set with the js_shared_dict_zone directive in -http -or -stream. - - - -A SharedDict() object -has the following properties and methods: - - -ngx.shared.SharedDict.add(key, -value) - -Sets the value -for the specified key in the dictionary -only if the key does not exist yet. -The key is a string representing -the key of the item to add, -the value is the value of the item to add. -Returns true if the value has been successfully added -to the SharedDict dictionary, -false if the key already exists in the dictionary. -Throws SharedMemoryError if -there is not enough free space in the SharedDict dictionary. -Throws TypeError if the value is -of a different type than expected by this dictionary. - - -ngx.shared.SharedDict.capacity - -Returns the capacity of the SharedDict dictionary, -corresponds to the size parameter of -js_shared_dict_zone directive in -http -or -stream. - - -ngx.shared.SharedDict.clear() - -Removes all items from the SharedDict dictionary. - - -ngx.shared.SharedDict.delete(key) - -Removes the item associated with the specified key -from the SharedDict dictionary, -true if the item in the dictionary existed and was removed, -false otherwise. - - -ngx.shared.SharedDict.freeSpace() - -Returns the free page size in bytes. -If the size is zero, the SharedDict dictionary -will still accept new values if there is space in the occupied pages. - - -ngx.shared.SharedDict.get(key) - -Retrieves the item by its key, -returns the value associated with the key -or undefined if there is none. - - -ngx.shared.SharedDict.has(key) - -Searches for an item by its key, -returns true if such item exists or -false otherwise. - - -ngx.shared.SharedDict.incr(key,delta[,init]) - -Increments the integer value associated with the key -by delta. -If the key does not exist, -the item will be initialized to init. -The key is a string, -the delta is the number -to increment or decrement the value by, -the init is a number to initialize the item with -if it does not exist, by default is 0. -Returns the new value. -Throws SharedMemoryError if -there is not enough free space in the SharedDict dictionary. -Throws TypeError if this dictionary does not expect numbers. - -This method can be used only if the dictionary type was declared with -type=number parameter of the -js_shared_dict_zone directive in -http -or -stream. - - - -ngx.shared.SharedDict.items([maxCount]) - -Returns an array of the SharedDict dictionary -key-value items (since 0.8.1). -The maxCount parameter -sets maximum number of items to retrieve, -by default is 1024. - - - -ngx.shared.SharedDict.keys([maxCount]) - -Returns an array of the SharedDict dictionary keys. -The maxCount parameter -sets maximum number of keys to retrieve, -by default is 1024. - - -ngx.shared.SharedDict.name - -Returns the name of the SharedDict dictionary, -corresponds to the zone= parameter of -js_shared_dict_zone directive in -http -or -stream. - - -ngx.shared.SharedDict.pop(key) - -Removes the item associated with the specified key -from the SharedDict dictionary, -returns the value associated with the key -or undefined if there is none. - - -ngx.shared.SharedDict.replace(key, -value) - -Replaces the value -for the specified key only if the key already exists, -returns true if the value was successfully replaced, -false if the key does not exist -in the SharedDict dictionary. -Throws SharedMemoryError if -there is not enough free space in the SharedDict dictionary. -Throws TypeError if the value is -of a different type than expected by this dictionary. - - -ngx.shared.SharedDict.set(key, -value) - -Sets the value for the specified key, -returns this SharedDict dictionary (for method chaining). - - -ngx.shared.SharedDict.size() - -Returns the number of items for the SharedDict dictionary. - - -ngx.shared.SharedDict.type - -Returns string or number that -corresponds to the SharedDict dictionary type -set by the type= parameter of -js_shared_dict_zone directive in -http -or -stream. - - - - - -
- -
- -
- - -
- - -
- - - - - - - - - -
console.error()
console.info()
console.log()
console.time()
console.timeEnd()
console.warn()
-
- - -The console object is available -in nginx since 0.8.2, -in CLI since 0.2.6. - - -console.error(msg[, msg2 ...]) - -Outputs one or more error messages. -The message may be a string or an object. - - -console.info(msg[, msg2 ...]) - -Outputs one or more info messages. -The message may be a string or an object. - - -console.log(msg[, msg2 ...]) - -Outputs one or more log messages. -The message may be a string or an object. - - -console.time(label) - -Starts a timer that can track how long an operation takes. -The 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) - -Stops a timer previously started by -console.time() -The label parameter allows naming different timers. - - -console.warn(msg[, msg2 ...]) - -Outputs one or more warning messages. -The message may be a string or an object. - - - - - -
- - -
- - - - - - - - - - - - - - -
сrypto.getRandomValues()
сrypto.subtle.encrypt()
сrypto.subtle.decrypt()
сrypto.subtle.deriveBits()
сrypto.subtle.deriveKey()
сrypto.subtle.digest()
сrypto.subtle.exportKey()
сrypto.subtle.generateKey()
сrypto.subtle.importKey()
сrypto.subtle.sign()
сrypto.subtle.verify()
-
- - -The crypto object is a global object -that allows using cryptographic functionality -(since 0.7.0). - - - - - -сrypto.getRandomValues(typedArray) - -Gets cryptographically strong random values. -Returns the same array passed as typedArray -but with its contents replaced with the newly generated random numbers. -Possible values: - - -typedArray - -can be -Int8Array, -Int16Array, -Uint16Array, -Int32Array, or -Uint32Array - - - - - -сrypto.subtle.encrypt(algorithm, -key, -data) - -Encrypts data -using the provided -algorithm and -key. -Returns a Promise that fulfills with -an ArrayBuffer containing the ciphertext. -Possible values: - - -algorithm - -an object that specifies -the algorithm to be used and any extra parameters if required: - - - -for RSA-OAEP, -pass the object with the following keys: - - - - -name is a string, -should be set to RSA-OAEP: - - -crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data) - - - - - - - - -for AES-CTR, -pass the object with the following keys: - - - - -name is a string, -should be set to AES-CTR - - - -counter is an -ArrayBuffer, -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 - - - -length is 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 AES-CBC, pass the object with the following keys: - - - - -name is a string, -should be set to AES-CBC - - - -iv or the initialization vector, is an -ArrayBuffer, -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. - - - - - - -for AES-GCM, pass the object with the following keys: - - - - -name is a string, -should be set to AES-GCM - - - -iv or the initialization vector, is an -ArrayBuffer, -TypedArray, or -DataView, -must be 16 bytes, -and must be unique for every encryption operation carried out with a given key - - - -additionalData (optional) is an -ArrayBuffer, -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. - - - -tagLength (optional, default is 128) - -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. - - - - - - - - -key - -a CryptoKey that contains -the key to be used for encryption - - -data - -an -ArrayBuffer, -TypedArray, or -DataView -that contains -the data to be encrypted (also known as the plaintext) - - - - - -сrypto.subtle.decrypt(algorithm, -key, -data) - -Decrypts encrypted data. -Returns a Promise with the decrypted data. -Possible values: - - - -algorithm - -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 encrypt() call. - - - -for RSA-OAEP, -pass the object with the following keys: - - - - -name is a string, -should be set to RSA-OAEP: - - -crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data) - - - - - - - -for AES-CTR, -pass the object with the following keys: - - - - -name is a string, -should be set to AES-CTR - - - -counter is an -ArrayBuffer, -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. - - - -length is 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 AES-CBC, pass the object with the following keys: - - - - -name is a string, -should be set to AES-CBC - - - -iv or the initialization vector, is an -ArrayBuffer, -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). - - - - - - -for AES-GCM, pass the object with the following keys: - - - - -name is a string, -should be set to AES-GCM - - - -iv or the initialization vector, is an -ArrayBuffer, -TypedArray, or -DataView, -must be 16 bytes, -and must be unique for every encryption operation carried out with a given key - - - -additionalData (optional) is an -ArrayBuffer, -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. - - - -tagLength (optional, default is 128) - -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. - - - - - - - - -key - -a CryptoKey -that contains the key to be used for decryption. -If RSA-OAEP is used, this is the -privateKey property of the -CryptoKeyPair object. - - -data - -an -ArrayBuffer, -TypedArray, or -DataView -that contains the data to be decrypted (also known as ciphertext) - - - - - -сrypto.subtle.deriveBits(algorithm, -baseKey, -length) - -Derives an array of bits from a base key. -Returns a Promise -which will be fulfilled with an -ArrayBuffer that contains the derived bits. -Possible values: - - -algorithm - -is an object that defines the derivation algorithm to use: - - - -for HKDF, -pass the object with the following keys: - - - - -name is a string, -should be set to HKDF - - - -hash is a string with the digest algorithm to use: -SHA-1, -SHA-256, -SHA-384, or -SHA-512 - - - -salt is an -ArrayBuffer, -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. - - - -info is an -ArrayBuffer, -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. - - - - - - -for PBKDF2, -pass the object with the following keys: - - - - -name is a string, -should be set to PBKDF2 - - - -hash is a string with the digest algorithm to use: -SHA-1, -SHA-256, -SHA-384, or -SHA-512 - - - -salt is an -ArrayBuffer, -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. - - - -iterations is a number -that represents the number of times the hash function will be executed -in deriveKey() - - - - - - - - -baseKey - -is a CryptoKey -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 -сrypto.subtle.importKey() - - -length - -is a number representing the number of bits to derive. -For browsers compatibility, -the number should be a multiple of 8 - - - - - -сrypto.subtle.deriveKey(algorithm, -baseKey, -derivedKeyAlgorithm, -extractable, -keyUsages) - -Derives a secret key from a master key. -Possible values: - - -algorithm - -is an object that defines the derivation algorithm to use: - - - -for HKDF, -pass the object with the following keys: - - - - -name is a string, -should be set to HKDF - - - -hash is a string with the digest algorithm to use: -SHA-1, -SHA-256, -SHA-384, or -SHA-512 - - - -salt is an -ArrayBuffer, -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. - - - -info is an -ArrayBuffer, -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. - - - - - - -for PBKDF2, -pass the object with the following keys: - - - - -name is a string, -should be set to PBKDF2 - - - -hash is a string with the digest algorithm to use: -SHA-1, -SHA-256, -SHA-384, or -SHA-512 - - - -salt is an -ArrayBuffer, -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. - - - -iterations is a number -that represents the number of times the hash function will be executed -in deriveKey() - - - - - - - - -baseKey - -is a CryptoKey -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 -сrypto.subtle.importKey(). - - -derivedKeyAlgorithm - -is an object -that defines the algorithm the derived key will be used for: - - - -for HMAC, -pass the object with the following keys: - - - - -name is a string, -should be set to HMAC - - - -hash is a string with the name of the digest function to use: -SHA-1, -SHA-256, -SHA-384, or -SHA-512 - - - -length (optional) is a number -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 chozen hash function - - - - - - -for -AES-CTR, -AES-CBC, or -AES-GCM, -pass the object with the following keys: - - - - -name is a string, -should be set to -AES-CTR, -AES-CBC, or -AES-GCM, -depending on the algorithm used - - - -length is a number that represents -the length in bits of the key to generate: -128, -192, or -256 - - - - - - - - -extractable - -is a boolean value -that indicates whether it will be possible to export the key - - -keyUsages - -is an Array -that indicates what can be done with the derived key. -The key usages must be allowed by the algorithm -set in derivedKeyAlgorithm. -Possible values: - - -encrypt - -key for encrypting messages - - -decrypt - -key for decrypting messages - - -sign - -key for signing messages - - -verify - -key for verifying signatures - - -deriveKey - -key for deriving a new key - - -deriveBits - -key for deriving bits - - -wrapKey - -key for wrapping a key - - -unwrapKey - -key for unwrapping a key - - - - - - - - -сrypto.subtle.digest(algorithm, -data) - -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 Promise which will be fulfilled with the digest. -Possible values: - - -algorithm - -is a string that defines the hash function to use: -SHA-1 (not for cryptographic applications), -SHA-256, -SHA-384, or -SHA-512 - - -data - -is an -ArrayBuffer, -TypedArray, or -DataView -that contains the data to be digested - - - - - -сrypto.subtle.exportKey(format, -key) - -Exports a key: takes a key as -a 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: - - -format - -a string that describes the data format in which the key should be exported, -can be the following: - - -raw - -the raw data format - - -pkcs8 - -the -PKCS #8 -format - - -spki - -the -SubjectPublicKeyInfo -format - - -jwk - -the -JSON Web Key -(JWK) format (since 0.7.10) - - - - - -key - -the CryptoKey -that contains the key to be exported - - - - - -сrypto.subtle.generateKey(algorithm, -extractable, -usage) - -Generates a new key for symmetric algorithms -or key pair for public-key algorithms -(since 0.7.10). -Returns a Promise that fulfills with the generated key -as -a CryptoKey -or CryptoKeyPair object. -Possible values: - - -algorithm - -a dictionary object that defines the type of key to generate -and provides extra algorithm-specific parameters: - - - -for -RSASSA-PKCS1-v1_5, -RSA-PSS, or -RSA-OAEP, -pass the object with the following keys: - - - -name is a string, should be set to -RSASSA-PKCS1-v1_5, -RSA-PSS, or -RSA-OAEP, -depending on the used algorithm - - - -hash is a string that represents -the name of the digest function to use, can be -SHA-256, -SHA-384, or -SHA-512 - - - - - - -for -ECDSA, -pass the object with the following keys: - - - -name is a string, should be set to ECDSA - - - -namedCurve is a string that represents -the name of the elliptic curve to use, may be -P-256, -P-384, or -P-521 - - - - - - -for -HMAC, -pass the object with the following keys: - - - -name is a string, should be set to HMAC - - - - -hash is a string that represents -the name of the digest function to use, can be -SHA-256, -SHA-384, or -SHA-512 - - - -length (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 -AES-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 - - - - - -extractable - -boolean value that indicates if it is possible to export the key - - -usage - -an array that indicates possible actions with the key: - - -encrypt - -key for encrypting messages - - -decrypt - -key for decrypting messages - - -sign - -key for signing messages - - -verify - -key for verifying signatures - - -deriveKey - -key for deriving a new key - - -deriveBits - -key for deriving bits - - -wrapKey - -key for wrapping a key - - -unwrapKey - -key for unwrapping a key - - - - - - - - -сrypto.subtle.importKey(format, -keyData, -algorithm, -extractable, -keyUsages) - -Imports a key: takes as input a key in an external, portable format -and gives a CryptoKey object. -Returns a Promise that fulfills with the imported key -as a CryptoKey object. -Possible values: - - -format - -a string that describes the data format of the key to import, -can be the following: - - -raw - -the raw data format - - -pkcs8 - -the -PKCS #8 -format - - -spki - -the -SubjectPublicKeyInfo -format - - -jwk - -the -JSON Web Key -(JWK) format (since 0.7.10) - - - - - - -keyData - -the -ArrayBuffer, -TypedArray, or -DataView -object that contains the key in the given format - - -algorithm - -a dictionary object that defines the type of key to import -and provides extra algorithm-specific parameters: - - - -for -RSASSA-PKCS1-v1_5, -RSA-PSS, or -RSA-OAEP, -pass the object with the following keys: - - - -name is a string, should be set to -RSASSA-PKCS1-v1_5, -RSA-PSS, or -RSA-OAEP, -depending on the used algorithm - - - -hash is a string that represents -the name of the digest function to use, can be -SHA-1, -SHA-256, -SHA-384, or -SHA-512 - - - - - - -for -ECDSA, -pass the object with the following keys: - - - -name is a string, should be set to ECDSA - - - -namedCurve is a string that represents -the name of the elliptic curve to use, may be -P-256, -P-384, or -P-521 - - - - - - -for -HMAC, -pass the object with the following keys: - - - -name is a string, should be set to HMAC - - - - -hash is a string that represents -the name of the digest function to use, can be -SHA-256, -SHA-384, or -SHA-512 - - - -length (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 -AES-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 - - - -for -PBKDF2, -pass the PBKDF2 string - - - -for -HKDF, -pass the HKDF string - - - - - -extractable - -boolean value that indicates if it is possible to export the key - - -keyUsages - -an array that indicates possible actions with the key: - - -encrypt - -key for encrypting messages - - -decrypt - -key for decrypting messages - - -sign - -key for signing messages - - -verify - -key for verifying signatures - - -deriveKey - -key for deriving a new key - - -deriveBits - -key for deriving bits - - -wrapKey - -key for wrapping a key - - -unwrapKey - -key for unwrapping a key - - - - - - - - -сrypto.subtle.sign(algorithm, -key, -data) - -Returns signature as a Promise -that fulfills with an ArrayBuffer containing the signature. -Possible values: - - -algorithm - -is a string or object that specifies the signature algorithm to use -and its parameters: - - - - -for RSASSA-PKCS1-v1_5, -pass the string identifying the algorithm or an object -of the form { "name": "ALGORITHM" } - - - -for RSA-PSS, -pass the object with the following keys: - - - -name is a string, should be set to -RSA-PSS - - - -saltLength is a long integer -that represents the length of the random salt to use, in bytes - - - - - - -for ECDSA, -pass the object with the following keys: - - - -name is a string, should be set to -ECDSA - - - -hash is an identifier for the digest algorithm to use, -can be -SHA-256, -SHA-384, or -SHA-512 - - - - - - -for HMAC, -pass the string identifying the algorithm or an object -of the form { "name": "ALGORITHM" } - - - - - -key - -is a CryptoKey object -that the key to be used for signing. -If algorithm identifies a public-key cryptosystem, this is the private key. - - -data - -is an -ArrayBuffer, -TypedArray, or -DataView -object that contains the data to be signed - - - - - - -сrypto.subtle.verify(algorithm, -key, -signature, -data) - -Verifies a digital signature, -returns a Promise that fulfills with a boolean value: -true if the signature is valid, -otherwise false. -Possible values: - - -algorithm - -is a string or object that specifies the algorithm to use -and its parameters: - - - - -for RSASSA-PKCS1-v1_5, -pass the string identifying the algorithm or an object -of the form { "name": "ALGORITHM" } - - - -for RSA-PSS, -pass the object with the following keys: - - - -name is a string, should be set to -RSA-PSS - - - -saltLength is a long integer -that represents the length of the random salt to use, in bytes - - - - - - -for ECDSA, -pass the object with the following keys: - - - -name is a string, should be set to -ECDSA - - - -hash is an identifier for the digest algorithm to use, -can be -SHA-256, -SHA-384, or -SHA-512 - - - - - - -for HMAC, -pass the string identifying the algorithm or an object -of the form { "name": "ALGORITHM" } - - - - - -key - -is a CryptoKey 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. - - -signature - -is an -ArrayBuffer, -TypedArray, or -DataView -that contains the signature to verify - - -data - -is an -ArrayBuffer, -TypedArray, or -DataView -object that contains the data whose signature is to be verified - - - - - - - - -
- - -
- - - - - - - -
CryptoKey.algorithm
CryptoKey.extractable
CryptoKey.type
CryptoKey.usages
-
- - -The CryptoKey object -represents a cryptographic key obtained -from one of the SubtleCrypto methods: -сrypto.subtle.generateKey(), -сrypto.subtle.deriveKey(), -сrypto.subtle.importKey(). - - - - - -CryptoKey.algorithm - -returns an object describing the algorithm for which this key can be used -and any associated extra parameters -(since 0.8.0), -read-only - - -CryptoKey.extractable - -a boolean value, true if the key can be exported -(since 0.8.0), -read-only - - -CryptoKey.type - -a string value that indicates which kind of key is represented by the object, -read-only. -Possible values: - - -secret - -This key is a secret key for use with a symmetric algorithm. - - -private - -This key is the private half of an asymmetric algorithm's -CryptoKeyPair - - -public - -This key is the public half of an asymmetric algorithm's -CryptoKeyPair. - - - - - -CryptoKey.usages - -An array of strings indicating what this key can be used for -(since 0.8.0), -read-only. -Possible array values: - - -encrypt - -key for encrypting messages - - -decrypt - -key for decrypting messages - - -sign - -key for signing messages - - -verify - -key for verifying signatures - - -deriveKey - -key for deriving a new key - - -deriveBits - -key for deriving bits - - - - - - - - -
- - -
- - - - - -
CryptoKeyPair.privateKey
CryptoKeyPair.publicKey
-
- - -The CryptoKeyPair is a dictionary object -of the WebCrypto API -that represents an asymmetric key pair. - - - - - -CryptoKeyPair.privateKey - -A CryptoKey object -representing the private key. - - -CryptoKeyPair.publicKey - -A CryptoKey object -representing the public key. - - - - - -
- - -
- - - - - - - - -
njs.version
njs.version_number
njs.dump()
njs.memoryStats
njs.on()
-
- - -The njs object is a global object -that represents the current VM instance -(since 0.2.0). - - - - - -njs.version - -Returns a string with the current version of njs -(for example, “0.7.4”). - - -njs.version_number - -Returns a number with the current version of njs. -For example, “0.7.4” is returned as 0x000704 -(since 0.7.4). - - -njs.dump(value) - -Returns the pretty-print string representation for a value. - - -njs.memoryStats - -Object containing memory statistics for current VM instance -(since 0.7.8). - - -size - -amount of memory in bytes njs memory pool claimed from the operating system. - - - - - -njs.on(event, -callback) - -Registers a callback for the specified VM event -(since 0.5.2). -An event may be one of the following strings: - - -exit - -is called before the VM is destroyed. -The callback is called without arguments. - - - - - - - - -
- - -
- - - - - - - -
process.argv
process.env
process.pid
process.ppid
-
- - -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 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. - - - - - -
- - -
- - -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. - - -
- - - -Since 0.8.0, -the support for byte strings and byte string methods were removed. -When working with byte sequence, -the Buffer object -and Buffer properties, such as -r.requestBuffer, -r.rawVariables, -should be used. - - - - -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 UTF-8 encoding: - ->> '£'.toUTF8().toString('hex') -'c2a3' /* C2 A3 is the UTF-8 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) - -The method was made obsolete in -0.4.4 -and was removed in 0.8.0. -The Buffer.from method should be used instead: - ->> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString() -'buffer' - ->> Buffer.from('YnVmZmVy', 'base64').toString() -'buffer' - -Before 0.4.4, -created a byte string either from an array that contained octets, -or from an encoded string -(0.2.3), -the encoding could be -hex, -base64, and -base64url. - - -String.prototype.fromBytes(start[, -end]) - -the property was made obsolete in -0.7.7 -and was removed in 0.8.0. -Before 0.7.7, -returned a new Unicode string from a byte string -where each byte was replaced with a corresponding Unicode code point. - - -String.prototype.fromUTF8(start[, -end]) - -the property was made obsolete in -0.7.7 -and was removed in 0.8.0. -The TextDecoder method -should be used instead. -Before 0.7.7, -converted a byte string containing a valid UTF-8 string -into a Unicode string, -otherwise null was returned. - - -String.prototype.toBytes(start[, -end]) - -the property was made obsolete in -0.7.7 -and was removed in 0.8.0. -Before 0.7.7, -serialized a Unicode string to a byte string, -returned null if a character larger than 255 was -found in the string. - - -String.prototype.toString(encoding) - - -the property was made obsolete in -0.7.7 -and was removed in 0.8.0. -Before 0.7.7, -encoded 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]) - -the property was made obsolete in -0.7.7 -and was removed in 0.8.0. -The TextEncoder method -should be used instead. -Before 0.7.7, -serialized a Unicode string -to a byte string using UTF-8 encoding: - ->> 'αβγδ'.toUTF8().length -8 ->> 'αβγδ'.length -4 - - - - - - -
- -
- -
- - -
- - -
- - - - - - - - -
TextDecoder()
TextDecoder.prototype.encoding
TextDecoder.prototype.fatal
TextDecoder.prototype.ignoreBOM
TextDecoder.prototype.decode()
-
- - -The TextDecoder -produces a stream of code points -from a stream of bytes -(0.4.3). - - - - - -TextDecoder([[encoding], -options]) - -Creates a new TextDecoder object -for specified encoding, -currently, only UTF-8 is supported. -The options is -TextDecoderOptions dictionary with the property: - - - -fatal - -boolean flag indicating if -TextDecoder.decode() -must throw the TypeError exception when -a coding error is found, by default is false. - - - - - -TextDecoder.prototype.encoding - -Returns a string with the name of the encoding used by -TextDecoder(), -read-only. - - -TextDecoder.prototype.fatal - -boolean flag, true if -the error mode is fatal, -read-only. - - -TextDecoder.prototype.ignoreBOM - -boolean flag, true if -the byte order marker is ignored, -read-only. - - -TextDecoder.prototype.decode(buffer, -[options]) - -Returns a string with the text -decoded from the buffer by -TextDecoder(). -The buffer can be ArrayBuffer. -The options is -TextDecodeOptions dictionary with the property: - - - -stream - -boolean flag indicating if -additional data will follow in subsequent calls to decode(): -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.prototype.encode()
TextEncoder.prototype.encodeInto()
-
- - -The TextEncoder object -produces a byte stream with UTF-8 encoding -from a stream of code points -(0.4.3). - - - - - -TextEncoder() - -Returns a newly constructed TextEncoder -that will generate a byte stream with UTF-8 encoding. - - -TextEncoder.prototype.encode(string) - -Encodes string into a Uint8Array -with UTF-8 encoded text. - - -TextEncoder.prototype.encodeInto(string, -uint8Array) - -Encodes a 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: - - - -read - -the number of UTF-16 units of code from the source string -converted to UTF-8 - - -written - -the number of bytes modified in the destination Uint8Array - - - - - - - - -
- -
- - -
- - - - - -
clearTimeout()
setTimeout()
-
- - - - -clearTimeout(timeout) - -Cancels a timeout object -created by setTimeout(). - - -setTimeout(function, -milliseconds[, -argument1, -argumentN]) - -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); - - - - - - -
- - - - - -
atob()
btoa()
-
- - - - -atob(encodedData) - -Decodes a string of data which has been encoded -using Base64 encoding. -The encodedData parameter is a binary string -that contains Base64-encoded data. -Returns a string that contains decoded data from encodedData. - -The similar 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) - -Creates a Base64-encoded ASCII string from a binary string. -The stringToEncode parameter is a binary string to encode. -Returns an ASCII string containing the Base64 representation of -stringToEncode. - -The method can be used to encode data -which may otherwise cause communication problems, transmit it, -then use the 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 - - - - - - - -
- -
- - -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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.buffer
buf.byteOffset
buf.compare()
buf.copy()
buf.equals()
buf.fill()
buf.includes()
buf.indexOf()
buf.lastIndexOf()
buf.length
buf.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()
-
- - - - -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]) - -Returns the byte length of a specified value, -when encoded using 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 -utf8, -hex, -base64, -base64url; -by default is utf8. - - -Buffer.compare(buffer1, -buffer2) - -Compares 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]) - -Returns a new Buffer -which is the result of concatenating all the Buffer instances in the list. -If there are no items in the list or the total length is 0, -a new zero-length Buffer is returned. -If 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) - -Allocates a new Buffer using an array of bytes -in the range 0255. -Array entries outside that range will be truncated. - - -Buffer.from(arrayBuffer, -byteOffset[, -length]]) - -Creates a view of the 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) - -Copies the passed buffer data onto a new Buffer instance. - - -Buffer.from(object[, -offsetOrEncoding[, -length]]) - -For objects whose valueOf() function -returns a value not strictly equal to object, -returns -Buffer.from(object.valueOf(), -offsetOrEncoding, -length). - - -Buffer.from(string[, -encoding]) - -Creates a new Buffer with a string. -The encoding parameter identifies the character encoding -to be used when converting a string into bytes. -The encoding can be -utf8, -hex, -base64, -base64url; -by default is utf8. - - -Buffer.isBuffer(object) - -A boolean value, -returns true if object is a Buffer. - - -Buffer.isEncoding(encoding) - -A boolean value, -returns true -if encoding is the name of a supported character encoding. - - -buffer[index] - -The index operator that 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.buffer - -The underlying ArrayBuffer object -based on which this Buffer object is created. - - -buf.byteOffset - -An integer, -specifying the byteOffset of the Buffers -underlying ArrayBuffer object. - - -buf.compare(target[, -targetStart[, -targetEnd[, -sourceStart[, -sourceEnd]]]]) - -Compares buffer with target and returns a number -indicating whether buffer comes before, after, or is the same -as target in sort order. -Comparison is based on the actual sequence of bytes in each Buffer. -The 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]]]) - -Copies data from a region of buffer to a region in target, -even if the target memory region overlaps with buffer. -The 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) - -A boolean value, -returns true if both Buffer and otherBuffer -have exactly the same bytes. - - -buf.fill(value[, -offset[, -end]][, -encoding]) - -Fills the Buffer with the specified 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]) - -Equivalent to -buf.indexOf() -!== -1, -returns true if the value was found -in Buffer. - - -buf.indexOf(value[, -byteOffset][, -encoding]) - -Returns an integer which is the index of the first occurrence of -value in Buffer, or -1 -if Buffer does not contain value. -The value can be a -string with specified encoding -(by default utf8), -Buffer, -Unit8Array, -or a number between 0 and 255. - - -buf.lastIndexOf(value[, -byteOffset][, -encoding]) - -The same as -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.length - -Returns the number of bytes in Buffer. - - -buf.readIntBE(offset, -byteLength) - -Reads the 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) - -Reads the 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) - -Reads the 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) - -Reads the 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]) - -Reads a 64-bit, big-endian double from buf -at the specified offset. - - -buf.readDoubleLE([offset]) - -Reads a 64-bit, little-endian double from buf -at the specified offset. - - -buf.readFloatBE([offset]) - -Reads a 32-bit, big-endian float from buf -at the specified offset. - - -buf.readFloatLE([offset]) - -Reads a 32-bit, little-endian float from buf -at the specified offset. - - -buf.subarray([start[, -end]]) - -Returns a new 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]]) - -Returns a new 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() - -Interprets 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() - -Interprets 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() - -Interprets 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() - -Returns a JSON representation of buf. -JSON.stringify() -implicitly calls this function when stringifying a Buffer instance. - - -buf.toString([encoding[, -start[, -end]]]) - -Decodes buf to a string -according to the specified character encoding -which can be utf8, -hex, -base64, -base64url. -The start and end parameters -may be passed to decode only a subset of Buffer. - - -buf.write(string[, -offset[, -length]][, -encoding]) - -Writes a 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 -utf8, -hex, -base64, -base64url. - - -buf.writeIntBE(value, -offset, -byteLength) - -Writes 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) - -Writes 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) - -Writes 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) - -Writes 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]) - -Writes the value to buf -at the specified offset as big-endian. - - -buf.writeDoubleLE(value, -[offset]) - -Writes the value to buf -at the specified offset as little-endian. - - -buf.writeFloatBE(value, -[offset]) - -Writes the value to buf -at the specified offset as big-endian. - - -buf.writeFloatLE(value, -[offset]) - -Writes the value to buf -at the specified offset as little-endian. - - - - - -
- - -
- - - - - -
crypto.createHash()
crypto.createHmac()
-
- - - -Since 0.7.0, -extended crypto API is available as a global -crypto object. - -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.update()
hash.digest()
-
- - - - -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 Buffer object -(0.4.4) is returned. - -Before version (0.4.4), -a byte string was returned instead of a Buffer object. - - - -hash.copy() - -Makes a copy of the current state of the hash -(since 0.7.12). - - - - - - - ->> var cr = require('crypto') -undefined - ->> cr.createHash('sha1').update('A').update('B').digest('base64url') -'BtlFlCqiamG-GMPiK_GbvKjdK10' - - - -
- - -
- - - - - -
hmac.update()
hmac.digest()
-
- - - - -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 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' - - - -
- -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - -
fs.accessSync()
fs.appendFileSync()
fs.closeSync()
fs.existsSync()
fs.fstatSync()
fs.lstatSync()
fs.mkdirSync()
fs.openSync()
fs.promises.open()
fs.readdirSync()
fs.readFileSync()
fs.readSync()
fs.realpathSync()
fs.renameSync()
fs.rmdirSync()
fs.statSync()
fs.symlinkSync()
fs.unlinkSync()
fs.writeFileSync()
fs.writeSync()
fs.writeSync()
-
- - - - - - - - -
fs.Dirent
fs.FileHandle
fs.Stats
File Access Constants
File System Flags
-
- - -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 - -an optional integer -that specifies the accessibility checks to be performed, -by default is fs.constants.F_OK - -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. -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: - - -mode - -mode option, by default is 0o666 - - -flag - -file system flag, -by default is a - - - - - -closeSync(fd) - -Closes the fd file descriptor represented by an integer -used by the method. -Returns undefined. - - -existsSync(path) - -Boolean value, returns -true if the specified path exists. -(0.8.2) - - -fstatSync(fd) - -Retrieves the fs.Stats object -for the file descriptor -(0.7.7). -The fd parameter is an integer -representing the file descriptor used by the method. - - -lstatSync(path[, -options]) - -Synchronously retrieves -the fs.Stats object -for the symbolic link referred to by path -(0.7.1). -The options parameter is expected to be -an object with the following keys: - -throwIfNoEntry - -a boolean value which indicates -whether an exception is thrown if no file system entry exists, -rather than returning undefined, -by default is false. - - - - -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. - - - - - -openSync(path[, -flags[, mode]]) - -Returns an integer -representing the file descriptor for the opened file path -(0.7.7). - - -flags - -file system flag, -by default is r - - -mode - -mode option, by default is 0o666 - - - - - -promises.open(path[, -flags[, mode]]) - -Returns a FileHandle object -representing the opened file path -(0.7.7). - - -flags - -file system flag, -by default is r - - -mode - -mode option, by default is 0o666 - - - - - -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 utf8. -The encoding can be utf8 and buffer -(0.4.4). - - -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 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: - - -encoding - -encoding, by default is not specified. -The encoding can be utf8, -hex -(0.4.4), -base64 -(0.4.4), -base64url -(0.4.4). - - -flag - -file system flag, -by default is r - - - - ->> 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 - - - -readSync(fd, -buffer, offset[, -length[, position]]) - -Reads the content of a file path using file descriptor fd, -returns the number of bytes read -(0.7.7). - - - -buffer - -the buffer value can be a -Buffer, -TypedArray, or -DataView - - -offset - -is an integer representing -the position in buffer to write the data to - - -length - -is an integer representing -the number of bytes to read - - -position - -specifies where to begin reading from in the file, -the value can be -integer or -null, -by default is null. -If position is null, -data will be read from the current file position, -and the file position will be updated. -If position is an integer, -the file position will be unchanged - - - - - -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). - - -statSync(path,[ -options]) - -Synchronously retrieves -the fs.Stats object -for the specified path -(0.7.1). -The path can be a -string or -buffer. -The options parameter is expected to be -an object with the following keys: - -throwIfNoEntry - -a boolean value which indicates whether -an exception is thrown if no file system entry exists -rather than returning undefined, -by default is true. - - - - -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. -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: - -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 - - - -writeSync(fd, -buffer, offset[, -length[, position]]) - -Writes a buffer to a file using file descriptor, -returns the number of bytes written -(0.7.7). - - - -fd - -an integer representing the file descriptor - - -buffer - -the buffer value can be a -Buffer, -TypedArray, or -DataView - - -offset - -is an integer that determines -the part of the buffer to be written, -by default 0 - - -length - -is an integer specifying the number of bytes to write, -by default is an offset of -Buffer.byteLength - - -position - -refers to the offset from the beginning of the file -where this data should be written, -can be an -integer or -null, -by default is null. -See also -pwrite(2). - - - - - -writeSync(fd, -string[, -position[, -encoding]]) - -Writes a string to a file -using file descriptor fd, -returns the number of bytes written -(0.7.7). - - - -fd - -is an integer representing a file descriptor - - -position - -refers to the offset from the beginning of the file -where this data should be written, -can be an -integer or -null, by default is null. -See also -pwrite(2) - - -encoding - -is a string, -by default is utf8 - - - - - - - - - -
- - -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. - - - - - -
- - -
- - - - - - - - - -
filehandle.close()
filehandle.fd
filehandle.read()
filehandle.stat()
filehandle.write(buf)
filehandle.write(str)
-
- - -The FileHandle object is an object wrapper -for a numeric file descriptor -(0.7.7). -Instances of the FileHandle object are created by the -fs.promises.open() method. -If a FileHandle is not closed using the -filehandle.close() method, -it will try to automatically close the file descriptor, -helping to prevent memory leaks. -Please do not rely on this behavior because it can be unreliable. -Instead, always explicitly close a FileHandle. - - - - - -filehandle.close() - -Closes the file handle after waiting for any pending operation on the handle -to complete. -Returns a promise, fulfills with undefined upon success. - - -filehandle.fd - -The numeric file descriptor -managed by the FileHandle object. - - -filehandle.read(buffer, -offset[, -length[, -position]]) - -Reads data from the file and stores that in the given buffer. - - - -buffer - -a buffer that will be filled with the file data read, -the value can be a -Buffer, -TypedArray, or -DataView - - -offset - -is an integer -representing the location in the buffer at which to start filling - - -length - -is an integer -representing the number of bytes to read - - -position - -the location where to begin reading data from the file, -the value can be -integer, -null. -If null, data will be read from the current file position -and the position will be updated. -If position is an integer, -the current file position will remain unchanged. - - - -Returns a Promise which fulfills upon success -with an object with two properties: - - -bytesRead - -is an integer representing the number of bytes read - - -buffer - -is a reference to the passed argument in buffer, can be -Buffer, -TypedArray, or -DataView - - - - - -filehandle.stat() - -Fulfills with an -fs.Stats for the file, -returns a promise. - - -filehandle.write(buffer, -offset[, -length[, -position]]) - -Writes a buffer to the file. - - - -buffer - -the buffer value can be a -Buffer, -TypedArray, or -DataView - - -offset - -is an integer representing -the start position from within buffer where the data to write begins - - -length - -is an integer representing -the number of bytes from buffer to write, by default -is an offset of -Buffer.byteLength - - -position - -the offset from the beginning of the file -where the data from buffer should be written, -can be an -integer or -null, -by default is null. -If position is not a number, -the data will be written at the current position. -See the POSIX -pwrite(2) -documentation for details. - - -Returns a Promise which is resolved with an object -containing two properties: - - -bytesWritten - -is an integer representing the number of bytes written - - -buffer - -a reference to the buffer written, can be a -Buffer, -TypedArray, or -DataView - - - - -It is unsafe to use filehandle.write() multiple times -on the same file without waiting for the promise to be resolved or rejected. - - - - - -filehandle.write(string[, -position[, -encoding]]) - -Writes a string to the file. - - - -position - -the offset from the beginning of the file -where the data from buffer should be written, -can be an -integer or -null, -by default is null. -If position is not a number, -the data will be written at the current position. -See the POSIX -pwrite(2) -documentation for details. - - -encoding - -the expected encoding of the string, by default utf8 - - - -Returns a Promise which is resolved with an object -containing two properties: - - -bytesWritten - -is an integer representing the number of bytes written - - -buffer - -a reference to the buffer written, can be a -Buffer, -TypedArray, or -DataView - - - - -It is unsafe to use filehandle.write() multiple times -on the same file without waiting for the promise to be resolved or rejected. - - - - - - - - -
- - -
- - -The fs.Stats object provides information about a file. -The object is returned from -fs.statSync() and -fs.lstatSync(). - - - - -stats.isBlockDevice()—returns -true if the fs.Stats object describes -a block device. - - - -stats.isDirectory()—returns -true if the fs.Stats object describes -a file system directory. - - - -stats.isFIFO()—returns -true if the fs.Stats object describes -a first-in-first-out (FIFO) pipe. - - - -stats.isFile()—returns -true if the fs.Stats object describes -a regular file. - - - -stats.isSocket()—returns -true if the fs.Stats object describes -a socket. - - - -stats.isSymbolicLink()—returns -true if the fs.Stats object describes -a symbolic link. - - - -stats.dev— -the numeric identifier of the device containing the file. - - - -stats.ino— -the file system specific Inode number for the file. - - - -stats.mode— -a bit-field describing the file type and mode. - - - -stats.nlink— -the number of hard-links that exist for the file. - - - -stats.uid— -the numeric user identifier of the user that owns the file (POSIX). - - - -stats.gid— -the numeric group identifier of the group that owns the file (POSIX). - - - -stats.rdev— -the numeric device identifier if the file represents a device. - - - -stats.size— -the size of the file in bytes. - - - -stats.blksize— -the file system block size for i/o operations. - - - -stats.blocks— -the number of blocks allocated for this file. - - - -stats.atimeMs— -the timestamp indicating the last time this file was accessed expressed -in milliseconds since the POSIX Epoch. - - - -stats.mtimeMs— -the timestamp indicating the last time this file was modified expressed -in milliseconds since the POSIX Epoch. - - - -stats.ctimeMs— -the timestamp indicating the last time this file was changed expressed -in milliseconds since the POSIX Epoch. - - - -stats.birthtimeMs— -the timestamp indicating the creation time of this file expressed -in milliseconds since the POSIX Epoch. - - - -stats.atime— -the timestamp indicating the last time this file was accessed. - - - -stats.mtime— -the timestamp indicating the last time this file was modified. - - - -stats.ctime— -the timestamp indicating the last time this file was changed. - - - -stats.birthtime— -the timestamp indicating the creation time of this file. - - - - - -
- - -
- - -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 - - - - - -
- -
- - -
- - - - - - - - - -
querystring.decode()
querystring.encode()
querystring.escape()
querystring.parse()
querystring.stringify()
querystring.unescape()
-
- - -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() - -is an alias for -querystring.parse(). - - -querystring.encode() - -is an alias for -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 - -Function used -to decode percent-encoded characters in the query string, -by default is -querystring.unescape() - - -maxKeys -number - -the maximum number of keys to parse, -by default is 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 - -The function to use when converting -URL-unsafe characters to percent-encoding in the query string, -by default is -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. - - - - - - -
- - -
- - - - - - - - - - - -
xml.parse()
xml.c14n()
xml.exclusiveC14n()
xml.serialize()
xml.serializeToString()
XMLDoc
XMLNode
XMLAttr
-
- - -The XML module allows working with XML documents -(since 0.7.10). -The XML module object is returned by -require('xml'). - - - -Example: - -const xml = require("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) - -Parses a string or Buffer for an XML document, -returns an -XMLDoc wrapper object -representing the parsed XML document. - - -c14n(root_node[, -excluding_node]) - -Canonicalizes 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_node - -allows omitting from the output a part of the document - - - - - - - -exclusiveC14n(root_node[, -excluding_node[, -withComments -[,prefix_list]]]) - -Canonicalizes root_node and its children according to -Exclusive XML -Canonicalization Version 1.0. - - - - -root_node - -is -XMLNode or -XMLDoc wrapper object -around XML structure - - -excluding_node - -allows omitting from the output a part of the document -corresponding to the node and its children - - -withComments - -a boolean value, false by default. -If true, canonicalization corresponds to -Exclusive XML -Canonicalization Version 1.0. -Returns Buffer object that contains canonicalized output. - - -prefix_list - -an optional string with a space separated namespace prefixes -for namespaces that should also be included into the output - - - - - - - -serialize() - -The same as -xml.c14n() -(since 0.7.11). - - -serializeToString() - -The same as -xml.c14n() -except it returns the result as a string -(since 0.7.11). - - -XMLDoc - -An XMLDoc wrapper object around XML structure, -the root node of the document. - - - - -doc.$root - -the document's root by its name or undefined - - -doc.abc - -the first root tag named abc as -XMLNode wrapper object - - - - - - - -XMLNode - -An XMLNode wrapper object around XML tag node. - - - -node.abc - -the same as -node.$tag$abc - - -node.$attr$abc - -the node's attribute value of abc, -writable -since 0.7.11 - - -node.$attr$abc=xyz - -the same as -node.setAttribute('abc', -xyz) -(since 0.7.11) - - -node.$attrs - -an XMLAttr wrapper object -for all attributes of the node - - -node.$name - -the name of the node - - -node.$ns - -the namespace of the node - - -node.$parent - -the parent node of the current node - - -node.$tag$abc - -the first child tag of the node named abc, -writable -since 0.7.11 - - -node.$tags - -an array of all children tags - - -node.$tags = [node1, node2, ...] - -the same as -node.removeChildren(); -node.addChild(node1); -node.addChild(node2) -(since 0.7.11). - - -node.$tags$abc - -all children tags named abc of the node, -writable -since 0.7.11 - - -node.$text - -the content of the node, -writable -since 0.7.11 - - -node.$text = 'abc' - -the same as -node.setText('abc') -(since 0.7.11) - - -node.addChild(nd) - -adds XMLNode as a child to node -(since 0.7.11). -nd is recursively copied before adding to the node - - -node.removeAllAttributes() - -removes all attributes of the node -(since 0.7.11) - - -node.removeAttribute(attr_name) - -removes the attribute named attr_name -(since 0.7.11) - - -node.removeChildren(tag_name) - -removes all the children tags named tag_name -(since 0.7.11). -If tag_name is absent, all children tags are removed - - -node.removeText() - -removes the node's text value -(0.7.11) - - -node.setAttribute(attr_name, -value) - -sets a value for an attr_name -(since 0.7.11). -When the value is null, -the attribute named attr_name is deleted - - -node.setText(value) - -sets a text value for the node -(since 0.7.11). -When the value is null, the text of the node is deleted. - - - - - - - -XMLAttr - -An XMLAttrs wrapper object around XML node attributes. - - - - -attr.abc - -the attribute value of abc - - - - - - - - - - -
- - -
- - - - - - - -
zlib.deflateRawSync()
zlib.deflateSync()
zlib.inflateRawSync()
zlib.inflateSync()
-
- - -The zlib module provides compression functionality using the -“deflate” and “inflate” algorithms -(since 0.7.12). -The zlib module object is returned by -require('zlib'). - - - - - -deflateRawSync(string | -Buffer[, -options]) - -Compresses data using the “deflate” algorithm provided as a string or Buffer -and does not append a zlib header. -The buffer value can be a -Buffer, -TypedArray, or -DataView. -Options is an optional object that contains -. -Returns Buffer instance that contains the compressed data. - - -deflateSync(string | -Buffer[, -options]) - -Compresses data using the “deflate” algorithm provided as a string or Buffer. -The Buffer value can be a -Buffer, -TypedArray, or -DataView. -Options is an optional object that contains -. -Returns Buffer instance that contains the compressed data. - - -inflateRawSync(string | -Buffer) - -Decompresses a raw stream by using the “deflate” algorithm. -Returns Buffer instance that contains the decompressed data. - - -inflateSync(string | -Buffer) - -Decompresses a stream by using the “deflate” algorithm. -Returns Buffer instance that contains the decompressed data. - - - - - - -
- - - - - -chunkSize—is an integer, -by default is 1024 - - - -dictionary—is a -Buffer, -TypedArray, or -DataView. -by default is empty - - - -level—is an integer, compression only, -see - - - -memLevel—is an integer -from 1 to 9, compression only - - - -strategy—is an integer, compression only, -see - - - -windowBits—is an integer -from -15 to -9 -for raw data, -from 9 to 15 -for an ordinary stream - - - - - -
- -
- - - - - - - - -
NameDescription
zlib.constants.Z_NO_COMPRESSIONno compression
zlib.constants.Z_BEST_SPEEDfastest, produces the least compression
zlib.constants.Z_DEFAULT_COMPRESSIONtrade-off between speed and compression
zlib.constants.Z_BEST_COMPRESSIONslowest, produces the most compression
-
- -
- -
- - - - - - - - - -
NameDescription
zlib.constants.Z_FILTEREDFiltered strategy: for the data produced by a filter or predictor
zlib.constants.Z_HUFFMAN_ONLYHuffman-only strategy: only Huffman encoding, no string matching
zlib.constants.Z_RLERun Length Encoding strategy: limit match distances to one, better compression of PNG image data
zlib.constants.Z_FIXEDFixed table strategy: prevents the use of dynamic Huffman codes, a simpler decoder for special applications
zlib.constants.Z_DEFAULT_STRATEGYDefault strategy, suitable for general purpose compression
-
- -
- -
- -
- -
diff --git a/xml/en/docs/njs/security.xml b/xml/en/docs/njs/security.xml deleted file mode 100644 --- a/xml/en/docs/njs/security.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - -
- -
- - -All njs security issues should be reported to -security-alert@nginx.org. - - - -Patches are signed using one of the -PGP public keys. - - -
- - -
- - -njs does not evaluate dynamic code -and especially the code received from the network in any way. -The only way to evaluate that code using njs -is to configure the -js_import -directive in nginx. -JavaScript code is loaded once during nginx start. - - - -In nginx/njs threat model, JavaScript code is considered a trusted source -in the same way as nginx.conf and sites certificates. -What this means in practice: - - - - -memory disclosure and other security issues -triggered by JavaScript code modification -are not considered security issues, but as ordinary bugs - - - -measures should be taking for protecting JavaScript code used by njs - - - -if no js_import -directives are present in nginx.conf, -nginx is safe from JavaScript-related vulnerabilities - - - - - -
- - -
diff --git a/xml/en/docs/njs/typescript.xml b/xml/en/docs/njs/typescript.xml deleted file mode 100644 --- a/xml/en/docs/njs/typescript.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - -
- -
- - -TypeScript is -a typed superset of JavaScript -that compiles to plain JavaScript. - - - -TypeScript supports definition files that contain -type information of existing JavaScript libraries. -This enables other programs to use the values defined in the files -as if they were statically typed TypeScript entities. - - - -njs provides TypeScript definition files for its -API which can be used to: - - - -Get autocompletion and API check in an editor - - - -Write njs type-safe code - - - - - -
- - -
- - - -$ hg clone http://hg.nginx.org/njs -$ cd njs && ./configure && make ts -$ ls build/ts/ -njs_core.d.ts -njs_shell.d.ts -ngx_http_js_module.d.ts -ngx_stream_js_module.d.ts - - - -
- - -
- - -Put *.d.ts files to a place where you editor can find it. - - - -test.js: - -/// <reference path="ngx_http_js_module.d.ts" /> -/** - * @param {NginxHTTPRequest} r - * */ -function content_handler(r) { - r.headersOut['content-type'] = 'text/plain'; - r.return(200, "Hello"); -} - - - -
- - -
- - -test.ts: - -/// <reference path="ngx_http_js_module.d.ts" /> -function content_handler(r: NginxHTTPRequest) { - r.headersOut['content-type'] = 'text/plain'; - r.return(200, "Hello from TypeScript"); -} - -TypeScript installation: - -# npm install -g typescript - -TypeScript compilation: - -$ tsc test.ts -$ cat test.js - -The resulting test.js file can be used directly with njs. - - -
- - -
diff --git a/xml/en/docs/stream/ngx_stream_js_module.xml b/xml/en/docs/stream/ngx_stream_js_module.xml deleted file mode 100644 --- a/xml/en/docs/stream/ngx_stream_js_module.xml +++ /dev/null @@ -1,793 +0,0 @@ - - - - - - - - -
- - -The ngx_stream_js_module module is used to implement -handlers in njs — -a subset of the JavaScript language. - - - -Download and install instructions are available -here. - - -
- - -
- - -The example works since -0.4.0. - -stream { - js_import stream.js; - - js_set $bar stream.bar; - js_set $req_line stream.req_line; - - server { - listen 12345; - - js_preread stream.preread; - return $req_line; - } - - server { - listen 12346; - - js_access stream.access; - proxy_pass 127.0.0.1:8000; - js_filter stream.header_inject; - } -} - -http { - server { - listen 8000; - location / { - return 200 $http_foo\n; - } - } -} - - - - -The stream.js file: - -var line = ''; - -function bar(s) { - var v = s.variables; - s.log("hello from bar() handler!"); - return "bar-var" + v.remote_port + "; pid=" + v.pid; -} - -function preread(s) { - s.on('upload', function (data, flags) { - var n = data.indexOf('\n'); - if (n != -1) { - line = data.substr(0, n); - s.done(); - } - }); -} - -function req_line(s) { - return line; -} - -// Read HTTP request line. -// Collect bytes in 'req' until -// request line is read. -// Injects HTTP header into a client's request - -var my_header = 'Foo: foo'; -function header_inject(s) { - var req = ''; - s.on('upload', function(data, flags) { - req += data; - var n = req.search('\n'); - if (n != -1) { - var rest = req.substr(n + 1); - req = req.substr(0, n + 1); - s.send(req + my_header + '\r\n' + rest, flags); - s.off('upload'); - } - }); -} - -function access(s) { - if (s.remoteAddress.match('^192.*')) { - s.deny(); - return; - } - - s.allow(); -} - -export default {bar, preread, req_line, header_inject, access}; - - - -
- - -
- - -function | module.function - -stream -server - - -Sets an njs function which will be called at the -access phase. -Since 0.4.0, -a module function can be referenced. - - - -The function is called once at the moment when the stream session reaches -the access phase -for the first time. -The function is called with the following arguments: - - -s - -the Stream Session object - - - - - - -At this phase, it is possible to perform initialization -or register a callback with -the s.on() -method -for each incoming data chunk until one of the following methods are called: -s.allow(), -s.decline(), -s.done(). -As soon as one of these methods is called, the stream session processing -switches to the next phase -and all current -s.on() -callbacks are dropped. - - - - - - -size -16k -stream -server -0.7.4 - - -Sets the size of the buffer used for reading and writing -with Fetch API. - - - - - - -ciphers -HIGH:!aNULL:!MD5 -stream -server -0.7.0 - - -Specifies the enabled ciphers for HTTPS connections -with Fetch API. -The ciphers are specified in the format understood by the OpenSSL library. - - - -The full list can be viewed using the -“openssl ciphers” command. - - - - - - -size -1m -stream -server -0.7.4 - - -Sets the maximum size of the response received -with Fetch API. - - - - - - - - [TLSv1] - [TLSv1.1] - [TLSv1.2] - [TLSv1.3] -TLSv1 TLSv1.1 TLSv1.2 -stream -server -0.7.0 - - -Enables the specified protocols for HTTPS connections -with Fetch API. - - - - - - -time -60s -stream -server -0.7.4 - - -Defines a timeout for reading and writing -for Fetch API. -The timeout is set only between two successive read/write operations, -not for the whole response. -If no data is transmitted within this time, the connection is closed. - - - - - - -file - -stream -server -0.7.0 - - -Specifies a file with trusted CA certificates in the PEM format -used to -verify -the HTTPS certificate -with Fetch API. - - - - - - -on | off -on -stream -server -0.7.4 - - -Enables or disables verification of the HTTPS server certificate -with Fetch API. - - - - - - -number -100 -stream -server -0.7.0 - - -Sets the verification depth in the HTTPS server certificates chain -with Fetch API. - - - - - - -function | module.function - -stream -server - - -Sets a data filter. -Since 0.4.0, -a module function can be referenced. -The filter function is called once at the moment when the stream session reaches -the content phase. - - - -The filter function is called with the following arguments: - -s - -the Stream Session object - - - - - - -At this phase, it is possible to perform initialization -or register a callback with -the s.on() -method for each incoming data chunk. -The -s.off() -method may be used to unregister a callback and stop filtering. - - - - -As the js_filter handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -ngx.fetch() -or -setTimeout() -are not supported. - - - - - - - -module.js | -export_name from module.js - -stream -server -0.4.0 - - -Imports a module that implements location and variable handlers in njs. -The export_name is used as a namespace -to access module functions. -If the export_name is not specified, -the module name will be used as a namespace. - -js_import stream.js; - -Here, the module name stream is used as a namespace -while accessing exports. -If the imported module exports foo(), -stream.foo is used to refer to it. - - - -Several js_import directives can be specified. - - - - -The directive can be specified on the -server level -since 0.7.7. - - - - - - - -file - -stream - - -Specifies a file that implements server and variable handlers in njs: - -nginx.conf: -js_include stream.js; -js_set $js_addr address; -server { - listen 127.0.0.1:12345; - return $js_addr; -} - -stream.js: -function address(s) { - return s.remoteAddress; -} - - - - -The directive was made obsolete in version -0.4.0 -and was removed in version -0.7.1. -The directive should be used instead. - - - - - - - -path - -stream -server -0.3.0 - - -Sets an additional path for njs modules. - - - - -The directive can be specified on the -server level -since 0.7.7. - - - - - - - -function | - module.function - [interval=time] - [jitter=number] - [worker_affinity=mask] - -server -0.8.1 - - -Specifies a content handler to run at regular interval. -The handler receives a -session object -as its first argument, -it also has access to global objects such as -ngx. - - - -The optional interval parameter -sets the interval between two consecutive runs, -by default, 5 seconds. - - - -The optional jitter parameter sets the time within which -the location content handler will be randomly delayed, -by default, there is no delay. - - - -By default, the js_handler is executed on worker process 0. -The optional worker_affinity parameter -allows specifying particular worker processes -where the location content handler should be executed. -Each worker process set is represented by a bitmask of allowed worker processes. -The all mask allows the handler to be executed -in all worker processes. - - - -Example: - -example.conf: - -location @periodics { - # to be run at 1 minute intervals in worker process 0 - js_periodic main.handler interval=60s; - - # to be run at 1 minute intervals in all worker processes - js_periodic main.handler interval=60s worker_affinity=all; - - # to be run at 1 minute intervals in worker processes 1 and 3 - js_periodic main.handler interval=60s worker_affinity=0101; - - resolver 10.0.0.1; - js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; -} - -example.js: - -async function handler(s) { - let reply = await ngx.fetch('https://nginx.org/en/docs/njs/'); - let body = await reply.text(); - - ngx.log(ngx.INFO, body); -} - - - - - - - -name.json | -name from file.json - -stream -server -0.7.8 - - -Preloads an -immutable object -at configure time. -The name is used as a name of the global variable -though which the object is available in njs code. -If the name is not specified, -the file name will be used instead. - -js_preload_object map.json; - -Here, the map is used as a name -while accessing the preloaded object. - - - -Several js_preload_object directives can be specified. - - - - - - -function | module.function - -stream -server - - -Sets an njs function which will be called at the -preread phase. -Since 0.4.0, -a module function can be referenced. - - - -The function is called once -at the moment when the stream session reaches the -preread phase -for the first time. -The function is called with the following arguments: - - -s - -the Stream Session object - - - - - - -At this phase, it is possible to perform initialization -or register a callback with -the s.on() -method -for each incoming data chunk until one of the following methods are called: -s.allow(), -s.decline(), -s.done(). -When one of these methods is called, -the stream session switches to the -next phase -and all current -s.on() -callbacks are dropped. - - - - -As the js_preread handler -returns its result immediately, it supports -only synchronous callbacks. -Thus, asynchronous callbacks such as -ngx.fetch() -or -setTimeout() -are not supported. -Nevertheless, asynchronous operations are supported in -s.on() -callbacks in the -preread phase. -See -this example for more information. - - - - - - - - -$variable function | -module.function - -stream -server - - -Sets an njs function -for the specified variable. -Since 0.4.0, -a module function can be referenced. - - - -The function is called when -the variable is referenced for the first time for a given request. -The exact moment depends on a -phase -at which the variable is referenced. -This can be used to perform some logic -not related to variable evaluation. -For example, if the variable is referenced only in the - directive, -its handler will not be executed until the log phase. -This handler can be used to do some cleanup -right before the request is freed. - - - - -As the js_set handler -returns its result immediately, it supports -only synchronous callbacks. -Thus, asynchronous callbacks such as -ngx.fetch() -or -setTimeout() -are not supported. - - - - - -The directive can be specified on the -server level -since 0.7.7. - - - - - - - - - zone=name:size - [timeout=time] - [type=string|number] - [evict] - -stream -0.8.0 - - -Sets the name and size of the shared memory zone -that keeps the -key-value dictionary -shared between worker processes. - - - -By default the shared dictionary uses a string as a key and a value. -The optional type parameter -allows redefining the value type to number. - - - -The optional timeout parameter sets -the time after which all shared dictionary entries are removed from the zone. - - - -The optional evict parameter removes the oldest -key-value pair when the zone storage is exhausted. - - - -Example: - -example.conf: - # Creates a 1Mb dictionary with string values, - # removes key-value pairs after 60 seconds of inactivity: - js_shared_dict_zone zone=foo:1M timeout=60s; - - # Creates a 512Kb dictionary with string values, - # forcibly removes oldest key-value pairs when the zone is exhausted: - js_shared_dict_zone zone=bar:512K timeout=30s evict; - - # Creates a 32Kb permanent dictionary with number values: - js_shared_dict_zone zone=num:32k type=number; - -example.js: - function get(r) { - r.return(200, ngx.shared.foo.get(r.args.key)); - } - - function set(r) { - r.return(200, ngx.shared.foo.set(r.args.key, r.args.value)); - } - - function del(r) { - r.return(200, ngx.shared.bar.delete(r.args.key)); - } - - function increment(r) { - r.return(200, ngx.shared.num.incr(r.args.key, 2)); - } - - - - - - - -$variable [value] - -stream -server -0.5.3 - - -Declares -a writable -variable. -The value can contain text, variables, and their combination. - - - - -The directive can be specified on the -server level -since 0.7.7. - - - - - -
- - -
- - -Each stream njs handler receives one argument, a stream session -object. - - -
- -
diff --git a/xml/en/index.xml b/xml/en/index.xml --- a/xml/en/index.xml +++ b/xml/en/index.xml @@ -8,7 +8,7 @@
+ rev="163">
@@ -204,11 +204,7 @@ coming from one address; -Embedded Perl; - - - -njs scripting language. +Embedded Perl. @@ -330,11 +326,7 @@ log writing, -A/B testing; - - - -njs scripting language. +A/B testing. diff --git a/xml/ru/GNUmakefile b/xml/ru/GNUmakefile --- a/xml/ru/GNUmakefile +++ b/xml/ru/GNUmakefile @@ -47,7 +47,6 @@ REFS = \ http/ngx_http_headers_module \ http/ngx_http_image_filter_module \ http/ngx_http_index_module \ - http/ngx_http_js_module \ http/ngx_http_limit_conn_module \ http/ngx_http_limit_req_module \ http/ngx_http_limit_zone_module \ @@ -89,7 +88,6 @@ REFS = \ stream/ngx_stream_core_module \ stream/ngx_stream_geo_module \ stream/ngx_stream_geoip_module \ - stream/ngx_stream_js_module \ stream/ngx_stream_limit_conn_module \ stream/ngx_stream_log_module \ stream/ngx_stream_map_module \ @@ -103,13 +101,6 @@ REFS = \ stream/ngx_stream_upstream_module \ stream/stream_processing \ ngx_google_perftools_module \ - njs/index \ - njs/cli \ - njs/compatibility \ - njs/install \ - njs/node_modules \ - njs/preload_objects \ - njs/typescript \ TOP = \ download \ diff --git a/xml/ru/docs/http/ngx_http_js_module.xml b/xml/ru/docs/http/ngx_http_js_module.xml deleted file mode 100644 --- a/xml/ru/docs/http/ngx_http_js_module.xml +++ /dev/null @@ -1,814 +0,0 @@ - - - - - - - - -
- - -Модуль ngx_http_js_module позволяет задавать -обработчики location и переменных -на njs — -подмножестве языка JavaScript. - - - -Инструкция по сборке и установке доступны -здесь. - - -
- - -
- - -Пример работает начиная с версии -0.4.0. - -http { - js_import http.js; - - js_set $foo http.foo; - js_set $summary http.summary; - js_set $hash http.hash; - - resolver 10.0.0.1; - - server { - listen 8000; - - location / { - add_header X-Foo $foo; - js_content http.baz; - } - - location = /summary { - return 200 $summary; - } - - location = /hello { - js_content http.hello; - } - - # начиная с версии 0.7.0 - location = /fetch { - js_content http.fetch; - js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; - } - - # начиная с версии 0.7.0 - location = /crypto { - add_header Hash $hash; - return 200; - } - } -} - - - - -Файл http.js: - -function foo(r) { - r.log("hello from foo() handler"); - return "foo"; -} - -function summary(r) { - var a, s, h; - - s = "JS summary\n\n"; - - s += "Method: " + r.method + "\n"; - s += "HTTP version: " + r.httpVersion + "\n"; - s += "Host: " + r.headersIn.host + "\n"; - s += "Remote Address: " + r.remoteAddress + "\n"; - s += "URI: " + r.uri + "\n"; - - s += "Headers:\n"; - for (h in r.headersIn) { - s += " header '" + h + "' is '" + r.headersIn[h] + "'\n"; - } - - s += "Args:\n"; - for (a in r.args) { - s += " arg '" + a + "' is '" + r.args[a] + "'\n"; - } - - return s; -} - -function baz(r) { - r.status = 200; - r.headersOut.foo = 1234; - r.headersOut['Content-Type'] = "text/plain; charset=utf-8"; - r.headersOut['Content-Length'] = 15; - r.sendHeader(); - r.send("nginx"); - r.send("java"); - r.send("script"); - - r.finish(); -} - -function hello(r) { - r.return(200, "Hello world!"); -} - -// начиная с версии 0.7.0 -async function fetch(r) { - let results = await Promise.all([ngx.fetch('https://nginx.org/'), - ngx.fetch('https://nginx.org/en/')]); - - r.return(200, JSON.stringify(results, undefined, 4)); -} - -// начиная с версии 0.7.0 -async function hash(r) { - let hash = await crypto.subtle.digest('SHA-512', r.headersIn.host); - r.setReturnValue(Buffer.from(hash).toString('hex')); -} - -export default {foo, summary, baz, hello, fetch, hash}; - - - -
- - -
- - -функция | модуль.функция -[buffer_type=строка | буфер] - -location -if in location -limit_except -0.5.2 - - -Задаёт функцию njs в качестве фильтра тела ответа. -Функция фильтра вызывается для каждого блока данных тела ответа -со следующими аргументами: - - -r - -объект HTTP request - - -data - -входящий блок данных -может быть строкой или буфером -в зависимости от значения buffer_type, -по умолчанию является строкой. - - -flags - -объект со следующими свойствами: - -last - -логическое значение, true, если данные являются последним буфером. - - - - - - - - - -Функция фильтра может передавать свою модифицированную версию -входящего блока данных следующему фильтру тела ответа при помощи вызова -r.sendBuffer(). -Пример преобразования букв в нижний регистр в теле ответа: - -function filter(r, data, flags) { - r.sendBuffer(data.toLowerCase(), flags); -} - -Для отмены фильтра (блоки данных будут передаваться клиенту -без вызова js_body_filter), -можно использовать -r.done(). - - - -Если функция фильтра изменяет длину тела ответа, то -необходимо очистить заголовок ответа
Content-Length
-(если присутствует) в -js_header_filter, -чтобы применить поблочное кодирование. -
- - - -Так как обработчик js_body_filter -должен сразу возвращать результат, -то поддерживаются только синхронные операции, -Таким образом, асинхронные операции, например -r.subrequest() -или -setTimeout(), -не поддерживаются. - - - - - -Директива может быть указана внутри -блока if -начиная с 0.7.7. - - - -
- - - -функция | модуль.функция - -location -if in location -limit_except - - -Задаёт функцию njs в качестве обработчика содержимого location. -Начиная с версии 0.4.0 -можно ссылаться на функцию модуля. - - - - -Директива может быть указана внутри -блока if -начиная с 0.7.7. - - - - - - - -размер -16k -http -server -location -0.7.4 - - -Задаёт размер буфера, который будет использоваться -для чтения и записи для -Fetch API. - - - - - - -шифры -HIGH:!aNULL:!MD5 -http -server -location -0.7.0 - - -Описывает разрешённые шифры для HTTPS-запросов -при помощи Fetch API. -Шифры задаются в формате, поддерживаемом библиотекой OpenSSL. - - - -Полный список можно посмотреть с помощью команды -“openssl ciphers”. - - - - - - -размер -1m -http -server -location -0.7.4 - - -Задаёт максимальный размер ответа, полученного -при помощи Fetch API. - - - - - - - - [TLSv1] - [TLSv1.1] - [TLSv1.2] - [TLSv1.3] -TLSv1 TLSv1.1 TLSv1.2 -http -server -location -0.7.0 - - -Разрешает указанные протоколы для HTTPS-запросов -при помощи Fetch API. - - - - - - -время -60s -http -server -location -0.7.4 - - -Задаёт таймаут при чтении и записи -при помощи Fetch API. -Таймаут устанавливается не на всю передачу ответа, -а только между двумя операциями чтения. -Если по истечении этого времени данные не передавались, соединение закрывается. - - - - - - -файл - -http -server -location -0.7.0 - - -Задаёт файл с доверенными сертификатами CA в формате PEM, -используемыми при -проверке -HTTPS-сертификата -при помощи Fetch API. - - - - - - -on | off -on -http -server -location -0.7.4 - - -Разрешает или запрещает проверку сертификата HTTPS-сервера -при помощи Fetch API. - - - - - - -число -100 -http -server -location -0.7.0 - - -Устанавливает глубину проверки в цепочке HTTPS-сертификатов -при помощи Fetch API. - - - - - - -функция | модуль.функция - -location -if in location -limit_except -0.5.1 - - -Задаёт функцию njs в качестве фильтра заголовка ответа. -Директива позволяет менять произвольные поля заголовка ответа. - - - - -Так как обработчик js_header_filter -должен сразу возвращать результат, -то поддерживаются только синхронные операции, -Таким образом, асинхронные операции, например -r.subrequest() -или -setTimeout(), -не поддерживаются. - - - - - -Директива может быть указана внутри -блока if -начиная с 0.7.7. - - - - - - - -модуль.js | -имя_экспорта from модуль.js - -http -server -location -0.4.0 - - -Импортирует модуль, позволяющий задавать обработчики location и переменных -на njs. -Имя_экспорта является пространством имён -при доступе к функциям модуля. -Если имя_экспорта не задано, -то пространством имён будет являться имя модуля. - -js_import http.js; - -В примере при доступе к экспорту в качестве -пространства имён используется имя модуля http. -Если импортируемый модуль экспортирует foo(), -то для доступа используется http.foo. - - - -Директив js_import может быть несколько. - - - - -Директива может быть указана -на уровне server и location -начиная с 0.7.7. - - - - - - - -файл - -http - - -Задаёт файл, позволяющий задавать обработчики location и переменных на njs: - -nginx.conf: -js_include http.js; -location /version { - js_content version; -} - -http.js: -function version(r) { - r.return(200, njs.version); -} - - - - -Директива устарела в версии -0.4.0 -и была удалена в версии -0.7.1. -Вместо неё следует использовать директиву . - - - - - - - -путь - -http -server -location -0.3.0 - - -Задаёт дополнительный путь для модулей njs. - - - - -Директива может быть указана -на уровне server и location -начиная с 0.7.7. - - - - - - - -функция | - модуль.функция - [interval=время] - [jitter=число] - [worker_affinity=маска] - -location -0.8.1 - - -Задаёт периодичность запуска обработчика содержимого. -В качестве первого аргумента обработчик получает -объект сессии, -также у обработчика есть доступ к глобальным объектам таким как -ngx. - - - -Необязательный параметр interval -задаёт интервал между двумя последовательными запусками, -по умолчанию 5 секунд. - - - -Необязательный параметр jitter -задаёт время, в пределах которого -случайным образом задерживается каждый запуск, -по умолчанию задержки нет. - - - -По умолчанию js_handler выполняется для рабочего процесса 0. -Необязательный параметр worker_affinity -позволяет указать рабочий процесс, -для которого будет выполняться обработчик содержимого location. -Рабочие процессы задаются битовой маской разрешённых к использованию рабочих -процессов. -Маска all позволяет обработчику выполняться -для всех рабочих процессов. - - - -Пример: - -example.conf: - -location @periodics { - # интервал выполнения 1 минута для рабочего процесса 0 - js_periodic main.handler interval=60s; - - # интервал выполнения 1 минута для всех рабочих процессов - js_periodic main.handler interval=60s worker_affinity=all; - - # интервал выполнения 1 минута для рабочих процессов 1 и 3 - js_periodic main.handler interval=60s worker_affinity=0101; - - resolver 10.0.0.1; - js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; -} - -example.js: - -async function handler(s) { - let reply = await ngx.fetch('https://nginx.org/en/docs/njs/'); - let body = await reply.text(); - - ngx.log(ngx.INFO, body); -} - - - - - - - -имя.json | -имя from файл.json - -http -server -location -0.7.8 - - -Предварительно загружает -неизменяемый объект -во время конфигурации. -Имя используется в качестве имени глобальной переменной, -через которую объект доступен в коде njs. -Если имя не указано, -то будет использоваться имя файла. - -js_preload_object map.json; - -В примере map используется в качестве имени -во время доступа к предварительно загруженному объекту. - - - -Директив js_preload_object может быть несколько. - - - - - - - -$переменная функция | -модуль.функция - -http -server -location - - -Задаёт функцию njs -для указанной переменной. -Начиная с 0.4.0 -можно ссылаться на функцию модуля. - - - -Функция вызывается в момент -первого обращения к переменной для данного запроса. -Точный момент вызова функции зависит от -фазы, -в которой происходит обращение к переменной. -Это можно использовать для реализации дополнительной логики, -не относящейся к вычислению переменной. -Например, если переменная указана -в директиве , -то её обработчик не будет выполняться до фазы записи в лог. -Этот обработчик также может использоваться для выполнения процедур -непосредственно перед освобождением запроса. - - - - -Так как обработчик js_set -должен сразу возвращать результат, -то поддерживаются только синхронные операции, -Таким образом, асинхронные операции, например -r.subrequest() -или -setTimeout(), -не поддерживаются. - - - - - -Директива может быть указана -на уровне server и location -начиная с 0.7.7. - - - - - - - - - zone=имя:размер - [timeout=время] - [type=строка|число] - [evict] - -http -0.8.0 - - -Задаёт имя и размер зоны разделяемой памяти, -в которой хранится -словарь ключей и значений, -разделяемый между рабочими процессами. - - - -По умолчанию в качестве ключа и значения используется строка. -Необязательный параметр type -позволяет изменить тип значения на число. - - - -Необязательный параметр timeout задаёт время, -по завершении которого все записи в словаре удаляются из зоны. - - - -Необязательный параметр evict удаляет самую старую -пару ключ-значение при переполнении зоны. - - - -Пример: - -example.conf: - # Создаётся словарь размером 1Мб со строковыми значениями, - # пары ключ-значение удаляются при отсутствии активности в течение 60 секунд: - js_shared_dict_zone zone=foo:1M timeout=60s; - - # Создаётся словарь размером 512Кб со строковыми значениями, - # удаляется самая старая пара ключ-значение при переполнении зоны: - js_shared_dict_zone zone=bar:512K timeout=30s evict; - - # Создаётся постоянный словарь размером 32Кб с числовыми значениями: - js_shared_dict_zone zone=num:32k type=number; - -example.js: - function get(r) { - r.return(200, ngx.shared.foo.get(r.args.key)); - } - - function set(r) { - r.return(200, ngx.shared.foo.set(r.args.key, r.args.value)); - } - - function del(r) { - r.return(200, ngx.shared.bar.delete(r.args.key)); - } - - function increment(r) { - r.return(200, ngx.shared.num.incr(r.args.key, 2)); - } - - - - - - - -$переменная [значение] - -http -server -location -0.5.3 - - -Объявляет -перезаписываемую -переменную. -В качестве значения можно использовать текст, переменные и их комбинации. -Переменная не перезаписывается после перенаправления, -в отличие от переменных, созданных при помощи -директивы . - - - - -Директива может быть указана -на уровне server и location -начиная с 0.7.7. - - - - - -
- - -
- - -Каждый HTTP-обработчик njs получает один аргумент, -объект запроса. - - -
- -
diff --git a/xml/ru/docs/index.xml b/xml/ru/docs/index.xml --- a/xml/ru/docs/index.xml +++ b/xml/ru/docs/index.xml @@ -8,7 +8,7 @@
@@ -99,14 +99,6 @@ -Создание сценариев на njs - - - - - - - Глава “nginx” из книги “The Architecture of Open Source Applications” [en] @@ -306,11 +298,6 @@ ngx_http_index_module - -ngx_http_js_module - - - ngx_http_limit_conn_module @@ -519,11 +506,6 @@ ngx_stream_geoip_module - -ngx_stream_js_module - - - ngx_stream_limit_conn_module diff --git a/xml/ru/docs/njs/cli.xml b/xml/ru/docs/njs/cli.xml deleted file mode 100644 --- a/xml/ru/docs/njs/cli.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - -
- -
- -Создание и отладка njs-скриптов может осуществляться -в командной строке. -Утилита командной строки доступна после установки -пакета Linux -или после сборки из -исходных файлов. -В отличие от njs, запущенном внутри nginx, -в утилите недоступны объекты nginx -(HTTP и -Stream). - -$ echo "2**3" | njs -q -8 - -$ njs ->> globalThis -global { - njs: njs { - version: '0.3.9' - }, - global: [Circular], - process: process { - argv: [ - '/usr/bin/njs' - ], - env: { - PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - HOSTNAME: 'f777c149d4f8', - TERM: 'xterm', - NGINX_VERSION: '1.17.9', - NJS_VERSION: '0.3.9', - PKG_RELEASE: '1~buster', - HOME: '/root' - } - }, - console: { - log: [Function: native], - dump: [Function: native], - time: [Function: native], - timeEnd: [Function: native] - }, - print: [Function: native] -} ->> - - - -
- -
diff --git a/xml/ru/docs/njs/compatibility.xml b/xml/ru/docs/njs/compatibility.xml deleted file mode 100644 --- a/xml/ru/docs/njs/compatibility.xml +++ /dev/null @@ -1,1265 +0,0 @@ - - - - - - -
- -
- - -njs совместим с -ECMAScript 5.1 -(строгий режим) c некоторыми расширениями -ECMAScript 6 -и позже. -Совместимость находится в стадии развития. - - - -Описания методов и свойств, доступных только в njs -и не соответствующих стандарту ECMAScript, доступны в -справочнике. -Описания методов и свойств njs, -соответствующих стандарту, доступны в -спецификации -ECMAScript. - - -
- - -
- - - - - -Логические значения, числа, строки, объекты, массивы, -функции, конструкторы функций -(0.3.6) -и регулярные выражения - - - -ES5.1 операторы, ES7 операторы возведения в степень - - - -ES5.1 инструкции: -break, -catch, -continue, -do while, -else, -finally, -for, -for in, -if, -return, -switch, -throw, -try, -var, -while, -инструкции меток (labels) (0.2.8) - - - -ES6 инструкции: -let (0.6.0), -const (0.6.0), -async (0.7.0), -await (0.7.0) - - - -Свойства Math: - - - -ES6: -E, -LN10, -LN2, -LOG10E, -LOG2E, -PI, -SQRT1_2, -SQRT2 - - - - - -Методы Math: - - - -ES6: -abs, -acos, -acosh, -asin, -asinh, -atan, -atan2, -atanh, -cbrt, -ceil, -clz32, -cos, -cosh, -exp, -expm1, -floor, -fround, -hypot, -imul, -log, -log10, -log1p, -log2, -max, -min, -pow, -random, -round, -sign, -sin, -sinh, -sqrt, -tan, -tanh, -trunc - - - - - -Свойства Number: - - - -ES6: -EPSILON, -MAX_SAFE_INTEGER, -MAX_VALUE, -MIN_SAFE_INTEGER, -MIN_VALUE, -NEGATIVE_INFINITY, -NaN, -POSITIVE_INFINITY - - - - - - -Методы Number: - - - -ES6: -isFinite, -isInteger, -isNaN, -isSafeInteger, -parseFloat, -parseInt - - - - - - -Методы прототипа Number: - - - -ES6: -toExponential -(0.3.6), -toFixed -(0.3.6), -toPrecision -(0.3.6) - - - - - - -Методы String: - - - -ES5.1: -fromCharCode - - - -ES6: -fromCodePoint - - - - - - -Методы прототипа String: - - - -ES5.1: -charAt, -concat, -indexOf, -lastIndexOf, -match, -replace, -search, -slice, -split, -substr, -substring, -toLowerCase, -trim, -toUpperCase - - - -ES6: -codePointAt, -endsWith, -includes, -repeat, -startsWith - - - -ES8: -padEnd, -padStart - - - -ES9: -trimEnd -(0.3.4), -trimStart -(0.3.4) - - - -ES12: -replaceAll -(0.7.10) - - - - - - - -Методы Object: - - -ES5.1: -create (поддержка без списка свойств), -defineProperties (поддержка дескрипторов доступа -начиная с версии 0.3.3), -defineProperty (поддержка дескрипторов доступа -начиная с версии 0.3.3), -freeze, -getOwnPropertyDescriptor, -getOwnPropertyDescriptors -(0.3.1), -getOwnPropertyNames -(0.3.1), -getPrototypeOf, -isExtensible, -isFrozen, -isSealed, -keys, -preventExtensions, -seal - - - -ES6: -assign -(0.3.7) - - - -ES8: -entries -(0.2.7), -values -(0.2.7) - - - - - - -Методы прототипа Object: - - -ES5.1: -hasOwnProperty, -isPrototypeOf, -(0.3.0), -propertyIsEnumerable, -toString, -valueOf - - - -ES6: -is -(0.3.8), -setPrototypeOf -(0.3.8) - - - - - - -Методы Array: - - -ES5.1: -isArray - - - -ES6: -of - - - -ES13: -from -(0.8.0), - - - - - - -Методы прототипа Array: - - -ES5.1: -concat, -every, -filter, -forEach, -indexOf, -join, -lastIndexOf, -map, -pop, -push, -reduce, -reduceRight, -reverse, -shift, -slice, -some, -sort, -splice, -unshift - - - -ES6: -copyWithin -(0.3.7), -fill, -find, -findIndex - - - -ES7: includes - - - -ES13: -toReversed -(0.8.0), -toSorted -(0.8.0), -toSpliced -(0.8.0) - - - - - - -Методы ArrayBuffer -(0.3.8): - - -ES6: -isView - - - - - - -Методы прототипа ArrayBuffer -(0.3.8): - - -ES6: -slice - - - - - - -Конструкторы Typed-array -(0.3.8): - - -ES6: -Int8Array, -Uint8Array, -Uint8ClampedArray, -Int16Array, -Uint16Array, -Int32Array, -Uint32Array, -Float32Array, -Float64Array - - - - - - -Методы прототипа Typed-array -(0.3.8): - - -ES6: -copyWithin, -every -(0.4.4), -fill, -filter -(0.4.4), -find -(0.4.4), -findIndex -(0.4.4), -forEach -(0.4.4), -includes -(0.4.4), -indexOf -(0.4.4), -join, -lastIndexOf -(0.4.4), -map -(0.4.4), -reduce -(0.4.4), -reduceRight -(0.4.4), -reverse -(0.4.4), -set, -slice, -some -(0.4.4), -sort -(0.4.2), -subarray, -toString - - - -ES13: -toReversed -(0.8.0) -toSorted -(0.8.0) - - - - - - - -Методы Buffer -(0.4.4): - - -alloc, -allocUnsafe, -byteLength, -compare, -concat, -from, -isBuffer, -isEncoding - - - - - - -Методы прототипа Buffer: -(0.4.4): - - -compare, -copy, -equals, -fill, -includes, -indexOf, -lastIndexOf, -readIntBE, -readInt8, -readInt16BE, -readInt32BE, -readIntLE, -readInt8, -readInt16LE, -readInt32LE, -readUIntBE, -readUInt8, -readUInt16BE, -readUInt32BE, -readUIntLE, -readUInt8, -readUInt16LE, -readUInt32LE, -readDoubleBE, -readDoubleLE, -readFloatBE, -readFloatLE, -subarray, -slice, -swap16, -swap32, -swap64, -toJSON, -toString, -write, -writeIntBE, -writeInt8, -writeInt16BE, -writeInt32BE, -writeIntLE, -writeInt8, -writeInt16LE, -writeInt32LE, -writeUIntBE, -writeUInt8, -writeUInt16BE, -writeUInt32BE, -writeUIntLE, -writeUInt8, -writeUInt16LE, -writeUInt32LE, -writeDoubleBE, -writeDoubleLE, -writeFloatBE, -writeFloatLE - - - - - - -Методы Promise -(0.3.8): - - -ES6: -any -(0.6.2), - all -(0.6.2), - allSettled -(0.6.2), -reject, -resolve, -race (0.6.2) - - - - - - -Методы прототипа Promise -(0.3.8): - - -ES6: -catch, -finally, -then - - - - - - -Методы прототипа Function: - - - -ES5.1: -apply, -bind, -call - - - - - - -Свойства аксессоров прототипа RegExp: - - - -flags (0.6.0), -global, -ignoreCase, -multiline, -source, -sticky (0.6.0) - - - - - - -Методы прототипа RegExp: - - - -[@@replace] -(0.4.2), -[@@split] -(0.6.0) - - - -ES5.1: -exec, -test, -toString - - - - - - -Свойства экземпляра RegExp: - - - -lastIndex - - - - - - -RegExp -ES9 именные группы записи (0.3.2) - - - -Методы прототипа DataView -(0.4.4): - - - -ES6: -getFloat32, -getFloat64, -getInt16, -getInt32, -getInt8, -getUint16, -getUint32, -getUint8, -setFloat32, -setFloat64, -setInt16, -setInt32, -setInt8, -setUint16, -setUint32, -setUint8 - - - - - - -Методы Date: - - - -ES5.1: -now, -parse, -UTC - - - - - - -Методы прототипа Date: - - - -ES5.1: -getDate, -getDay, -getFullYear, -getHours, -getMilliseconds, -getMinutes, -getMonth, -getSeconds, -getTime, -getTimezoneOffset, -getUTCDate, -getUTCDay, -getUTCFullYear, -getUTCHours, -getUTCMilliseconds, -getUTCMinutes, -getUTCMonth, -getUTCSeconds, -toDateString, -toISOString, -toLocaleDateString, -toLocaleString, -toLocaleTimeString, -toTimeString, -toUTCString, -setDate, -setFullYear, -setHours, -setMinutes, -setMilliseconds, -setMonth, -setSeconds, -setTime, -setUTCDate, -setUTCFullYear, -setUTCHours, -setUTCMilliseconds, -setUTCMinutes, -setUTCMonth, -setUTCSeconds - - - - - - -Методы JSON: - - - -ES5.1: -parse, -stringify - - - - - - -Методы Symbol -(0.7.6): - - - -for, -keyfor - - - - - - -ES5.1 объект arguments -(0.2.5) - - - -ES6 синтаксис rest параметров (без поддержки деструктуризации) -(0.2.7) - - - -ES5.1 global functions: -decodeURI, -decodeURIComponent, -encodeURI, -encodeURIComponent, -isFinite, -isNaN, -parseFloat, -parseInt - - - -Global functions (0.7.6): -atob, -btoa - - - -Объекты Error: -Error, -EvalError, -InternalError, -RangeError, -ReferenceError, -SyntaxError, -TypeError, -URIError - - - -Функции -clearTimeout -и -setTimeout -(0.2.0) - - - -Методы File system: -fs.accessSync -(0.3.9), -fs.appendFileSync, -fs.closeSync, -fs.existsSync -(0.8.2), -fs.FileHandle -(0.7.7), -fs.fstatSync -(0.7.7), -fs.lstatSync -(0.7.1), -fs.mkdirSync -(0.4.2), -fs.openSync -(0.7.7), -fs.promises.open -(0.7.7), -fs.readdirSync -(0.4.2), -fs.readFileSync, -fs.readSync -(0.7.7), -fs.realpathSync -(0.3.9), -fs.renameSync -(0.3.4), -fs.rmdirSync -(0.4.2), -fs.symlinkSync -(0.3.9), -fs.unlinkSync -(0.3.9), -fs.writeFileSync -fs.writeSync -(0.7.7) - - - -fs.promises API (0.3.9), -асинхронная версия файловых методов file system. - - - -Методы Crypto -(0.2.0): -crypto.createHash, -crypto.createHmac - - - -Методы -Query String -(0.4.3): -querystring.decode, -querystring.encode, -querystring.escape, -querystring.parse, -querystring.stringify, -querystring.unescape - - - -Методы -TextDecoder -(0.4.3): -encoding, -fatal, -ignoreBOM, -decode - - - -Методы -TextEncoder -(0.4.3): -encode, -encodeInto - - - -Методы -XML -(0.7.10): -parse, -xml.c14n, -xml.exclusiveC14n - - - -Методы -zlib -(0.7.12): -deflateRawSync, -deflateSync, -inflateRawSync -inflateSync - - - -ES6 поддержка модулей: -инструкции -export по умолчанию и -import по умолчанию -(0.3.0) - - - -ES6 поддержка стрелочных функций -(0.3.1) - - - -Шаблонные строки: -многострочные литералы, интерполяция выражений, вложенные шаблоны -(0.3.2) - - - -Глобальные объекты -(0.3.3): - - - -console -(0.8.2): -error, -info, -log, -time, -timeEnd, -warn - - - -crypto -(0.7.0): -getRandomValues, -subtle.encrypt, -subtle.decrypt, -subtle.deriveBits, -subtle.deriveKey, -subtle.digest -subtle.exportKey -(0.7.10), -subtle.generateKey -(0.7.10), -subtle.importKey, -subtle.sign, -subtle.verify - - - -псевдоним globalThis -(0.3.8), - - - -njs: -version, -version_number -(0.7.4), -dump, -memoryStats -(0.7.8), -on -(0.5.2) - - - -process: -argv, -env, -pid, -ppid - - - - - - -Методы объекта nginx: - - - -HTTP Request: -r.done -(0.5.2), -r.error, -r.finish, -r.internalRedirect, -r.log, -r.return -(0.5.0), -r.send -(0.5.0), -r.sendBuffer -(0.5.2), -r.sendHeader, -r.setReturnValue -(0.7.0), -r.subrequest, -r.warn - - - -Stream Session: -s.allow -(0.2.4), -s.decline -(0.2.4), -s.deny -(0.2.4), -s.done -(0.2.4), -s.error, -s.log, -s.off -(0.2.4), -s.on -(0.2.4), -s.send -(0.2.4), -s.sendDownstream -(0.7.8), -s.sendUpstream -(0.7.8), -s.setReturnValue -(0.7.0), -s.warn - - - -Headers -(0.5.1): -append, -delete, -get, -getAll, -forEach, -has, -set - - - -Request -(0.7.10): -arrayBuffer, -headers, -json, -text - - - -Response -(0.5.1): -arrayBuffer, -headers, -json, -text - - - -ngx -(0.5.0): -fetch -(0.5.1), -log - - - -ngx.shared -(0.8.0): -add, -clear, -delete, -freeSpace, -get, -has, -incr, -items, -keys, -pop, -replace, -set, -size - - - - - - -Свойства объекта nginx: - - - -HTTP Request: -r.args, -r.headersIn, -r.headersOut, -r.httpVersion, -r.internal, -r.method, -r.parent, -r.rawHeadersIn -(0.4.1), -r.rawHeadersOut -(0.4.1), -r.rawVariables -(0.5.0), -r.remoteAddress, -r.requestBuffer -(0.5.0), -r.requestText, -r.responseBuffer -(0.5.0), -r.responseText -(0.5.0), -r.status, -r.uri, -r.variables -(0.2.8) - - - -Stream Session: -s.remoteAddress, -s.rawVariables -(0.5.0), -s.status -(0.5.2), -s.variables -(0.2.8) - - - -Periodic Session -(0.8.1): -PeriodicSession.rawVariables, -PeriodicSession.variables - - - -Request -(0.7.10): -bodyUsed, -cache, -credentials, -method, -mode, -url - - - -Response -(0.5.1): -bodyUsed, -ok, -redirected, -status, -statusText, -type, -url - - - -ngx -(0.5.0): -build -(0.8.0), -conf_file_path -(0.8.0), -conf_prefix -(0.7.8), -error_log_path -(0.8.0), -prefix -(0.8.0), -version -(0.8.0), -version_number -(0.8.0), -worker_id -(0.8.0) - - - -ngx.shared -(0.8.0): -capacity, -name, -type - - - - - - - - -
- -
diff --git a/xml/ru/docs/njs/examples.xml b/xml/ru/docs/njs/examples.xml deleted file mode 100644 --- a/xml/ru/docs/njs/examples.xml +++ /dev/null @@ -1,331 +0,0 @@ - - - - - - -
- -
- - -Примеры работают начиная с версии -0.4.0. - - -
- - -
- - -nginx.conf: - -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} - - - - -http.js: - -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; - - - -
- - -
- - -
- - -nginx.conf: - -js_import http.js; - -js_set $jwt http.jwt; - - - - -http.js: - -function generate_hs256_jwt(claims, key, valid) { - var header = { typ: "JWT", alg: "HS256" }; - var claims = Object.assign(claims, {exp: Math.floor(Date.now()/1000) + valid}); - - var s = [header, claims].map(JSON.stringify) - .map(v=>v.toString('base64url')) - .join('.'); - - var h = require('crypto').createHmac('sha256', key); - - return s + '.' + h.update(s).digest('base64url'); -} - -function jwt(r) { - var claims = { - iss: "nginx", - sub: "alice", - foo: 123, - bar: "qq", - zyx: false - }; - - return generate_hs256_jwt(claims, 'foo', 600); -} - -export default {jwt}; - - - -
- - - - - -
- - -В данном примере из JWT payload извлекается поле sub. -JWT-токен извлекается из заголовка
Authorization
. -
- - -nginx.conf: - -js_import http.js; - -js_set $jwt_payload_sub http.jwt_payload_sub; - -server { - #... - - location /jwt { - return 200 $jwt_payload_sub; - } -} - - - - -http.js: - -function jwt(data) { - var parts = data.split('.').slice(0,2) - .map(v=>Buffer.from(v, 'base64url').toString()) - .map(JSON.parse); - return { headers:parts[0], payload: parts[1] }; -} - -function jwt_payload_sub(r) { - return jwt(r.headersIn.Authorization.slice(7)).payload.sub; - // в случае, если токен передаётся как аргумент "myjwt" - // return jwt(r.args.myjwt).payload.sub; -} - -export default {jwt_payload_sub}; - - - -
- -
- - -
- - -
- - -nginx.conf: - -js_import http.js; - -location /start { - js_content http.content; -} - -location /foo { - proxy_pass http://backend1; -} - -location /bar { - proxy_pass http://backend2; -} - - - - -http.js: - -function content(r) { - var n = 0; - - function done(res) { - if (n++ == 0) { - r.return(res.status, res.responseBody); - } - } - - r.subrequest('/foo', r.variables.args, done); - r.subrequest('/bar', r.variables.args, done); -} - -export default {content}; - - - -
- - -
- - -nginx.conf: - -js_import http.js; - -location /start { - js_content http.content; -} - -location /auth { - proxy_pass http://auth_backend; -} - -location /backend { - proxy_pass http://backend; -} - - - - -http.js: - -async function content(r) { - try { - let reply = await r.subrequest('/auth'); - let response = JSON.parse(reply.responseBody); - let token = response['token']; - - if (!token) { - throw new Error("token is not available"); - } - - let backend_reply = await r.subrequest('/backend', `token=${token}`); - r.return(backend_reply.status, backend_reply.responseBody); - - } catch (e) { - r.error(e); - r.return(500); - } -} - -export default {content}; - - - -
- -
- - -
- - -
- - -nginx.conf: - -js_import http.js; - -location /redirect { - js_content http.redirect; -} - -location @named { - return 200 named; -} - - - - -http.js: - -function redirect(r) { - r.internalRedirect('@named'); -} - -export default {redirect}; - - - -
- -
- -
diff --git a/xml/ru/docs/njs/index.xml b/xml/ru/docs/njs/index.xml deleted file mode 100644 --- a/xml/ru/docs/njs/index.xml +++ /dev/null @@ -1,232 +0,0 @@ - - - - - - -
- -
- - -njs - это подмножество языка JavaScript, позволяющее -расширить функциональность nginx. -njs совместим с -ECMAScript 5.1 -(строгий режим) c некоторыми расширениями -ECMAScript 6 -и позже. -Совместимость находится в стадии развития. - - -
- - - - - -
- - - - - -Комплексное управление доступом и проверка защиты при помощи njs -до получения запроса сервером группы - - - -Управление заголовками ответа - - - -Создание гибких асинхронных обработчиков содержимого и фильтров - - - -Подробнее о сценариях использования -см. в примерах -и блогпостах. - - -
- - -
- - -Чтобы использовать njs в nginx, необходимо: - - - - -установить njs - - - - - -создать файл сценария njs, например http.js. -Описание свойств и методов языка njs -см. в справочнике. - -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; - - - - - - - -в файле nginx.conf включить -модуль ngx_http_js_module -и указать директиву -js_import -с файлом сценария http.js: - -load_module modules/ngx_http_js_module.so; - -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} - - - - - -Также доступна отдельная утилита командной строки, -которая может использоваться независимо от nginx для разработки и отладки njs. - - -
- - -
- - - - - -FreeBSD / amd64; - - - -Linux / x86, amd64, arm64, ppc64el; - - - -Solaris 11 / amd64; - - - -macOS / x86_64; - - - - - -
- - -
- - - -
- -
diff --git a/xml/ru/docs/njs/install.xml b/xml/ru/docs/njs/install.xml deleted file mode 100644 --- a/xml/ru/docs/njs/install.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - -
- -
- - -Для установки модулей njs на Linux могут быть использованы -пакеты: - - - -nginx-module-njs — -динамические модули -njs - - - -nginx-module-njs-dbg — debug-символы для -пакета nginx-module-njs - - - - - - -После установки пакетов необходимо загрузить динамические модули njs при помощи -директивы -load_module: - -load_module modules/ngx_http_js_module.so; - -или - -load_module modules/ngx_stream_js_module.so; - - - -
- - -
- - -Репозиторий -с исходным кодом njs можно клонировать следующей командой: -(необходим клиент Mercurial): - -hg clone http://hg.nginx.org/njs - -Затем модули необходимо собрать из -корневого каталога nginx с помощью -конфигурационного параметра --add-module: - -./configure --add-module=path-to-njs/nginx - -Модули также можно собрать как -динамические: - -./configure --add-dynamic-module=path-to-njs/nginx - - - - -Чтобы собрать только утилиту командной строки njs -необходимо запустить -команды ./configure и make njs -из корневого каталога njs. -Утилита доступна как ./build/njs. - - -
- -
diff --git a/xml/ru/docs/njs/node_modules.xml b/xml/ru/docs/njs/node_modules.xml deleted file mode 100644 --- a/xml/ru/docs/njs/node_modules.xml +++ /dev/null @@ -1,546 +0,0 @@ - - - - - - -
- -
- - -Часто разработчику приходится использовать сторонний код и, -как правило, такой код доступен в виде библиотеки. -В JavaScript концепция модулей является новой и -до недавнего времени не была стандартизированa. -До сих пор множество платформ или браузеров не поддерживают модули, -по этой причине практически невозможно повторно использовать код. -В данной статье приводятся способы повторного использования -кода в njs при помощи Node.js. - - - -В примерах статьи используется функциональность -njs -0.3.8 - - - -При добавлении стороннего кода в njs -может возникнуть несколько проблем: - - - - -большое количество файлов, ссылающихся друг на друга, и их зависимости - - - -платформозависимые API - - - -языковые конструкции нового стандарта - - - - - - -Однако это не является чем-то новым или специфичным для njs. -Разработчикам JavaScript приходится часто иметь дело с подобными случаями, -например при поддержке нескольких несхожих платформ -с разными свойствами. -Данные проблемы можно разрешить при помощи следующих инструментов: - - - - -Большое количество файлов, ссылающихся друг на друга, и их зависимости - -Решение: слияние всего независимого кода в один файл. -Для этих целей могут использоваться утилиты -browserify или -webpack, -позволяющие преобразовать проект в один файл, содержащий -код и все зависимости. - - - - -Платформозависимые API - -Решение: использование библиотек, реализующих подобные API -в платформонезависимом режиме, однако в ущерб производительности. -Определённая функциональность может быть также реализована при помощи -polyfill. - - - - -Языковые конструкции нового стандарта - -Решение: трансплирование кода— -ряд преобразований, -заменяющих новые функции языка в соответствии со старым стандартом. -Для этих целей может использоваться - babel. - - - - - - - -В статье также используются две относительно большие -библиотеки на основе npm: - - - - -protobufjs— -библиотека для создания и парсинга protobuf-сообщений, используемая -протоколом gRPC - - - -dns-packet— -библиотека для обработки пакетов протокола DNS - - - - - -
- - -
- - - -В статье описываются общие принципы работы -и не ставится цель описания подробных сценариев работы с Node.js -и JavaScript. -Перед выполнением команд -необходимо ознакомиться с документацией соответствующих пакетов. - -Сначала, предварительно установив и запустив Node.js, необходимо создать -пустой проект и установить зависимости; -для выполнения нижеперечисленных команд необходимо -находиться в рабочем каталоге: - -$ mkdir my_project && cd my_project -$ npx license choose_your_license_here > LICENSE -$ npx gitignore node - -$ cat > package.json <<EOF -{ - "name": "foobar", - "version": "0.0.1", - "description": "", - "main": "index.js", - "keywords": [], - "author": "somename <some.email@example.com> (https://example.com)", - "license": "some_license_here", - "private": true, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - } -} -EOF -$ npm init -y -$ npm install browserify - - - -
- - -
- - -Библиотека предоставляет парсер -для определения интерфейса .proto, -а также генератор кода для парсинга и генерации сообщений. - - - -В данном примере используется -файл -helloworld.proto -из примеров gRPC. -Целью является создание двух сообщений: -HelloRequest и -HelloResponse. -Также используется -статический -режим protobufjs вместо динамически генерируемых классов, так как -njs не поддерживает динамическое добавление новых функций -из соображений безопасности. - - - -Затем устанавливается библиотека, -из определения протокола генерируется код JavaScript, -реализующий маршалинг сообщений: - -$ npm install protobufjs -$ npx pbjs -t static-module helloworld.proto > static.js - - - - -Таким образом файл static.js становится новой зависимостью, -хранящей необходимый код для реализации обработки сообщений. -Функция set_buffer() содержит код, использующий -библиотеку для создания буфера с сериализованным -сообщением HelloRequest. -Код находится в файле code.js: - -var pb = require('./static.js'); - -// Пример использования библиотеки protobuf: подготовка буфера к отправке -function set_buffer(pb) -{ - // назначение полей gRPC payload - var payload = { name: "TestString" }; - - // создание объекта - var message = pb.helloworld.HelloRequest.create(payload); - - // сериализация объекта в буфер - var buffer = pb.helloworld.HelloRequest.encode(message).finish(); - - var n = buffer.length; - - var frame = new Uint8Array(5 + buffer.length); - - frame[0] = 0; // флаг 'compressed' - frame[1] = (n & 0xFF000000) >>> 24; // длина: uint32 в сетевом порядке байт - frame[2] = (n & 0x00FF0000) >>> 16; - frame[3] = (n & 0x0000FF00) >>> 8; - frame[4] = (n & 0x000000FF) >>> 0; - - frame.set(buffer, 5); - - return frame; -} - -var frame = set_buffer(pb); - - - - -Для проверки работоспособности необходимо выполнить код при помощи node: - -$ node ./code.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] - -Результатом является закодированный фрейм gRPC. -Теперь фрейм можно запустить с njs: - -$ njs ./code.js -Thrown: -Error: Cannot find module "./static.js" - at require (native) - at main (native) - - - - -Так как модули не поддерживаются, то операция завершается получением исключения. -В этом случае можно использовать утилиту browserify -или другую подобную утилиту. - - - -Попытка обработки файла code.js завершится -большим количеством JS-кода, который предполагается запускать в браузере, -то есть сразу после загрузки. -Однако необходимо получить другой результат— -экспортируемую функцию, на которую -можно сослаться из конфигурации nginx. -Для этого потребуется создание кода-обёртки. - -В целях упрощения в примерах данной статьи -используется интерфейс комадной строки njs. -На практике для запуска кода обычно используется njs-модуль для nginx. - - - - -Файл load.js содержит код, загружающий библиотеку, -храняющую дескриптор в глобальном пространстве имён: - -global.hello = require('./static.js'); - -Данный код будет заменён объединённым содержимым. -Код будет использовать дескриптор "global.hello" для доступа -к библиотеке. - - - -Затем для получения всех зависимостей в один файл -код обрабатыается утилитой browserify: - -$ npx browserify load.js -o bundle.js -d - -В результате генерируется объёмный файл, содержащий все зависимости: - -(function(){function...... -... -... -},{"protobufjs/minimal":9}]},{},[1]) -//# sourceMappingURL.............. - -Для получения результирующего файла "njs_bundle.js" -необходимо объединить "bundle.js" и следующий код: - -// Пример использования библиотеки protobuf: подготовка буфера к отправке -function set_buffer(pb) -{ - // назначение полей gRPC payload - var payload = { name: "TestString" }; - - // создание объекта - var message = pb.helloworld.HelloRequest.create(payload); - - // сериализация объекта в буфер - var buffer = pb.helloworld.HelloRequest.encode(message).finish(); - - var n = buffer.length; - - var frame = new Uint8Array(5 + buffer.length); - - frame[0] = 0; // флаг 'compressed' - frame[1] = (n & 0xFF000000) >>> 24; // длина: uint32 в сетевом порядке байт - frame[2] = (n & 0x00FF0000) >>> 16; - frame[3] = (n & 0x0000FF00) >>> 8; - frame[4] = (n & 0x000000FF) >>> 0; - - frame.set(buffer, 5); - - return frame; -} - -// функции, вызываемые снаружи -function setbuf() -{ - return set_buffer(global.hello); -} - -// вызов кода -var frame = setbuf(); -console.log(frame); - -Для проверки работоспособности необходимо запустить файл при помощи node: - -$ node ./njs_bundle.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] - -Дальнейшие шаги выполняются при помощи njs: - -$ njs ./njs_bundle.js -Uint8Array [0,0,0,0,12,10,10,84,101,115,116,83,116,114,105,110,103] - -Теперь необходимо задействовать njs API для преобразования -массива в байтовую строку для дальнейшего использования модулем nginx. -Данный код необходимо добавить перед строкой -return frame; }: - -if (global.njs) { - return String.bytesFrom(frame) -} - -Проверка работоспособности: - -$ njs ./njs_bundle.js |hexdump -C -00000000 00 00 00 00 0c 0a 0a 54 65 73 74 53 74 72 69 6e |.......TestStrin| -00000010 67 0a |g.| -00000012 - -Экспортируемая функция получена. -Парсинг ответа может быть сделан аналогичным способом: - -function parse_msg(pb, msg) -{ - // преобразование байтовой строки в массив целых чисел - var bytes = msg.split('').map(v=>v.charCodeAt(0)); - - if (bytes.length < 5) { - throw 'message too short'; - } - - // первые 5 байт являются фреймом gRPC (сжатие + длина) - var head = bytes.splice(0, 5); - - // проверка правильной длины сообщения - var len = (head[1] << 24) - + (head[2] << 16) - + (head[3] << 8) - + head[4]; - - if (len != bytes.length) { - throw 'header length mismatch'; - } - - // вызов protobufjs для декодирования сообщения - var response = pb.helloworld.HelloReply.decode(bytes); - - console.log('Reply is:' + response.message); -} - - - -
- - -
- - -В примере используется библиотека для создания и парсинга пакетов DNS. -Эта библиотека, а также её зависимости, -использует современные языковые конструкции, не поддерживаемые в njs. -Для поддержки таких конструкций -потребуется дополнительный шаг: транспилирование исходного кода. - - - -Необходимо установить дополнительные пакеты node: - -$ npm install @babel/core @babel/cli @babel/preset-env babel-loader -$ npm install webpack webpack-cli -$ npm install buffer -$ npm install dns-packet - -Файл конфигурации webpack.config.js: - -const path = require('path'); - -module.exports = { - entry: './load.js', - mode: 'production', - output: { - filename: 'wp_out.js', - path: path.resolve(__dirname, 'dist'), - }, - optimization: { - minimize: false - }, - node: { - global: true, - }, - module : { - rules: [{ - test: /\.m?js$$/, - exclude: /(bower_components)/, - use: { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'] - } - } - }] - } -}; - -В данном случае используется режим "production". -Конструкция "eval" не используется, так как -не поддерживается njs. -Точкой входа является файл load.js: - -global.dns = require('dns-packet') -global.Buffer = require('buffer/').Buffer - -Сначала необходимо создать единый файл для библиотек, как в предыдущих примерах: - -$ npx browserify load.js -o bundle.js -d - -Затем необходимо обработать утилитой webpack, что также запускает babel: - -$ npx webpack --config webpack.config.js - -Команда создаёт файл dist/wp_out.js, являющийся -трансплицированной версией bundle.js. -Далее необходимо объединить этот файл с code.js, -хранящим код: - -function set_buffer(dnsPacket) -{ - // create DNS packet bytes - var buf = dnsPacket.encode({ - type: 'query', - id: 1, - flags: dnsPacket.RECURSION_DESIRED, - questions: [{ - type: 'A', - name: 'google.com' - }] - }) - - return buf; -} - -В данном примере генерируемый код не обёрнут в функцию, -явного вызова не требуется. -Результат доступен в каталоге "dist": - -$ cat dist/wp_out.js code.js > njs_dns_bundle.js - -Далее осуществляется вызов кода в конце файла: - -var b = set_buffer(global.dns); -console.log(b); - -И затем выполнение кода при помощи node: - -$ node ./njs_dns_bundle_final.js -Buffer [Uint8Array] [ - 0, 1, 1, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 6, 103, 111, 111, - 103, 108, 101, 3, 99, 111, 109, 0, - 0, 1, 0, 1 -] - -Тестирование и запуск кода вместе с njs: - -$ njs ./njs_dns_bundle_final.js -Uint8Array [0,1,1,0,0,1,0,0,0,0,0,0,6,103,111,111,103,108,101,3,99,111,109,0,0,1,0,1] - - - - -Ответ можно распарсить следующим способом: - -function parse_response(buf) -{ - var bytes = buf.split('').map(v=>v.charCodeAt(0)); - - var b = global.Buffer.from(bytes); - - var packet = dnsPacket.decode(b); - - var resolved_name = packet.answers[0].name; - - // ожидаемое имя 'google.com', согласно запросу выше -} - - - - -
- -
diff --git a/xml/ru/docs/njs/preload_objects.xml b/xml/ru/docs/njs/preload_objects.xml deleted file mode 100644 --- a/xml/ru/docs/njs/preload_objects.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - -
- -
- - -Для каждого входящего запроса в njs создаётся отдельная виртуальная машина. -Это позволяет прогнозировать предсказуемое поглощение памяти -или осуществить изоляцию запросов. -Однако поскольку все запросы являются изолированными, то -если обработчику запроса необходимо получить доступ к данным, -ему нужно сначала их прочитать самому. -Это неэффективно, особенно если объём данных большой. - - - -Это ограничение можно обойти -при помощи разделяемого предзагруженного объекта. -Такие объекты создаются неизменяемыми и не имеют цепочки прототипов: -у них нет возможности -изменить значения или добавить/удалить свойства в объектах/массивах. - - -
- - -
- - -Примеры работы с предзагруженными объектами в njs: - - - - -доступ к свойствам по имени: - -preloaded_object.prop_name -preloaded_object[prop_name] - - - - -перечисление свойств: - -for (i in preloaded_object_name) { - ... -} - - - - -применение встроенных методов, не изменяющих состояние, -при помощи call(): - -Array.prototype.filter.call(preloaded_object_name, ...) - - - - - - -
- -
diff --git a/xml/ru/docs/njs/reference.xml b/xml/ru/docs/njs/reference.xml deleted file mode 100644 --- a/xml/ru/docs/njs/reference.xml +++ /dev/null @@ -1,1606 +0,0 @@ - - - - - - -
- -
- - -njs предоставляет объекты, методы и свойства -для расширения функциональности nginx. - - - -Справочник содержит описания методов, свойств и модулей, -доступных только в njs и не соответствующих стандарту ECMAScript. -Описания методов и свойств njs, -соответствующих стандарту, доступны в -спецификации -ECMAScript. -Список всех методов и свойств njs доступен в разделе -Совместимость. - - -
- - -
- - -
- - -Объект HTTP доступен только в -модуле ngx_http_js_module. -Все строки в объекте HTTP являются -байтовыми строками. - - - -r.args{} - -объект аргументов запроса, только чтение - - -r.error(строка) - -записывает строку в лог-файл ошибок -на уровне лога error - - -r.finish() - -завершает отправку ответа клиенту - - -r.headersIn{} - -объект входящих заголовков, только чтение. - -Доступ к заголовку запроса Foo -можно получить при помощи синтаксиса: -headersIn.foo или 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
и -
User-Agent
-могут иметь только одно значение поля -(0.4.1). -Дубликаты значений поля в заголовке запроса
Cookie
-разделяются точкой с запятой (;). -Дубликаты значений поля во всех остальных заголовках запроса -разделяются запятой. -
-
- -r.headersOut{} - -объект исходящих заголовков, доступно для записи. - -Доступ к заголовку ответа Foo -можно получить при помощи синтаксиса: -headersOut.foo или headersOut['Foo']. - - - -Значения полей многозначных заголовков ответа -(0.4.0) -можно задать при помощи синтаксиса: - -r.headersOut['Foo'] = ['a', 'b'] - -результат: - -Foo: a -Foo: b - -Все предыдущие значения поля заголовка ответа
Foo
-будут удалены. -
- - -В стандартных заголовках ответа, -поля которых могут принимать только одно значение, например -
Content-Type
, -учитывается только последний элемент массива. -Значения поля в заголовке ответа
Set-Cookie
-всегда возвращаются в виде массива. -Дубликаты значений поля в заголовках ответа -
Age
, -
Content-Encoding
, -
Content-Length
, -
Content-Type
, -
ETag
, -
Expires
, -
Last-Modified
, -
Location
, -
Retry-After
-игнорируются. -Дубликаты значений поля в других заголовках ответов -разделяются при помощи запятой. -
-
- -r.httpVersion - -версия HTTP, только чтение - - -r.internalRedirect(uri) - -осуществляет внутреннее перенаправление на указанный uri. -Если uri начинается с префикса “@”, -то он считается именованным location. -Перенаправление осуществляется после завершения выполнения обработчика. - - -r.log(строка) - -записывает строку в лог-файл ошибок -на уровне лога info - - -r.method - -HTTP метод, только чтение - - -r.parent - -ссылается на родительский объект запроса - - -r.remoteAddress - -адрес клиента, только чтение - - -r.rawHeadersIn{} - -возвращает массив пар ключей и значений -таким же, каким он был получен от клиента -(0.4.1). - -Например для следующих заголовков запроса: - -Host: localhost -Foo: bar -foo: bar2 - -результат r.rawHeadersIn: - -[ - ['Host', 'localhost'], - ['Foo', 'bar'], - ['foo', 'bar2'] -] - -Значения полей всех заголовков foo -можно получить при помощи синтаксиса: - -r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1]) - -результат: - -['bar', 'bar2'] - -Имена полей заголовков не приводятся к нижнему регистру, -дубликаты значений поля не объединяются. - - - -r.rawHeadersOut{} - -возвращает массив пар ключей и значений заголовков ответа -(0.4.1). -Имена полей заголовков не приводятся к нижнему регистру, -дубликаты значений поля не объединяются. - - -r.requestBody - -возвращает тело запроса клиента, если оно не было -записано во временный файл. -Чтобы убедиться, что тело запроса клиента находится в памяти, -его размер должен быть ограничен -, -и также необходимо установить достаточный размер буфера при помощи -. -Свойство доступно только в директиве -. - - -r.responseBody - -хранит тело ответа подзапроса, только чтение. -Размер r.responseBody ограничивается директивой -. - - -r.return(код[, строка]) - -отправляет -клиенту полный ответ с указанным кодом - -Можно задать или URL перенаправления -(для кодов 301, 302, 303, 307 и 308), -или текст тела ответа (для остальных кодов) в качестве второго аргумента - - - -r.send(строка) - -отправляет часть тела ответа клиенту - - -r.sendHeader() - -отправляет заголовки HTTP клиенту - - -r.status - -статус, доступно для записи - - -r.subrequest(uri[, -options[, callback]]) - -создаёт подзапрос с заданными uri и -options и устанавливает -необязательный callback завершения. - - -Подзапрос -использует входящие заголовки клиентского запроса. -Для отправки на проксируемый сервер заголовков, отличных от оригинальных, -может использоваться директива -. -Для отправки на проксируемый сервер нового набора заголовков -может использоваться директива -. - - - -Если options является строкой, то в ней -содержится срока аргументов подзапроса. -В противном случае ожидается, что options является -объектом со следующими ключами: - -args - -строка с аргументами, по умолчанию используется пустая строка - -body - -тело запроса, -по умолчанию используется тело запроса родительского объекта запроса - - -method - -метод HTTP, по умолчанию используется метод GET - - -detached - -логический флаг (0.3.9), -если true, -то создаваемый подзапрос является независимым подзапросом. -Ответы на независимые подзапросы игнорируются. -В отличие от обычных подзапросов независимый подзапрос -можно создать внутри обработчика переменной. -Флаг detached и аргумент callback -являются взаимоисключающими. - - - - - - -callback получает -объект ответа подзапроса с методами и свойствами, -идентичными родительскому объекту запроса. - - - -Начиная с версии njs 0.3.8 -если не указан callback, -то возвращается объект Promise, -который разрешается в объект ответа подзапроса. - - - -r.uri - -текущий URI -запроса в -нормализованном -виде, только чтение - - -r.variables{} - -объект переменных nginx, доступно для записи -(начиная с версии 0.2.8) - - -r.warn(строка) - -записывает строку в лог-файл ошибок -на уровне лога warning - - -
-
- -
- - -
- - -Объект stream-сессии доступен только в -модуле -ngx_stream_js_module. -Все строки в объекте stream являются -байтовыми строками. - - - - - -s.allow() - -успешно финализирует обработчик фазы -(0.2.4) - - -s.decline() - -финализирует обработчик фазы и передаёт контроль следующему обработчику -(0.2.4) - - -s.deny() - -финализирует обработчик фазы с кодом ошибки доступа -(0.2.4) - - -s.done([код]) - -успешно финализирует текущий обработчик фазы -или финализирует его с указанным числовым кодом -(0.2.4). - - -s.error(строка) - -записывает отправленную строку в лог-файл ошибок -на уровне лога error - - -s.log(строка) - -записывает отправленную строку в лог-файл ошибок -на уровне лога info - - -s.off(имяСобытия) - -отменяет регистрацию callback'а, установленного методом -s.on() -(0.2.4) - - -s.on(событие, -callback) - -регистрирует callback -для указанного события -(0.2.4). - - -Событием может являться одна из следующих строк: - -upload - -новые данные от клиента - - -download - -новые данные к клиенту - - - - - - -Callback завершения имеет следующий прототип: -callback(данные, флаги), где -данные являются строкой, -флаги являются объектом -со следующими свойствами: - -last - -логическое свойство, -true, если данные являются последним буфером. - - - - - - -s.remoteAddress - -адрес клиента, только чтение - - -s.send(данные[, -параметры]) - -отправляет данные клиенту -(0.2.4). -Параметры являются объектом, используемым -для переопределения флагов буфера nginx, -полученных из буфера входных данных. -Флаги могут быть переопределены при помощи следующих флагов: - - - -last - -логическое свойство, -true, если буфер является последним буфером - - -flush - -логическое свойство, -true, если буфер должен иметь флаг flush - - - -Метод может быть вызван несколько раз в течение одного вызова callback'a. - - -s.variables{} - -объект переменных nginx, доступно для записи -(начиная с версии 0.2.8) - - -s.warn(строка) - -записывает отправленную строку в лог-файл ошибок -на уровне лога warning - - - - - -
- -
- - -
- - -
- - -
- - -Объект process является глобальным объектом, -предоставляющим информацию о текущем процессе -(0.3.3). - - - - - -process.argv - -Возвращает массив, содержащий аргументы командной строки, -передаваемые в момент запуска текущего процесса. - - -process.env - -Возвращает объект, содержащий переменные окружения пользователя. - -По умолчанию nginx удаляет все переменные окружения, унаследованные -от своего родительского процесса, кроме переменной TZ. -Для сохранения части унаследованных переменных -необходимо использовать директиву . - - - -process.pid - -Возвращает PID текущего процесса. - - -process.ppid - -Возвращает PID текущего родительского процесса. - - - - - -
- -
- - -
- - -В njs существует два типа строк: строка Unicode (по умолчанию) и -байтовая строка. - - - -Строка Unicode соответствует строке ECMAScript, -содержащей символы Unicode. - - - -Байтовые строки содержат последовательность байт и -используются для сериализации строк Unicode -во внешние данные и десериализации из внешних источников. -Например метод toUTF8() сериализует -строку Unicode в байтовую строку используя кодировку UTF8: - ->> '£'.toUTF8().toString('hex') -'c2a3' /* C2 A3 является UTF8-представлением codepoint 00A3 ('£') */ - -Метод toBytes() сериализует -строку Unicode с codepoints до 255 в байтовую строку, -в противном случае возвращается null: - ->> '£'.toBytes().toString('hex') -'a3' /* a3 является байтом, равным codepoint 00A3 ('£') */ - - - - -String.bytesFrom(массив -| строка, кодировка) - -Создаёт байтовую строку или из массива, содержащего октеты, -или из кодированной строки -(0.2.3). -Кодировкой может быть -hex, -base64 и -base64url. -Метод устарел начиная с -0.4.4, -вместо него следует использовать метод Buffer.from: - ->> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString() -'buffer' - ->> Buffer.from('YnVmZmVy', 'base64').toString() -'buffer' - - - -String.prototype.fromBytes(начало[, -конец]) - -Возвращает новую строку Unicode из байтовой строки, -в которой каждый байт заменяется соответствующей Unicode codepoint. - - -String.prototype.fromUTF8(начало[, -конец]) - -Преобразует байтовую строку, содержащую валидную строку UTF8, -в строку Unicode, -иначе возвращается null. - - -String.prototype.toBytes(начало[, -конец]) - -Сериализует строку Unicode в байтовую строку. -Возвращает null, если в строке найден символ больше, чем 255. - - -String.prototype.toString(кодировка) - - -Кодирует указанную строку в -hex, -base64 или -base64url: - ->> 'αβγδ'.toString('base64url') -'zrHOss6zzrQ' - -До версии 0.4.3 -могла быть кодирована только байтовая строка: - ->> 'αβγδ'.toUTF8().toString('base64url') -'zrHOss6zzrQ' - - - - -String.prototype.toUTF8(начало[, -конец]) - -Сериализует строку Unicode -в байтовую строку при помощи кодирования UTF8. - ->> 'αβγδ'.toUTF8().length -8 ->> 'αβγδ'.length -4 - - - - - - -
- - -
- - -Объект TextDecoder -создаёт поток кодовых точек из потока данных -(0.4.3). - - - - - -TextDecoder([[кодировка], -options]) - -Создаёт новый объект TextDecoder -для указанной кодировки, -на данный момент поддерживается только UTF-8. -Параметр options является -словарём TextDecoderOption со свойствами: - - - -fatal - -логический флаг, указывающий, что -TextDecoder.decode() -должен вызывать исключение TypeError в случае, если -найдена ошибка кодирования, по умолчанию false. - - - - - -TextDecoder.prototype.encoding - -Возвращает строку с именем кодировки, используемой -TextDecoder(), -только чтение. - - -TextDecoder.prototype.fatal - -логический флаг, true, если -генерируется ошибка для невалидных символов, -только чтение. - - -TextDecoder.prototype.ignoreBOM - -логический флаг, true, если -игнорируется маркер порядка следования байтов, -только чтение. - - -TextDecoder.prototype.decode(буфер, -[options]) - -Возвращает строку с текстом, -декодированным из буфера при помощи -TextDecoder(). -Буфером может быть -ArrayBuffer. -Параметром options является -словарь TextDecodeOptions со свойствами: - - - -stream - -логический флаг, указывающий, что -при последующих вызовах decode() -должны последовать дополнительные данные: -true, если данные обрабатываются блоками, и -false для последнего блока -или если данные не передаются блоками. -По умолчанию false. - - - - ->> (new TextDecoder()).decode(new Uint8Array([206,177,206,178])) -αβ - - - - - - -
- - -
- - -Объект TextEncoder -создаёт поток данных в кодировке UTF-8 -из потока кодовых точек -(0.4.3). - - - - - -TextEncoder() - -Возвращает только что созданный TextEncoder, -который создаёт поток данных в кодировке UTF-8. - - -TextEncoder.prototype.encode(строка) - -Кодирует строку в Uint8Array, -содержащий текст в кодировке UTF-8. - - -TextEncoder.prototype.encodeInto(строка, -uint8Array) - -Преобразует строку в UTF-8, -сохраняет результат в целевом Uint8Array и -возвращает объект словаря, отражающий прогресс кодирования, со свойствами: - - - -read - -количество блоков кода UTF-16 из исходной строки, -преобразованных в UTF-8 - - -written - -количество байтов, преобразованных в целевом Uint8Array - - - - - - - - -
- - -
- - - - -clearTimeout(timeout) - -Отменяет объект timeout, -созданный setTimeout(). - - -setTimeout(функция, -миллисекунды[, -аргумент1, -аргументN]) - -Вызывает функцию -по прошествии указанного количества миллисекунд. -Указанной функции можно передать -один или более необязательных аргументов. -Возвращает объект timeout. - -function handler(v) -{ - // ... -} - -t = setTimeout(handler, 12); - -// ... - -clearTimeout(t); - - - - - - -
- -
- - -
- -
- - -Модуль Crypto предоставляет поддержку криптографических функций. -Объект модуля Crypto доступен через require('crypto'). - - - - - -crypto.createHash(алгоритм) - -Создаёт и возвращает объект Hash, -который может использоваться для создания hash digests -при помощи указанного алгоритма. -Алгоритмом может быть -md5, -sha1 и -sha256. - - -crypto.createHmac(алгоритм, -секретный ключ) - -Создаёт и возвращает объект HMAC, который -использует заданный алгоритм и секретный ключ. -Алгоритм может быть -md5, -sha1 и -sha256. - - - - - - -
- - - - -hash.update(данные) - -Обновляет содержимое хэша с передаваемыми данными. - - -hash.digest([кодировка]) - -Подсчитывает дайджест всех данных, передаваемых при помощи -hash.update(). -Кодировка может быть -hex, -base64 и -base64url. -Если кодировка не указана, то будет возвращен объект буфера -(0.4.4). - -До версии 0.4.4 -вместо объекта буфера возвращалась байтовая строка. - - - - - - - - ->> var cr = require('crypto') -undefined - ->> cr.createHash('sha1').update('A').update('B').digest('base64url') -'BtlFlCqiamG-GMPiK_GbvKjdK10' - - - -
- - -
- - - - -hmac.update(данные) - -Обновляет содержимое HMAC с передаваемыми данными. - - -hmac.digest([кодировка]) - -Подсчитывает HMAC-дайджест всех данных, передаваемых при помощи -hmac.update(). -Кодировка может быть -hex, -base64 и -base64url. -Если кодировка не указана, то будет возвращена байтовая строка. - - - - - - ->> var cr = require('crypto') -undefined - ->> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url') -'Oglm93xn23_MkiaEq_e9u8zk374' - - - -
- -
- - -
- - -Модуль File System предоставляет набор функций для операций с файлами. - - - -Объект модуля доступен через require('fs'). -Начиная с версии 0.3.9 -доступны промисифицированные версии методов file system через -объект require('fs').promises: - -> var fs = require('fs').promises; -undefined -> fs.readFile("/file/path").then((data)=>console.log(data)) -<file data> - - - -accessSync(путь[, -mode]) - -Синхронно проверяет разрешения для файла или каталога, -указанного в пути -(0.3.9). -Если проверка не удалась, то будет возвращена ошибка, -в противном случае метод возвратит undefined. - - -mode - -По умолчанию -fs.constants.F_OK. -Является необязательным числом, -которое задаёт выполнение проверок доступа. - -try { - fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK); - console.log('has access'); -} catch (e) { - console.log('no access');) -} - - - - - - -appendFileSync(имяФайла, -данные[, options]) - -Синхронно добавляет указанные данные -в файл с указанным именем. -Данными могут быть строка -или объект буфера (0.4.4. -Если файл не существует, то он будет создан. -Параметр options должен быть -объектом со следующими ключами: - - -режим - -режим, по умолчанию 0o666 - - -флаг - -флаг файловой системы, -по умолчанию a - - - - - -mkdirSync(путь[, -options]) - -Синхронно создаёт каталог по указанному пути -(0.4.2). -Параметр options должен быть -числом, которое задаёт -режим, -или объектом с ключами: - - -режим - -режим, по умолчанию 0o777. - - - - - -readdirSync(путь[, -options]) - -Синхронно читает содержимое каталога -по указанному пути -(0.4.2). -Параметр options должен быть -строкой, определяющей кодировку -или объектом с ключами: - - -кодировка - -кодировка, по умолчанию utf8. -Кодировка может быть utf8 и буфер -(0.4.4). - - -withFileTypes - -если true, то массив файлов будет содержать -объекты fs.Dirent, -по умолчанию false. - - - - - -readFileSync(имяФайла[, -options]) - -Синхронно возвращает содержимое файла -с указанным именем. -Параметр options хранит -строку, которая задаёт кодировку. -Если кодировка указана, то будет возвращена строка, -иначе будет возвращён объект буфера -(0.4.4). - -До версии 0.4.4 -возвращалась байтовая строка -в случае, если не была указана кодировка. - -Иначе ожидается, что options является -объектом с ключами: - - -кодировка - -кодировка, по умолчанию не указана. -Кодировка может быть utf8, -hex -(0.4.4), -base64 -(0.4.4), -base64url -(0.4.4). - - -флаг - -флаг файловой системы, -по умолчанию r - - - - ->> 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(путь[, -options]) - -Синхронно вычисляет канонический путь при помощи преобразования -., .. и символических ссылок используя -realpath(3). -Аргумент options может быть строкой, определяющей кодировку, -или объектом со свойством encoding, определяющим символьную кодировку, -которая используется для передачи пути обратному вызову -(0.3.9). - - -renameSync(старыйПуть, -новыйПуть) - -Синхронно меняет имя или местоположение файла. -(0.3.4). - ->> var fs = require('fs') -undefined ->> var file = fs.renameSync('hello.txt', 'HelloWorld.txt') -undefined - - - -rmdirSync(путь) - -Синхронно удаляет каталог по указанному пути -(0.4.2). - - -symlinkSync(цель, -path) - -Синхронно создаёт ссылку с именем путь, -указывающую на цель при помощи -symlink(2) -(0.3.9). -Относительные цели считаются относительно корневого каталога ссылки. - - -unlinkSync(путь) - -Синхронно удаляет файл по указанному пути -(0.3.9). - - -writeFileSync(имяФайла, -данные[, -options]) - -Синхронно записывает данные в файл -с указанным именем. -Данными могут быть строка -или объект буфера (0.4.4. -Если файл не существует, то он будет создан. -Если файл существует, то он будет заменён. -Параметр options должен быть -объектом с ключами: - -режим - -режим, по умолчанию 0o666 - - -флаг - -флаг файловой системы, -по умолчанию w - - - - ->> var fs = require('fs') -undefined ->> var file = fs.writeFileSync('hello.txt', 'Hello world') -undefined - - - - - - - -
- - -fs.Dirent является представлением записи каталога— -файлом или подкаталогом . -В случае, если -readdirSync() -вызывается с опцией -withFileTypes -получившийся массив содержит объекты fs.Dirent. - - - - -dirent.isBlockDevice()—возвращает -true, если объект fs.Dirent описывает -блочное устройство - - - -dirent.isCharacterDevice()—возвращает -true, если объект fs.Dirent описывает -символьное устройство. - - - -dirent.isDirectory()—возвращает -true, если объект fs.Dirent описывает -каталог файловой системы. - - - -dirent.isFIFO()—возвращает -true, если объект fs.Dirent описывает -FIFO-канал. - - - -dirent.isFile()—возвращает -true, если объект fs.Dirent описывает -обычный файл. - - - -dirent.isSocket()—возвращает -true, если объект fs.Dirent описывает -сокет. - - - -dirent.isSymbolicLink()—возвращает -true, если объект fs.Dirent описывает -символическую ссылку. - - - -dirent.name— -имя файла, на которое ссылается объект fs.Dirent. - - - - - -
- - -
- - -Метод access() -может принимать следующие флаги. -Флаги экспортируются при помощи fs.constants: - - - - -F_OK—указывает, что файл может -быть видимым для для вызывающего процесса, -используется по умолчанию, если режим не указан - - - -R_OK—указывает, что файл может -читаться вызывающим процессом - - - -W_OK—указывает, что файл может -записываться вызывающим процессом - - - -X_OK—указывает, что файл может -выполняться вызывающим процессом - - - - - -
- - -
- - -Опция флаг может принимать следующие значения: - - - - -a—открытие файла для добавления данных. -Если файл не существует, то он будет создан - - - -ax—то же, что и a, -но завершится неудачей, если файл существует - - - -a+—открытие файла для чтения и добавления данных. -Если файл не существует, то он будет создан - - - -ax+—то же, что и a+, -но завершится неудачей, если файл существует - - - -as—открытие файла для добавления данных -в синхронном режиме. -Если файл не существует, то он будет создан - - - -as+—открытие файла для чтения и добавления данных -в синхронном режиме. -Если файл не существует, то он будет создан - - - -r— открытие файла для чтения. -Если файл не существует, то возникнет исключение - - - -r+—открытие файла для чтения и записи. -Если файл не существует, то возникнет исключение - - - -rs+—открытие файла для чтения и записи -в синхронном режиме. -Указывает операционной системе не использовать кэш локальной файловой системы - - - -w—открытие файла для записи. -Если файл не существует, то он будет создан. -Если файл существует, то он будет заменён. - - - -wx—то же, что и w, -но завершится неудачей, если файл существует - - - -w+—открытие файла для чтения и записи. -Если файл не существует, то он будет создан. -Если файл существует, то он будет заменён. - - - -wx+—то же, что и w+, -но завершится неудачей, если файл существует - - - - - -
- -
- - -
- - -Модуль Query String предоставляет поддержку -синтаксического разбора и форматирования строки запроса URL. -(0.4.3). -Объект модуля Query String доступен через -require('querystring'). - - - - - -querystring.decode() - -является псевдонимом для -querystring.parse(). - - -querystring.encode() - -является псевдонимом для -querystring.stringify(). - - -querystring.escape(строка) - - -Кодирует заданную строку, -возвращает экранированную строку. -Метод используется методом -querystring.stringify() -и не должен использоваться напрямую. - - - -querystring.parse(строка[, -separator[, -equal[, -options]]]) - - -Осуществляет синтаксический разбор строки запроса и возвращает объект. - - - -Параметр separator является подстрокой, -разделяющей в строке запроса пары ключей и значений, -по умолчанию “&”. - - - -Параметр equal является подстрокой, -разделяющей в строке запроса ключи и значения, -по умолчанию “=”. - - - -Параметр options должен быть -объектом со следующими ключами: - -decodeURIComponent -функция - -Функция, используемая -при декодировании процентно-кодированных символов в строке запроса, -по умолчанию -querystring.unescape() - - -maxKeys -число - -максимальное число ключей для синтаксического разбора, -по умолчанию 1000. -Значение 0 удаляет ограничение на подсчёт ключей. - - - -По умолчанию предполагается, что процентно-кодированные символы в строке запроса -используют кодировку UTF-8, -неверная последовательность байтов UTF-8 будет заменена на -U+FFFD. - - - -Пример для строки запроса: - -'foo=bar&abc=xyz&abc=123' - -результат: - -{ - foo: 'bar', - abc: ['xyz', '123'] -} - - - - - -querystring.stringify(object[, -separator[, -equal[, -options]]]) - - -Осуществляет синтаксический разбор объекта и возвращает строку запроса. - - - -Параметр separator является подстрокой, -разделяющей в строке запроса пары ключей и значений, -по умолчанию “&”. - - - -Параметр equal является подстрокой, -разделяющей в строке запроса ключи и значения, -по умолчанию “=”. - - - -Параметр options должен быть -объектом со следующими ключами: - -encodeURIComponent -функция - -Функция, используемая при декодировании -URL-небезопасных символов в в процентно-кодированные символы в строке запроса, -по умолчанию -querystring.escape(). - - - - - - -По умолчанию символы, требующие процентной кодировки внутри строки запроса, -кодируются в UTF-8. -Если требуется другая кодировка, то -необходимо указать опцию encodeURIComponent. - - - -Пример: - -querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], 123: '' }); - -результат: - -'foo=bar&baz=qux&baz=quux&123=' - - - - - -querystring.unescape(строка) - - -Осуществляет декодирование процентно-кодированных символов URL -в строке, -возвращает неэкранированную строку запроса. -Метод используется методом -querystring.parse() -и не должен использоваться напрямую. - - - - - - -
- -
- -
- diff --git a/xml/ru/docs/njs/typescript.xml b/xml/ru/docs/njs/typescript.xml deleted file mode 100644 --- a/xml/ru/docs/njs/typescript.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - -
- -
- - -TypeScript—это -типизированное подмножество JavaScript, -которое компилируется в обычный JavaScript. - - - -TypeScript поддерживает файлы деклараций, в которых содержится -типизированная информация существующих библиотек JavaScript. -С их помощью программы могут использовать значения в файлах также, -если бы эти значения были статически типизированными сущностями TypeScript. - - - -В njs файлы деклараций TypeScript предоставляются для -API и могут использоваться при: - - - -автозаполнении и проверки API в редакторе - - - -создании типобезопасного njs-кода. - - - - - -
- - -
- - - -$ hg clone http://hg.nginx.org/njs -$ cd njs && ./configure && make ts -$ ls build/ts/ -njs_core.d.ts -njs_shell.d.ts -ngx_http_js_module.d.ts -ngx_stream_js_module.d.ts - - - -
- - -
- - -Файлы деклараций *.d.ts необходимо поместить в место, -доступное редактору: - - - -test.js: - -/// <reference path="ngx_http_js_module.d.ts" /> -/** - * @param {NginxHTTPRequest} r - * */ -function content_handler(r) { - r.headersOut['content-type'] = 'text/plain'; - r.return(200, "Hello"); -} - - - -
- - -
- - -test.ts: - -/// <reference path="ngx_http_js_module.d.ts" /> -function content_handler(r: NginxHTTPRequest) { - r.headersOut['content-type'] = 'text/plain'; - r.return(200, "Hello from TypeScript"); -} - -Установка TypeScript: - -# npm install -g typescript - -Компиляция TypeScript: - -$ tsc test.ts -$ cat test.js - -Созданный файл test.js может использоваться напрямую в njs. - - -
- -
diff --git a/xml/ru/docs/stream/ngx_stream_js_module.xml b/xml/ru/docs/stream/ngx_stream_js_module.xml deleted file mode 100644 --- a/xml/ru/docs/stream/ngx_stream_js_module.xml +++ /dev/null @@ -1,793 +0,0 @@ - - - - - - - - -
- - -Модуль ngx_stream_js_module позволяет задавать -обработчики на njs — -подмножестве языка JavaScript. - - - -Инструкция по сборке и установке доступны -здесь. - - -
- - -
- - -Пример работает начиная с версии -0.4.0. - -stream { - js_import stream.js; - - js_set $bar stream.bar; - js_set $req_line stream.req_line; - - server { - listen 12345; - - js_preread stream.preread; - return $req_line; - } - - server { - listen 12346; - - js_access stream.access; - proxy_pass 127.0.0.1:8000; - js_filter stream.header_inject; - } -} - -http { - server { - listen 8000; - location / { - return 200 $http_foo\n; - } - } -} - - - - -Файл stream.js: - -var line = ''; - -function bar(s) { - var v = s.variables; - s.log("hello from bar() handler!"); - return "bar-var" + v.remote_port + "; pid=" + v.pid; -} - -function preread(s) { - s.on('upload', function (data, flags) { - var n = data.indexOf('\n'); - if (n != -1) { - line = data.substr(0, n); - s.done(); - } - }); -} - -function req_line(s) { - return line; -} - -// Чтение строки HTTP-запроса. -// Получение байт в 'req' до того как -// будет прочитана строка запроса. -// Добавление HTTP-заголовка в запрос клиента - -var my_header = 'Foo: foo'; -function header_inject(s) { - var req = ''; - s.on('upload', function(data, flags) { - req += data; - var n = req.search('\n'); - if (n != -1) { - var rest = req.substr(n + 1); - req = req.substr(0, n + 1); - s.send(req + my_header + '\r\n' + rest, flags); - s.off('upload'); - } - }); -} - -function access(s) { - if (s.remoteAddress.match('^192.*')) { - s.deny(); - return; - } - - s.allow(); -} - -export default {bar, preread, req_line, header_inject, access}; - - - -
- - -
- - -функция | модуль.функция - -stream -server - - -Задаёт функцию njs, которая будет вызываться в -access-фазе. -Начиная с 0.4.0 -можно ссылаться на функцию модуля. - - - -Функция вызывается однократно при первом достижении сессией -access-фазы. -Функция вызывается со следующими аргументами: - - -s - -объект stream-сессии - - - - - - -В этой фазе может происходить инициализация, -также при помощи метода -s.on() -может регистрироваться вызов -для каждого входящего блока данных пока не будет вызван один из методов: -s.done() -s.decline(), -s.allow(). -При вызове любого из этих методов обработка сессии -переходит на следующую фазу -и все текущие вызовы -s.on() -сбрасываются. - - - - - - -размер -16k -stream -server -0.7.4 - - -Задаёт размер буфера, который будет использоваться -для чтения и записи для -Fetch API. - - - - - - -шифры -HIGH:!aNULL:!MD5 -stream -server -0.7.0 - - -Описывает разрешённые шифры для HTTPS-соединений -при помощи Fetch API. -Шифры задаются в формате, поддерживаемом библиотекой OpenSSL. - - - -Полный список можно посмотреть с помощью команды -“openssl ciphers”. - - - - - - -размер -1m -stream -server -0.7.4 - - -Задаёт максимальный размер ответа, полученного -при помощи Fetch API. - - - - - - - - [TLSv1] - [TLSv1.1] - [TLSv1.2] - [TLSv1.3] -TLSv1 TLSv1.1 TLSv1.2 -stream -server -0.7.0 - - -Разрешает указанные протоколы для HTTPS-соединений -при помощи Fetch API. - - - - - - -время -60s -stream -server -0.7.4 - - -Задаёт таймаут при чтении и записи -при помощи Fetch API. -Таймаут устанавливается не на всю передачу ответа, -а только между двумя операциями чтения. -Если по истечении этого времени данные не передавались, соединение закрывается. - - - - - - -файл - -stream -server -0.7.0 - - -Задаёт файл с доверенными сертификатами CA в формате PEM, -используемыми при -проверке -HTTPS-сертификата -при помощи Fetch API. - - - - - - -on | off -on -stream -server -0.7.4 - - -Разрешает или запрещает проверку сертификата HTTPS-сервера -при помощи Fetch API. - - - - - - -число -100 -stream -server -0.7.0 - - -Устанавливает глубину проверки в цепочке HTTPS-сертификатов -при помощи Fetch API. - - - - - - -функция | модуль.функция - -stream -server - - -Задаёт фильтр данных. -Начиная с 0.4.0 -можно ссылаться на функцию модуля. -Функция фильтра вызывается однократно при первом достижении сессией -content-фазы. - - - -Функция фильтра вызывается со следующими аргументами: - -s - -объект stream-сессии - - - - - - -В этой фазе может происходить инициализация, -также при помощи метода -s.on() -может регистрироваться вызов -для каждого входящего блока данных. -Для отмены регистрации вызова и отмены фильтра -можно использовать метод -s.off(). - - - - -Так как обработчик js_filter -должен сразу возвращать результат, -то поддерживаются только синхронные операции. -Таким образом, асинхронные операции, например -ngx.fetch() -или -setTimeout(), -не поддерживаются. - - - - - - - -модуль.js | -имя_экспорта from модуль.js - -stream -server -0.4.0 - - -Импортирует модуль, позволяющий задавать обработчики location и переменных -на njs. -Имя_экспорта является пространством имён -при доступе к функциям модуля. -Если имя_экспорта не задано, -то пространством имён будет являться имя модуля. - -js_import stream.js; - -В примере при доступе к экспорту в качестве -пространства имён используется имя модуля stream. -Если импортируемый модуль экспортирует foo(), -то для доступа используется stream.foo. - - - -Директив js_import может быть несколько. - - - - -Директива может быть указана -на уровне server -начиная с 0.7.7. - - - - - - - -файл - -stream - - -Задаёт файл, который позволяет задавать обработчики server и переменных на njs: - -nginx.conf: -js_include stream.js; -js_set $js_addr address; -server { - listen 127.0.0.1:12345; - return $js_addr; -} - -stream.js: -function address(s) { - return s.remoteAddress; -} - - - - -Директива устарела в версии -0.4.0 -и была удалена в версии -0.7.1. -Вместо неё следует использовать директиву . - - - - - - -имя.json | -имя from файл.json - -stream -server -0.7.8 - - -Предварительно загружает -неизменяемый объект -во время конфигурации. -Имя используется в качестве имени глобальной переменной, -через которую объект доступен в коде njs. -Если имя не указано, -то будет использоваться имя файла. - -js_preload_object map.json; - -В примере map используется в качестве имени -во время доступа к предварительно загруженному объекту. - - - -Директив js_preload_object может быть несколько. - - - - - - -функция | модуль.функция - -stream -server - - -Задаёт функцию njs, которая будет вызываться в -preread-фазе. -Начиная с 0.4.0 -можно ссылаться на функцию модуля. - - - -Функция вызывается однократно при первом достижении сессией -preread-фазы. -Функция вызывается со следующими аргументами: - - -s - -объект stream-сессии - - - - - - -В этой фазе может происходить инициализация, -также при помощи метода -s.on() -может регистрироваться вызов -для каждого входящего блока данных пока не будет вызван один из методов: -s.done() -s.decline(), -s.allow(). -При вызове любого из этих методов обработка сессии -переходит на следующую фазу -и все текущие вызовы -s.on() -сбрасываются. - - - - -Так как обработчик js_preread -должен сразу возвращать результат, -то поддерживаются только синхронные операции. -Таким образом, асинхронные операции, например -ngx.fetch() -или -setTimeout(), -не поддерживаются. -Тем не менее асинхронные операции поддерживаются в вызовах -s.on() -в -preread-фазе. -Подробнее см. -пример. - - - - - - - - -путь - -stream -server -0.3.0 - - -Задаёт дополнительный путь для модулей njs. - - - - -Директива может быть указана -на уровне server -начиная с 0.7.7. - - - - - - - -функция | - модуль.функция - [interval=время] - [jitter=число] - [worker_affinity=маска] - -server -0.8.1 - - -Задаёт периодичность запуска обработчика содержимого. -В качестве первого аргумента обработчик получает -объект сессии, -также у обработчика есть доступ к глобальным объектам таким как -ngx. - - - -Необязательный параметр interval -задаёт интервал между двумя последовательными запусками, -по умолчанию 5 секунд. - - - -Необязательный параметр jitter -задаёт время, в пределах которого -случайным образом задерживается каждый запуск, -по умолчанию задержки нет. - - - -По умолчанию js_handler выполняется для рабочего процесса 0. -Необязательный параметр worker_affinity -позволяет указать рабочий процесс, -для которого будет выполняться обработчик содержимого location. -Рабочие процессы задаются битовой маской разрешённых к использованию рабочих -процессов. -Маска all позволяет обработчику выполняться -для всех рабочих процессов. - - - -Пример: - -example.conf: - -location @periodics { - # интервал выполнения 1 минута для рабочего процесса 0 - js_periodic main.handler interval=60s; - - # интервал выполнения 1 минута для всех рабочих процессов - js_periodic main.handler interval=60s worker_affinity=all; - - # интервал выполнения 1 минута для рабочих процессов 1 и 3 - js_periodic main.handler interval=60s worker_affinity=0101; - - resolver 10.0.0.1; - js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem; -} - -example.js: - -async function handler(s) { - let reply = await ngx.fetch('https://nginx.org/en/docs/njs/'); - let body = await reply.text(); - - ngx.log(ngx.INFO, body); -} - - - - - - - - -$переменная функция | -модуль.функция - -stream -server - - -Задаёт функцию njs -для указанной переменной. -Начиная с 0.4.0 -можно ссылаться на функцию модуля. - - - -Функция вызывается в момент -первого обращения к переменной для данного запроса. -Точный момент вызова функции зависит от -фазы, -в которой происходит обращение к переменной. -Это можно использовать для реализации дополнительной логики, -не относящейся к вычислению переменной. -Например, если переменная указана -в директиве , -то её обработчик не будет выполняться до фазы записи в лог. -Этот обработчик также может использоваться для выполнения процедур -непосредственно перед освобождением запроса. - - - - -Так как обработчик js_set -должен сразу возвращать результат, -то поддерживаются только синхронные операции. -Таким образом, асинхронные операции, например -ngx.fetch() -или -setTimeout(), -не поддерживаются. - - - - - -Директива может быть указана -на уровне server -начиная с 0.7.7. - - - - - - - - - zone=имя:размер - [timeout=время] - [type=строка|число] - [evict] - -stream -0.8.0 - - -Задаёт имя и размер зоны разделяемой памяти, -в которой хранится -словарь ключей и значений, -разделяемый между рабочими процессами. - - - -По умолчанию в качестве ключа и значения используется строка. -Необязательный параметр type -позволяет изменить тип значения на число. - - - -Необязательный параметр timeout задаёт время, -по завершении которого все записи в словаре удаляются из зоны. - - - -Необязательный параметр evict удаляет самую старую -пару ключ-значение при переполнении зоны. - - - -Пример: - -example.conf: - # Создаётся словарь размером 1Мб со строковыми значениями, - # пары ключ-значение удаляются при отсутствии активности в течение 60 секунд: - js_shared_dict_zone zone=foo:1M timeout=60s; - - # Создаётся словарь размером 512Кб со строковыми значениями, - # удаляется самая старая пара ключ-значение при переполнении зоны: - js_shared_dict_zone zone=bar:512K timeout=30s evict; - - # Создаётся постоянный словарь размером 32Кб с числовыми значениями: - js_shared_dict_zone zone=num:32k type=number; - -example.js: - function get(r) { - r.return(200, ngx.shared.foo.get(r.args.key)); - } - - function set(r) { - r.return(200, ngx.shared.foo.set(r.args.key, r.args.value)); - } - - function del(r) { - r.return(200, ngx.shared.bar.delete(r.args.key)); - } - - function increment(r) { - r.return(200, ngx.shared.num.incr(r.args.key, 2)); - } - - - - - - - -$переменная [значение] - -stream -server -0.5.3 - - -Объявляет -перезаписываемую -переменную. -В качестве значения можно использовать текст, переменные и их комбинации. - - - - -Директива может быть указана -на уровне server -начиная с 0.7.7. - - - - - -
- - -
- - -Каждый stream-обработчик njs получает один аргумент, -объект stream-сессии. - - -
- -
diff --git a/xml/ru/index.xml b/xml/ru/index.xml --- a/xml/ru/index.xml +++ b/xml/ru/index.xml @@ -8,7 +8,7 @@
+ rev="163">
@@ -203,11 +203,7 @@ PUT, DELETE, MKCOL, COPY и MOVE; -Встроенный Perl; - - - -сценарный язык njs. +Встроенный Perl. @@ -330,11 +326,7 @@ TCP и UDP; -A/B-тестирование; - - - -сценарный язык njs. +A/B-тестирование.