Mercurial > hg > nginx-site
changeset 3048:1bb11d9ca0ba
Free nginx: removed njs which is maintained separately.
author | Maxim Dounin <mdounin@mdounin.ru> |
---|---|
date | Wed, 14 Feb 2024 20:06:00 +0300 |
parents | 185dd0a00e10 |
children | 12f3dbd5ff18 |
files | GNUmakefile xml/en/GNUmakefile xml/en/docs/dev/development_guide.xml xml/en/docs/http/ngx_http_js_module.xml xml/en/docs/index.xml xml/en/docs/njs/changes.xml xml/en/docs/njs/cli.xml xml/en/docs/njs/compatibility.xml xml/en/docs/njs/examples.xml xml/en/docs/njs/index.xml xml/en/docs/njs/install.xml xml/en/docs/njs/node_modules.xml xml/en/docs/njs/preload_objects.xml xml/en/docs/njs/reference.xml xml/en/docs/njs/security.xml xml/en/docs/njs/typescript.xml xml/en/docs/stream/ngx_stream_js_module.xml xml/en/index.xml xml/ru/GNUmakefile xml/ru/docs/http/ngx_http_js_module.xml xml/ru/docs/index.xml xml/ru/docs/njs/cli.xml xml/ru/docs/njs/compatibility.xml xml/ru/docs/njs/examples.xml xml/ru/docs/njs/index.xml xml/ru/docs/njs/install.xml xml/ru/docs/njs/node_modules.xml xml/ru/docs/njs/preload_objects.xml xml/ru/docs/njs/reference.xml xml/ru/docs/njs/typescript.xml xml/ru/docs/stream/ngx_stream_js_module.xml xml/ru/index.xml |
diffstat | 32 files changed, 10 insertions(+), 23828 deletions(-) [+] |
line wrap: on
line diff
--- a/GNUmakefile Wed Feb 14 20:05:57 2024 +0300 +++ b/GNUmakefile Wed Feb 14 20:06:00 2024 +0300 @@ -271,7 +271,7 @@ 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 \
--- a/xml/en/GNUmakefile Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/en/GNUmakefile Wed Feb 14 20:06:00 2024 +0300 @@ -58,7 +58,6 @@ 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 @@ 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 @@ 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 \
--- a/xml/en/docs/dev/development_guide.xml Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/en/docs/dev/development_guide.xml Wed Feb 14 20:06:00 2024 +0300 @@ -7519,8 +7519,7 @@ <listitem> Is it possible to solve an issue using built-in scripting languages, -such as <link doc="../http/ngx_http_perl_module.xml">Perl</link> -or <link doc="../njs/index.xml">njs</link>? +such as <link doc="../http/ngx_http_perl_module.xml">Perl</link>? </listitem> </list>
--- a/xml/en/docs/http/ngx_http_js_module.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,812 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE module SYSTEM "../../../../dtd/module.dtd"> - -<module name="Module ngx_http_js_module" - link="/en/docs/http/ngx_http_js_module.html" - lang="en" - rev="46"> - -<section id="summary"> - -<para> -The <literal>ngx_http_js_module</literal> module is used to implement -location and variable handlers -in <link doc="../njs/index.xml">njs</link> — -a subset of the JavaScript language. -</para> - -<para> -Download and install instructions are available -<link doc="../njs/install.xml">here</link>. -</para> - -</section> - - -<section id="example" name="Example Configuration"> - -<para> -The example works since -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>. -<example> -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; - } - } -} -</example> -</para> - -<para> -The <path>http.js</path> file: -<example> -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}; -</example> -</para> - -</section> - - -<section id="directives" name="Directives"> - -<directive name="js_body_filter"> -<syntax><value>function</value> | <value>module.function</value> -[<value>buffer_type</value>=<value>string</value> | <value>buffer</value>]</syntax> -<default/> -<context>location</context> -<context>if in location</context> -<context>limit_except</context> -<appeared-in>0.5.2</appeared-in> - -<para> -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: - -<list type="tag"> -<tag-name><literal>r</literal></tag-name> -<tag-desc> -the <link doc="../njs/reference.xml" id="http">HTTP request</link> object -</tag-desc> - -<tag-name><literal>data</literal></tag-name> -<tag-desc> -the incoming data chunk, -may be a string or Buffer -depending on the <literal>buffer_type</literal> value, -by default is a string. -</tag-desc> - -<tag-name><literal>flags</literal></tag-name> -<tag-desc> -an object with the following properties: -<list type="tag"> -<tag-name><literal>last</literal></tag-name> -<tag-desc> -a boolean value, true if data is a last buffer. -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -<para> -The filter function can pass its own modified version -of the input data chunk to the next body filter by calling -<link doc="../njs/reference.xml" id="r_sendbuffer"><literal>r.sendBuffer()</literal></link>. -For example, to transform all the lowercase letters in the response body: -<example> -function filter(r, data, flags) { - r.sendBuffer(data.toLowerCase(), flags); -} -</example> -To stop filtering (following data chunks will be passed to client -without calling <literal>js_body_filter</literal>), -<link doc="../njs/reference.xml" id="r_done"><literal>r.done()</literal></link> -can be used. -</para> - -<para> -If the filter function changes the length of the response body, then -it is required to clear out the <header>Content-Length</header> response header -(if any) in -<link id="js_header_filter"><literal>js_header_filter</literal></link> -to enforce chunked transfer encoding. -</para> - -<para> -<note> -As the <literal>js_body_filter</literal> handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -<link doc="../njs/reference.xml" id="r_subrequest">r.subrequest()</link> -or -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link> -are not supported. -</note> -</para> - -<para> -<note> -The directive can be specified inside the -<link doc="../http/ngx_http_rewrite_module.xml" id="if">if</link> block -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_content"> -<syntax><value>function</value> | <value>module.function</value></syntax> -<default/> -<context>location</context> -<context>if in location</context> -<context>limit_except</context> - -<para> -Sets an njs function as a location content handler. -Since <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>, -a module function can be referenced. -</para> - -<para> -<note> -The directive can be specified inside the -<link doc="../http/ngx_http_rewrite_module.xml" id="if">if</link> block -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_fetch_buffer_size"> -<syntax><value>size</value></syntax> -<default>16k</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Sets the <value>size</value> of the buffer used for reading and writing -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_ciphers"> -<syntax><value>ciphers</value></syntax> -<default>HIGH:!aNULL:!MD5</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Specifies the enabled ciphers for HTTPS requests -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -The ciphers are specified in the format understood by the -OpenSSL library. -</para> - -<para> -The full list can be viewed using the -“<command>openssl ciphers</command>” command. -</para> - -</directive> - - -<directive name="js_fetch_max_response_buffer_size"> -<syntax><value>size</value></syntax> -<default>1m</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Sets the maximum <value>size</value> of the response received -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_protocols"> -<syntax> - [<literal>TLSv1</literal>] - [<literal>TLSv1.1</literal>] - [<literal>TLSv1.2</literal>] - [<literal>TLSv1.3</literal>]</syntax> -<default>TLSv1 TLSv1.1 TLSv1.2</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Enables the specified protocols for HTTPS requests -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_timeout"> -<syntax><value>time</value></syntax> -<default>60s</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Defines a timeout for reading and writing -for <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -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. -</para> - -</directive> - - -<directive name="js_fetch_trusted_certificate"> -<syntax><value>file</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Specifies a <value>file</value> with trusted CA certificates in the PEM format -used to -<link doc="../njs/reference.xml" id="fetch_verify">verify</link> -the HTTPS certificate -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify"> -<syntax><literal>on</literal> | <literal>off</literal></syntax> -<default>on</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Enables or disables verification of the HTTPS server certificate -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify_depth"> -<syntax><value>number</value></syntax> -<default>100</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Sets the verification depth in the HTTPS server certificates chain -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_header_filter"> -<syntax><value>function</value> | <value>module.function</value></syntax> -<default/> -<context>location</context> -<context>if in location</context> -<context>limit_except</context> -<appeared-in>0.5.1</appeared-in> - -<para> -Sets an njs function as a response header filter. -The directive allows changing arbitrary header fields of a response header. -</para> - -<para> -<note> -As the <literal>js_header_filter</literal> handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -<link doc="../njs/reference.xml" id="r_subrequest">r.subrequest()</link> -or -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link> -are not supported. -</note> -</para> - -<para> -<note> -The directive can be specified inside the -<link doc="../http/ngx_http_rewrite_module.xml" id="if">if</link> block -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_import"> -<syntax><value>module.js</value> | -<value>export_name from module.js</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.4.0</appeared-in> - -<para> -Imports a module that implements location and variable handlers in njs. -The <literal>export_name</literal> is used as a namespace -to access module functions. -If the <literal>export_name</literal> is not specified, -the module name will be used as a namespace. -<example> -js_import http.js; -</example> -Here, the module name <literal>http</literal> is used as a namespace -while accessing exports. -If the imported module exports <literal>foo()</literal>, -<literal>http.foo</literal> is used to refer to it. -</para> - -<para> -Several <literal>js_import</literal> directives can be specified. -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> and <literal>location</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_include"> -<syntax><value>file</value></syntax> -<default/> -<context>http</context> - -<para> -Specifies a file that implements location and variable handlers in njs: -<example> -nginx.conf: -js_include http.js; -location /version { - js_content version; -} - -http.js: -function version(r) { - r.return(200, njs.version); -} -</example> -</para> - -<para> -The directive was made obsolete in version -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -and was removed in version -<link doc="../njs/changes.xml" id="njs0.7.1">0.7.1</link>. -The <link id="js_import"/> directive should be used instead. -</para> - -</directive> - - -<directive name="js_path"> -<syntax> -<value>path</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.3.0</appeared-in> - -<para> -Sets an additional path for njs modules. -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> and <literal>location</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_periodic"> -<syntax><value>function</value> | - <value>module.function</value> - [<literal>interval</literal>=<value>time</value>] - [<literal>jitter</literal>=<value>number</value>] - [<literal>worker_affinity</literal>=<value>mask</value>]</syntax> -<default/> -<context>location</context> -<appeared-in>0.8.1</appeared-in> - -<para> -Specifies a content handler to run at regular interval. -The handler receives a -<link doc="../njs/reference.xml" id="periodic_session">session object</link> -as its first argument, -it also has access to global objects such as -<link doc="../njs/reference.xml" id="ngx">ngx</link>. -</para> - -<para> -The optional <literal>interval</literal> parameter -sets the interval between two consecutive runs, -by default, 5 seconds. -</para> - -<para> -The optional <literal>jitter</literal> parameter sets the time within which -the location content handler will be randomly delayed, -by default, there is no delay. -</para> - -<para> -By default, the <literal>js_handler</literal> is executed on worker process 0. -The optional <literal>worker_affinity</literal> 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 <literal>all</literal> mask allows the handler to be executed -in all worker processes. -</para> - -<para> -Example: -<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); -} -</example> -</para> - -</directive> - - -<directive name="js_preload_object"> -<syntax><value>name.json</value> | -<value>name</value> from <value>file.json</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.8</appeared-in> - -<para> -Preloads an -<link doc="../njs/preload_objects.xml">immutable object</link> -at configure time. -The <literal>name</literal> is used as a name of the global variable -though which the object is available in njs code. -If the <literal>name</literal> is not specified, -the file name will be used instead. -<example> -js_preload_object map.json; -</example> -Here, the <literal>map</literal> is used as a name -while accessing the preloaded object. -</para> - -<para> -Several <literal>js_preload_object</literal> directives can be specified. -</para> - -</directive> - - -<directive name="js_set"> -<syntax> -<value>$variable</value> <value>function</value> | -<value>module.function</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> - -<para> -Sets an njs <literal>function</literal> -for the specified <literal>variable</literal>. -Since <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>, -a module function can be referenced. -</para> - -<para> -The function is called when -the variable is referenced for the first time for a given request. -The exact moment depends on a -<link doc="../dev/development_guide.xml" id="http_phases">phase</link> -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 -<link doc="ngx_http_log_module.xml" id="log_format"/> 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. -</para> - -<para> -<note> -As the <literal>js_set</literal> handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -<link doc="../njs/reference.xml" id="r_subrequest">r.subrequest()</link> -or -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link> -are not supported. -</note> -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> and <literal>location</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_shared_dict_zone"> -<syntax> - <literal>zone</literal>=<value>name</value>:<value>size</value> - [<literal>timeout</literal>=<value>time</value>] - [<literal>type</literal>=<literal>string</literal>|<literal>number</literal>] - [<literal>evict</literal>]</syntax> -<default/> -<context>http</context> -<appeared-in>0.8.0</appeared-in> - -<para> -Sets the <value>name</value> and <value>size</value> of the shared memory zone -that keeps the -key-value <link doc="../njs/reference.xml" id="dict">dictionary</link> -shared between worker processes. -</para> - -<para> -By default the shared dictionary uses a string as a key and a value. -The optional <literal>type</literal> parameter -allows redefining the value type to number. -</para> - -<para> -The optional <literal>timeout</literal> parameter sets -the time after which all shared dictionary entries are removed from the zone. -</para> - -<para> -The optional <literal>evict</literal> parameter removes the oldest -key-value pair when the zone storage is exhausted. -</para> - -<para> -Example: -<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)); - } -</example> -</para> - -</directive> - - -<directive name="js_var"> -<syntax><value>$variable</value> [<value>value</value>]</syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.5.3</appeared-in> - -<para> -Declares -a <link doc="../njs/reference.xml" id="r_variables">writable</link> -variable. -The value can contain text, variables, and their combination. -The variable is not overwritten after a redirect -unlike variables created with the -<link doc="ngx_http_rewrite_module.xml" id="set"/> directive. -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> and <literal>location</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - -</section> - - -<section id="arguments" name="Request Argument"> - -<para> -Each HTTP njs handler receives one argument, a request -<link doc="../njs/reference.xml" id="http">object</link>. -</para> - -</section> - -</module>
--- a/xml/en/docs/index.xml Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/en/docs/index.xml Wed Feb 14 20:06:00 2024 +0300 @@ -8,7 +8,7 @@ <article name="nginx documentation" link="/en/docs/" lang="en" - rev="51" + rev="52" toc="no"> @@ -98,14 +98,6 @@ <list type="bullet"> <listitem> -<link doc="njs/index.xml">Scripting with njs</link> -</listitem> - -</list> - -<list type="bullet"> - -<listitem> <link url="http://www.aosabook.org/en/nginx.html">Chapter “nginx” in “The Architecture of Open Source Applications”</link> </listitem> @@ -301,11 +293,6 @@ </listitem> <listitem> -<link doc="http/ngx_http_js_module.xml"> -ngx_http_js_module</link> -</listitem> - -<listitem> <link doc="http/ngx_http_limit_conn_module.xml"> ngx_http_limit_conn_module</link> </listitem> @@ -513,11 +500,6 @@ </listitem> <listitem> -<link doc="stream/ngx_stream_js_module.xml"> -ngx_stream_js_module</link> -</listitem> - -<listitem> <link doc="stream/ngx_stream_limit_conn_module.xml"> ngx_stream_limit_conn_module</link> </listitem>
--- a/xml/en/docs/njs/changes.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,6793 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Changes" - link="/en/docs/njs/changes.html" - lang="en" - rev="68" - toc="no"> - -<section id="njs0.8.3" name="Changes with njs 0.8.3"> - -<para> -Release Date: -07 February 2024 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="headers_set"><literal>Headers.set()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="../http/ngx_http_js_module.xml" id="js_set"/> -with <literal>Buffer</literal> values. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="dict_clear"><literal>clear()</literal></link> -method of a shared dictionary when a timeout is not specified. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="../http/ngx_http_stub_status_module.xml">stub_status</link> -statistics when -<link doc="../http/ngx_http_js_module.xml" id="js_periodic">js_periodic</link> -is enabled. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed building with -<link url="https://gitlab.gnome.org/GNOME/libxml2">libxml2</link> 2.12 -and later. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Date</literal> constructor for overflows -and with <literal>NaN</literal> values. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed underflow in -<link doc="reference.xml" id="querystring_parse"><literal>querystring.parse()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed potential buffer overread in -<literal>String.prototype.match()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of <literal>for-in</literal> loops. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of -hexadecimal, octal, and binary literals with no digits. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.8.2" name="Changes with njs 0.8.2"> - -<para> -Release Date: -24 October 2023 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -introduced -<link doc="reference.xml" id="console">console</link> object. -The following methods were introduced: -<link doc="reference.xml" id="console_error"><literal>error()</literal></link>, -<link doc="reference.xml" id="console_info"><literal>info()</literal></link>, -<link doc="reference.xml" id="console_log"><literal>log()</literal></link>, -<link doc="reference.xml" id="console_time"><literal>time()</literal></link>, -<link doc="reference.xml" id="console_time_end"><literal>timeEnd()</literal></link>, -<link doc="reference.xml" id="console_warn"><literal>warn()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>HEAD</literal> response handling with large Content-Length in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="dict_items"><literal>items()</literal></link> -method for a shared dictionary. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="dict_delete"><literal>delete()</literal></link> -method for a shared dictionary. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -extended -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> module. -Added -<link doc="reference.xml" id="fs_existssync"><literal>fs.existsSync()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="xml"><literal>xml</literal></link> module. -Broken XML exception handling in -<link doc="reference.xml" id="xml_parse"><literal>xml.parse()</literal></link> -method was fixed. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Regexp.prototype.exec()</literal> with global regexp and Unicode input. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.8.1" name="Changes with njs 0.8.1"> - -<para> -Release Date: -12 September 2023 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -introduced the <literal>js_periodic</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_periodic">http</link> -and -<link doc="../stream/ngx_stream_js_module.xml" id="js_periodic">stream</link> -that allows specifying a JS handler to run at regular intervals. -</para> -</listitem> - -<listitem> -<para> -Feature: -implemented -<link doc="reference.xml" id="dict_items"><literal>items()</literal></link> -method of a -<link doc="reference.xml" id="ngx_shared">shared dictionary</link>. -The method returns all the non-expired key-value pairs. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="dict_size"><literal>size()</literal></link> -and -<link doc="reference.xml" id="dict_keys"><literal>keys()</literal></link> -methods of a -<link doc="reference.xml" id="ngx_shared">shared dictionary</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed erroneous exception in -<link doc="reference.xml" id="r_internal_redirect"><literal>r.internalRedirect()</literal></link> -introduced in <link id="njs0.8.0">0.8.0</link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed incorrect order of keys in -<literal>Object.getOwnPropertyNames()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.8.0" name="Changes with njs 0.8.0"> - -<para> -Release Date: -06 July 2023 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Change: -removed special treatment of forbidden headers in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link> -introduced in <link id="njs0.7.10">0.7.10</link>. -</para> -</listitem> - -<listitem> -<para> -Change: -removed deprecated since <link id="njs0.5.0">0.5.0</link> -<link doc="reference.xml" id="r_request_body"><literal>r.requestBody</literal></link> -and -<link doc="reference.xml" id="r_response_body"><literal>r.responseBody</literal></link> -in -<link doc="../http/ngx_http_js_module.xml"><literal>http</literal></link> -module. -</para> -</listitem> - -<listitem> -<para> -Change: -throwing an exception in -<link doc="reference.xml" id="r_internal_redirect"><literal>r.internalRedirect()</literal></link> -while filtering in -<link doc="../http/ngx_http_js_module.xml"><literal>http</literal></link> -module. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced more global -<link doc="reference.xml" id="ngx"><literal>nginx</literal></link> properties: -<link doc="reference.xml" id="ngx_build"><literal>ngx.build</literal></link>, -<link doc="reference.xml" id="ngx_conf_file_path"><literal>ngx.conf_file_path</literal></link>, -<link doc="reference.xml" id="ngx_error_log_path"><literal>ngx.error_log_path</literal></link>, -<link doc="reference.xml" id="ngx_prefix"><literal>ngx.prefix</literal></link>, -<link doc="reference.xml" id="ngx_version"><literal>ngx.version</literal></link>, -<link doc="reference.xml" id="ngx_version_number"><literal>ngx.version_number</literal></link>, -and -<link doc="reference.xml" id="ngx_worker_id"><literal>ngx.worker_id</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced the <literal>js_shared_dict_zone</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_shared_dict_zone">http</link> -and -<link doc="../stream/ngx_stream_js_module.xml" id="js_shared_dict_zone">stream</link> -that allows declaring a dictionary shared between worker processes. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced global -<link doc="reference.xml" id="ngx_shared"><literal>nginx.shared</literal></link> -methods and properties for working with shared dictionaries. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added compile-time options to disable njs modules. -For example, to disable libxslt-related code: -<example> -NJS_LIBXSLT=NO ./configure .. --add-module=/path/to/njs/module -</example> -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="r_status"><literal>r.status</literal></link> -setter when filtering in -<link doc="../http/ngx_http_js_module.xml"><literal>http</literal></link> -module. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed setting of Location header in -<link doc="../http/ngx_http_js_module.xml"><literal>http</literal></link> -module. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Change: -native methods are provided with <literal>retval</literal> argument. -This change breaks compatibility with C extension for njs -requiring the modification of the code. -</para> -</listitem> - -<listitem> -<para> -Change: -non-compliant deprecated String methods were removed. -The following methods were removed: -<link doc="reference.xml" id="string_bytesfrom"><literal>String.bytesFrom()</literal></link>, -<link doc="reference.xml" id="string_frombytes"><literal>String.prototype.fromBytes()</literal></link>, -<link doc="reference.xml" id="string_fromutf8"><literal>String.prototype.fromUTF8()</literal></link>, -<link doc="reference.xml" id="string_tobytes"><literal>String.prototype.toBytes()</literal></link>, -<link doc="reference.xml" id="string_toutf8"><literal>String.prototype.toUTF8()</literal></link>, -<link doc="reference.xml" id="string_toutf8"><literal>String.prototype.toString(<value>encoding</value>)</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Change: -removed support for building with GNU readline. -</para> -</listitem> - -<listitem> -<para> -Feature: -added ES13-compliant <literal>Array</literal> methods: -<literal>Array.from()</literal>, -<literal>Array.prototype.toSorted()</literal>, -<literal>Array.prototype.toSpliced()</literal>, -<literal>Array.prototype.toReversed()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added ES13-compliant <literal>TypedArray</literal> methods: -<literal>%TypedArray%.prototype.toSorted()</literal>, -<literal>%TypedArray%.prototype.toSpliced()</literal>, -<literal>%TypedArray%.prototype.toReversed()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="cryptokey"><literal>CryptoKey</literal></link> -properties in -<link doc="reference.xml" id="builtin_crypto">WebCrypto API</link>. -The following properties were added: -<link doc="reference.xml" id="cryptokey_alg"><literal>algorithm</literal></link>, -<link doc="reference.xml" id="cryptokey_extractable"><literal>extractable</literal></link>, -<link doc="reference.xml" id="cryptokey_type"><literal>type</literal></link>, -<link doc="reference.xml" id="cryptokey_usages"><literal>usages</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>retval</literal> of -<link doc="reference.xml" id="crypto_get_random_values"><literal>сrypto.getRandomValues()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed evaluation of computed property names with function expressions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed implicit name for a function expression declared in arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of <literal>for-in</literal> loops. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Date.parse()</literal> with ISO-8601 format and UTC time offset. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.12" name="Changes with njs 0.7.12"> - -<para> -Release Date: -10 April 2023 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed <literal>Headers()</literal> constructor in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="crypto_hash_copy"><literal>Hash.copy()</literal></link> -method in -<link doc="reference.xml" id="crypto">crypto</link> module. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="zlib">zlib</link> -module. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added support for -<literal>export {name as default}</literal> statement. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Number</literal> constructor according to the spec. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.11" name="Changes with njs 0.7.11"> - -<para> -Release Date: -09 March 2023 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -added missed linking with -<link url="https://gitlab.gnome.org/GNOME/libxml2">libxml2</link> -for the dynamic module. -The bug was introduced in <link id="njs0.7.10">0.7.10</link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="xml_node">XMLNode API</link> -to modify XML documents. -</para> -</listitem> - -<listitem> -<para> -Change: -removed <literal>XML_PARSE_DTDVALID</literal> during parsing of an XML document -due to security implications. -The issue was introduced in <link id="njs0.7.10">0.7.10</link>. -When <literal>XML_PARSE_DTDVALID</literal> is enabled, -<link url="https://gitlab.gnome.org/GNOME/libxml2">libxml2</link> -parses and executes external entities present inside an XML document. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed the detection of <literal>await</literal> in arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Error()</literal> instance dumping -when “<literal>name</literal>” prop is not primitive. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed array instance with a <literal>getter</literal> property dumping. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>njs_object_property()</literal> with -<literal>NJS_WHITEOUT</literal> properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>func</literal> instance dumping -with “<literal>name</literal>” as getter. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed attaching of a stack to an error object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>String.prototype.replace()</literal> with replacement -containing “<literal>$'</literal>”, “<literal>$`</literal>”. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.10" name="Changes with njs 0.7.10"> - -<para> -Release Date: -07 February 2023 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="request"><literal>Request</literal></link>, -<link doc="reference.xml" id="response"><literal>Response</literal></link>, -and -<link doc="reference.xml" id="headers"><literal>Headers</literal></link> -ctors in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed nginx logger callback for calls in the master process. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added signal support in CLI. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="xml"><literal>xml</literal></link> -module for working with XML documents. -</para> -</listitem> - -<listitem> -<para> -Feature: -extended support for symmetric and asymmetric keys in WebCrypto. -Most notably <literal>JWK</literal> format for -<link doc="reference.xml" id="crypto_subtle_import_key"><literal>importKey()</literal></link> -was added. -</para> -</listitem> - -<listitem> -<para> -Feature: -extended support for symmetric and asymmetric keys in -<link doc="reference.xml" id="builtin_crypto">WebCrypto API</link>. -Most notably <literal>JWK</literal> format for -<link doc="reference.xml" id="crypto_subtle_import_key"><literal>importKey()</literal></link> -was added. -<link doc="reference.xml" id="crypto_subtle_generate_key"><literal>generateKey()</literal></link> -and -<link doc="reference.xml" id="crypto_subtle_export_key"><literal>exportKey()</literal></link> -were also implemented. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>String.prototype.replaceAll()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>for(expr1;</literal> conditional syntax error handling. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -<literal>Object.values()</literal> -and -<literal>Object.entries()</literal> -with external objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>RegExp.prototype[@@replace]()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.9" name="Changes with njs 0.7.9"> - -<para> -Release Date: -17 November 2022 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="ngx_fetch"><literal>Fetch</literal></link> -Response prototype reinitialization. -When at least one <literal>js_import</literal> directive was declared in both -<link doc="../http/ngx_http_js_module.xml" id="js_import">HTTP</link> -and -<link doc="../stream/ngx_stream_js_module.xml" id="js_import">Stream</link>, -<link doc="reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -returned inapproriate response in Stream. -The bug was introduced in <link id="njs0.7.7">0.7.7</link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed <literal>String.prototype.replace(re)</literal> -if <literal>re.exec()</literal> returns non-flat array. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.fill()</literal> -when <literal>start</literal> object changes <literal>this</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed description for -<link doc="reference.xml" id="fs_mkdirsync"><literal>fs.mkdir()</literal></link> -and -<link doc="reference.xml" id="fs_rmdirsync"><literal>fs.rmdir()</literal></link> -methods. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>%TypedArray%.prototype.set(s)</literal> -when <literal>s</literal> element changes <literal>this</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.splice(s,d)</literal> -when <literal>d</literal> resizes <literal>this</literal> during eval. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>for-in</literal> loop with left and right hand side expressions. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.8" name="Changes with njs 0.7.8"> - -<para> -Release Date: -25 October 2022 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="../http/ngx_http_js_module.xml" id="js_preload_object"/> directive. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="ngx_conf_prefix"><literal>ngx.conf_prefix</literal></link><literal></literal> -property. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="s_send_upstream"><literal>s.sendUpstream()</literal></link> -and -<link doc="reference.xml" id="s_send_downstream"><literal>s.sendDownstream()</literal></link> -in -<link doc="../stream/ngx_stream_js_module.xml">stream</link> module. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for <literal>HEAD</literal> method in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -improved <literal>async</literal> callback support for -<link doc="reference.xml" id="s_send"><literal>s.send()</literal></link> -in -<link doc="../stream/ngx_stream_js_module.xml">stream</link> module. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>name</literal> instance property for a function object. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="njs_memory_stats"><literal>njs.memoryStats</literal></link> -object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.trimEnd()</literal> -with unicode string. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Object.freeze()</literal> with fast arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Object.defineProperty()</literal> with fast arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>async</literal> token as a property name of an object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed property set instruction when key modifies base binding. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed complex assignments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of unhandled promise rejection. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed process.env -when duplicate environ variables are present. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed double declaration detection in modules. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed bound function calls according to the spec. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed break label for <literal>if</literal> statement. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed labeled empty statements. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.7" name="Changes with njs 0.7.7"> - -<para> -Release Date: -30 August 2022 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -the number of nginx configuration contexts where -js directives can be specified is extended. - -<list type="bullet"> - -<listitem id="contexts"> -<para> -HTTP: -the <link doc="../http/ngx_http_js_module.xml" id="js_import"/>, -<link doc="../http/ngx_http_js_module.xml" id="js_path"/>, -<link doc="../http/ngx_http_js_module.xml" id="js_set"/>, and -<link doc="../http/ngx_http_js_module.xml" id="js_var"/> directives -are allowed in -<literal>server</literal> and <literal>location</literal> contexts. -The <link doc="../http/ngx_http_js_module.xml" id="js_content"/>, -<link doc="../http/ngx_http_js_module.xml" id="js_body_filter"/> and -<link doc="../http/ngx_http_js_module.xml" id="js_header_filter"/> -are allowed in -<link doc="../http/ngx_http_rewrite_module.xml" id="if"/> context. -</para> -</listitem> - -<listitem> -<para> -Stream: -the <link doc="../http/ngx_http_js_module.xml" id="js_import"/>, -<link doc="../http/ngx_http_js_module.xml" id="js_path"/>, -<link doc="../http/ngx_http_js_module.xml" id="js_set"/>, and -<link doc="../http/ngx_http_js_module.xml" id="js_var"/> -are allowed in -<literal>server</literal> context. -</para> -</listitem> - -</list> - -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="r_internal"><literal>r.internal</literal></link> -property. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed reading response body in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="../stream/ngx_stream_js_module.xml" id="js_fetch_timeout"/> -in <link doc="../stream/ngx_stream_js_module.xml">stream</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed socket leak with <literal>0</literal> fetch timeout. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -extended -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> module. -Added -<link doc="reference.xml" id="fs_opensync"><literal>fs.openSync()</literal></link>, -<link doc="reference.xml" id="fs_promises_open"><literal>fs.promises.open()</literal></link>, -<link doc="reference.xml" id="fs_fstatsync"><literal>fs.fstatSync()</literal></link>, -<link doc="reference.xml" id="fs_readsync"><literal>fs.readSync()</literal></link>, -<link doc="reference.xml" id="fs_writesync_buf"><literal>fs.writeSync()</literal></link>. -</para> - -<para> -The following properties of -<link doc="reference.xml" id="fs_filehandle"><literal>FileHandle</literal></link> -are implemented: -<literal>fd</literal>, -<literal>read()</literal>, -<literal>stat()</literal>, -<literal>write()</literal>, -<literal>close()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>parseInt()</literal>, -<literal>parseFloat()</literal>, -<literal>Symbol.for()</literal> -with no arguments. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.6" name="Changes with njs 0.7.6"> - -<para> -Release Date: -19 July 2022 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -improved -<link doc="reference.xml" id="r_args"><literal>r.args{}</literal></link> object. -Added support for multiple arguments with the same key. -Added case sensitivity for keys. -Keys and values are percent-decoded now. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link> -setter for special headers. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>Symbol.for()</literal> and <literal>Symbol.keyfor()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="atob"><literal>atob()</literal></link> -and -<link doc="reference.xml" id="btoa"><literal>btoa()</literal></link> -from -<link url="https://html.spec.whatwg.org">WHATWG</link> spec. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed large non-decimal literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed Unicode argument trimming in <literal>parseInt()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>break</literal> instruction -in <literal>try-catch</literal> block. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>async</literal> function declaration in CLI. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.5" name="Changes with njs 0.7.5"> - -<para> -Release Date: -21 June 2022 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Change: -adapting to changes in nginx header structures. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link> -special getters when value is absent. -</para> -</listitem> - -<listitem> -<para> -Change: -returning undefined value instead of an empty string for -<literal>Content-Type</literal> when the header is absent. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed catching of the exception thrown from an awaited function. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function value initialization. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed interpreter when await fails. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed typed-array constructor when source array is changed while iterating. -</para> -</listitem> - -<listitem> -<para> -Bugfix:fixed -<literal>String.prototype.replace()</literal> -with byte strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed template literal from producing byte-strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed array iterator with sparse arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed memory free while converting a flat array to a slow array. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -properly handling <literal>NJS_DECLINE</literal> in -<literal>promise</literal> native functions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed working with an array-like object in -<literal>Promise.all()</literal> -and friends. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.4" name="Changes with njs 0.7.4"> - -<para> -Release Date: -24 May 2022 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added extended directives for configuring -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -The following directives were added for -<link doc="../http/ngx_http_js_module.xml">http</link> and -<link doc="../stream/ngx_stream_js_module.xml">stream</link>: -<list type="bullet"> - -<listitem> -<para> -<link doc="../http/ngx_http_js_module.xml" id="js_fetch_timeout"/>, -</para> -</listitem> - -<listitem> -<para> -<link doc="../http/ngx_http_js_module.xml" id="js_fetch_verify"/>, -</para> -</listitem> - -<listitem> -<para> -<link doc="../http/ngx_http_js_module.xml" id="js_fetch_buffer_size"/>, -</para> -</listitem> - -<listitem> -<para> -<link doc="../http/ngx_http_js_module.xml" id="js_fetch_max_response_buffer_size"/>. -</para> -</listitem> - -</list> - -</para> -</listitem> - -<listitem> -<para> -Change: -<link doc="reference.xml" id="r_internal_redirect"><literal>r.internalRedirect()</literal></link> now accepts escaped URIs. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="response">Response</link> parsing -with more than 8 headers in -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="njs_version_number"><literal>njs.version_number</literal></link> property. -</para> -</listitem> - -<listitem> -<para> -Feature: -added compatibility with BoringSSL for -<link doc="reference.xml" id="builtin_crypto">WebCrypto API</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.sort()</literal> -when arr size is changed in a comparator. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.slice()</literal> -with slow <literal>this</literal> argument. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed aggregation methods of <literal>Promise</literal> ctor -with array-like object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>String.prototype.lastIndexOf()</literal> -with Unicode string as <literal>this</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>JSON.parse()</literal> -when <literal>reviver</literal> function is provided. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.defineProperty()</literal> -when a recursive descriptor is provided. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.fill()</literal> for typed-arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -making function expression binding immutable according to the specs. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed redefinition of special props in -<literal>Object.defineProperty()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - - -<section id="njs0.7.3" name="Changes with njs 0.7.3"> - -<para> -Release Date: -12 April 2022 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added support of module resolution callback. -This feature allows the host environment to control -how imported modules are loaded. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed backtraces while traversing imported user modules. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.concat()</literal> -when <literal>this</literal> is a slow array. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed frame allocation from an awaited frame. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed allocation of large array literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed interpreter when <literal>toString</literal> conversion fails. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.2" name="Changes with njs 0.7.2"> - -<para> -Release Date: -25 January 2022 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.join()</literal> -when array is changed while iterating. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.slice()</literal> -when array is changed while iterating. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.concat()</literal> -when array is changed while iterating. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.reverse()</literal> -when array is changed while iterating. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Buffer.concat()</literal> -with subarrays. -Thanks to Sylvain Etienne. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -type confusion bug while resolving promises. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Function.prototype.apply()</literal> -with large array arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed recursive <literal>async</literal> function calls. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function redeclaration. -The bug was introduced in -<link id="njs0.7.0">0.7.0</link>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.7.1" name="Changes with njs 0.7.1"> - -<para> -Release Date: -28 December 2021 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Change: -the <link doc="../http/ngx_http_js_module.xml" id="js_include"/> directive -deprecated since <link id="njs0.4.0">0.4.0</link> was removed. -</para> -</listitem> - -<listitem> -<para> -Change: -PCRE/PCRE2-specific code was moved to the modules. -This ensures that njs uses the same RegExp library as nginx. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed -<literal>decodeURI()</literal> and -<literal>decodeURIComponent()</literal> -with invalid byte strings. -The bug was introduced in -<link id="njs0.4.3">0.4.3</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-use-after-free in <literal>await</literal> frame. -The bug was introduced in -<link id="njs0.7.0">0.7.0</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed WebCrypto <literal>sign()</literal> and -<literal>verify()</literal> methods with OpenSSL 3.0. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed exception throwing when RegExp match fails. -The bug was introduced in -<link id="njs0.1.15">0.1.15</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed catching of exception thrown in <literal>try</literal> block -of <literal>async</literal> function. -The bug was introduced in -<link id="njs0.7.0">0.7.0</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed execution of <literal>async</literal> function in synchronous context. -The bug was introduced in -<link id="njs0.7.0">0.7.0</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function redeclaration in CLI when interactive mode is on. -The bug was introduced in -<link id="njs0.6.2">0.6.2</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>typeof</literal> operator with -<literal>DataView</literal> object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: eliminated information leak in <literal>Buffer.from()</literal>. -</para> -</listitem> - -</list> - -</para> - -</section> - - -<section id="njs0.7.0" name="Changes with njs 0.7.0"> - -<para> -Release Date: -19 October 2021 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -Added -<link doc="../http/ngx_http_js_module.xml" id="js_fetch_protocols">HTTPS</link> -support for -<link doc="reference.xml" id="ngx_fetch">Fetch API</link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -Added -<literal>setReturnValue()</literal> method for -<link doc="reference.xml" id="r_set_return_value">http</link> and -<link doc="reference.xml" id="s_set_return_value">stream</link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -introduced <literal>Async/Await</literal> implementation. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="builtin_crypto">WebCrypto API</link> -implementation. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed copying of closures for declared functions. -The bug was introduced in -<link id="njs0.6.0">0.6.0</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed unhandled <literal>promise</literal> rejection in handle events. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed Response.headers getter in Fetch API. -</para> -</listitem> - -</list> - -</para> - -</section> - - -<section id="njs0.6.2" name="Changes with njs 0.6.2"> - -<para> -Release Date: -31 August 2021 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed CPU hog when -<literal>js_filter</literal> is registered in both directions. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -introduced <literal>AggregateError</literal> implementation. -</para> -</listitem> - -<listitem> -<para> -Feature: -added remaining <literal>Promise</literal> constructor methods. -The following methods were added: -<literal>Promise.all()</literal>, -<literal>Promise.allSettled()</literal>, -<literal>Promise.any()</literal>, -<literal>Promise.race()</literal>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -removed recursion from code generator. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed rest parameter parsing without binding identifier. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed resolve/reject callback for -<literal>Promise.prototype.finally()</literal> . -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>%TypedArray%.prototype.join()</literal> -with detached buffer. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed memory leak in interactive shell. -</para> -</listitem> -</list> - -</para> - -</section> - - -<section id="njs0.6.1" name="Changes with njs 0.6.1"> - -<para> -Release Date: -29 June 2021 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed <literal>RegExpBuiltinExec()</literal> with UTF-8 only regexps. -The bug was introduced in <link id="njs0.4.2">0.4.2</link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of export default declaration with non-assignment expressions. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.6.0" name="Changes with njs 0.6.0"> - -<para> -Release Date: -15 June 2021 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<literal>let</literal> and -<literal>const</literal> declaration support. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>RegExp.prototype[Symbol.split]</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added sticky flag support for RegExp. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>String.prototype.lastIndexOf()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>RegExp.prototype.test()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.split()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed use-of-uninitialized-value while tracking rejected promises. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>njs.dump()</literal> for objects with circular references. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.5.3" name="Changes with njs 0.5.3"> - -<para> -Release Date: -30 March 2021 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added the <literal>js_var</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_var">http</link> and -<link doc="../stream/ngx_stream_js_module.xml" id="js_var">stream</link>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.5.2" name="Changes with njs 0.5.2"> - -<para> -Release Date: -09 March 2021 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added the -<link doc="../http/ngx_http_js_module.xml" id="js_body_filter"><literal>js_body_filter</literal></link> -directive. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced the -<link doc="reference.xml" id="s_status"><literal>s.status</literal></link> -property for -<link doc="reference.xml" id="stream">Stream Session</link> -object. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="njs_on"><literal>njs.on</literal></link> -(<literal>exit</literal>) callback support. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed property descriptor reuse for not extensible objects. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Object.freeze()</literal> and friends -according to the specification. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Function()</literal> in CLI mode. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>for-in</literal> iteration of typed array values. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.5.1" name="Changes with njs 0.5.1"> - -<para> -Release Date: -16 February 2021 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -introduced -<link doc="reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -method implementing Fetch API. -</para> - -<para> -The following properties and methods of -<link doc="reference.xml" id="response"><literal>Response</literal></link> -object are implemented: -<link doc="reference.xml" id="response_arraybuffer"><literal>arrayBuffer()</literal></link>, -<link doc="reference.xml" id="response_bodyused"><literal>bodyUsed</literal></link>, -<link doc="reference.xml" id="response_json"><literal>json()</literal></link>, -<link doc="reference.xml" id="response_headers"><literal>headers</literal></link>, -<link doc="reference.xml" id="response_ok"><literal>ok</literal></link>, -<link doc="reference.xml" id="response_redirect"><literal>redirect</literal></link>, -<link doc="reference.xml" id="response_status"><literal>status</literal></link>, -<link doc="reference.xml" id="response_statustext"><literal>statusText</literal></link>, -<link doc="reference.xml" id="response_text"><literal>text()</literal></link>, -<link doc="reference.xml" id="response_type"><literal>type</literal></link>, -<link doc="reference.xml" id="response_url"><literal>url</literal></link>. -</para> - -<para> -Notable limitations: -only the <literal>http://</literal> scheme is supported, -redirects are not handled. -</para> - -<para> -In collaboration with 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Feature: -added the -<link doc="../http/ngx_http_js_module.xml" id="js_header_filter"><literal>js_header_filter</literal></link> -directive. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing buffered data in body filter in -<link doc="../stream/ngx_stream_js_module.xml">stream</link> module. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed safe mode bypass in <literal>Function</literal> constructor. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Date.prototype.toISOString()</literal> with invalid date values. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.5.0" name="Changes with njs 0.5.0"> - -<para> -Release Date: -01 December 2020 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -introduced global -<link doc="reference.xml" id="ngx"><literal>ngx</literal></link> object. -</para> - -<para> -The following methods were added: -<list type="bullet"> - -<listitem> -<para> -<link doc="reference.xml" id="ngx_log"><literal>ngx.log(level, -message)</literal></link> -</para> -</listitem> - -</list> -</para> - -<para> -The following properties were added: -<list type="bullet"> - -<listitem> -<para> -<literal>ngx.INFO</literal>, -<literal>ngx.WARN</literal>, -<literal>ngx.ERR</literal>. -</para> -</listitem> - -</list> -</para> - -</listitem> - -<listitem> -<para> -Feature: -added support for -<literal>Buffer</literal> object where string is expected. -</para> -</listitem> - -<listitem> -<para> -Feature: -added Buffer version of existing properties. -</para> - -<para> -The following properties were added: -<list type="bullet"> - -<listitem> -<para> -<link doc="reference.xml" id="r_request_buffer"><literal>r.requestBuffer</literal></link> -(<link doc="reference.xml" id="r_request_body"><literal>r.requestBody</literal></link>), -<link doc="reference.xml" id="r_response_buffer"><literal>r.responseBuffer</literal></link> -(<link doc="reference.xml" id="r_response_body"><literal>r.responseBody</literal></link>), -<link doc="reference.xml" id="r_raw_variables"><literal>r.rawVariables</literal></link> -(<link doc="reference.xml" id="r_variables"><literal>r.variables</literal></link>), -<link doc="reference.xml" id="s_raw_variables"><literal>s.rawVariables</literal></link> -(<link doc="reference.xml" id="s_variables"><literal>s.variables</literal></link>). -</para> -</listitem> - -</list> -</para> - -<para> -The following events were added in the stream module: -<list type="bullet"> - -<listitem> -<para> -<link doc="reference.xml" id="s_on"><literal>upstream</literal></link> -(upload), -<link doc="reference.xml" id="s_on"><literal>downstream</literal></link> -(download). -</para> -</listitem> - -</list> -</para> - -</listitem> - -<listitem> -<para> -Improvement: -added aliases to existing properties. -</para> - -<para> -The following properties were added: -<list type="bullet"> - -<listitem> -<para> -<link doc="reference.xml" id="r_request_text"><literal>r.requestText</literal></link> -(<link doc="reference.xml" id="r_request_body"><literal>r.requestBody</literal></link>), -<link doc="reference.xml" id="r_response_text"><literal>r.responseText</literal></link> -(<link doc="reference.xml" id="r_response_body"><literal>r.responseBody</literal></link>). -</para> -</listitem> - -</list> -</para> - -</listitem> - -<listitem> -<para> -Improvement: -throwing an exception in -<link doc="reference.xml" id="r_internal_redirect"><literal>r.internalRedirect()</literal></link> -for a subrequest. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed promise -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link> -with -<link doc="../http/ngx_http_core_module.xml" id="error_page"><literal>error_page</literal></link> -redirect. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>promise</literal> events handling. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<literal>TypeScript</literal> definitions for built-in modules. -Thanks to Jakub Jirutka. -</para> -</listitem> - -<listitem> -<para> -Feature: -tracking unhandled <literal>promise</literal> rejection. -</para> -</listitem> - -<listitem> -<para> -Feature: -added initial iterator support. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Improvement: -<literal>TypeScript</literal> definitions are refactored. -Thanks to Jakub Jirutka. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added forgotten support for -<literal>Object.prototype.valueOf()</literal> -in -<literal>Buffer.from()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-use-after-free in -<literal>JSON.parse()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-use-after-free in -<literal>JSON.stringify()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>JSON.stringify()</literal> for arrays resizable via getters. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow for -<literal>RegExp.prototype[Symbol.replace]</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed returned value for -<literal>Buffer.prototype.write*</literal> -functions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="querystring_stringify"><literal>querystring.stringify()</literal></link>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed the catch handler for -<literal>Promise.prototype.finally()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="querystring_parse"><literal>querystring.parse()</literal></link>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.4.4" name="Changes with njs 0.4.4"> - -<para> -Release Date: -29 September 2020 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed location merge. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="r_http_version"><literal>r.httpVersion</literal></link> -for HTTP/2. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added support for numeric separators (ES12). -</para> -</listitem> - -<listitem> -<para> -Feature: -added remaining methods for -<literal>%TypedArray%.prototype</literal>. -The following methods were added: -<literal>every()</literal>, -<literal>filter()</literal>, -<literal>find()</literal>, -<literal>findIndex()</literal>, -<literal>forEach()</literal>, -<literal>includes()</literal>, -<literal>indexOf()</literal>, -<literal>lastIndexOf()</literal>, -<literal>map()</literal>, -<literal>reduce()</literal>, -<literal>reduceRight()</literal>, -<literal>reverse()</literal>, -<literal>some()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>%TypedArray%</literal> remaining methods. -The following methods were added: -<literal>from()</literal>, -<literal>of()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>DataView</literal> object. -</para> -</listitem> -<listitem> -<para> -Feature: -added <literal>Buffer</literal> object implementation. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for <literal>ArrayBuffer</literal> in -<link doc="reference.xml" id="textdecoder_decode"><literal>TextDecoder.prototype.decode()</literal></link> -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for <literal>Buffer</literal> object in -<link doc="reference.xml" id="crypto"><literal>crypto</literal></link> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for <literal>Buffer</literal> object in -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> -methods. -</para> -</listitem> - -<listitem> -<para> -Change: -<link doc="reference.xml" id="crypto_hash_digest"><literal>Hash.prototype.digest()</literal></link> -and -<link doc="reference.xml" id="crypto_hmac_digest"><literal>Hmac.prototype.digest()</literal></link> -now return a <literal>Buffer</literal> instance instead of a byte string when -encoding is not provided. -</para> -</listitem> - -<listitem> -<para> -Change: -<link doc="reference.xml" id="readfilesync"><literal>fs.readFile()</literal></link> -and friends now return a <literal>Buffer</literal> instance -instead of a byte string when encoding is not provided. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function <literal>prototype</literal> property handler while setting. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function <literal>constructor</literal> property handler while setting. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>String.prototype.indexOf()</literal> -for byte strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>RegExpBuiltinExec()</literal> -with a global flag and byte strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>RegExp.prototype[Symbol.replace]</literal> -the when replacement value is a function. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="textdecoder_decode"><literal>TextDecoder.prototype.decode()</literal></link> -with non-zero <literal>TypedArray</literal> offset. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.4.3" name="Changes with njs 0.4.3"> - -<para> -Release Date: -11 August 2020 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="querystring"><literal>Query String</literal></link> -module. -</para> -</listitem> - -<listitem> -<para> -Feature: -improved -<link doc="reference.xml" id="fs_mkdirsync"><literal>fs.mkdir()</literal></link> -to support recursive directory creation. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -improved -<link doc="reference.xml" id="fs_rmdirsync"><literal>fs.rmdir()</literal></link> -to support recursive directory removal. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced UTF-8 decoder according to -<link url="https://encoding.spec.whatwg.org/">WHATWG</link> encoding spec. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="textdecoder"><literal>TextDecoder()</literal></link> -and -<link doc="reference.xml" id="textencoder"><literal>TextEncoder()</literal></link> -implementation. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing return statement without semicolon. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>njs_number_to_int32()</literal> for big-endian platforms. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed unit test on big-endian platforms. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed regexp-literals parsing with “<literal>=</literal>” characters. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed pre/post increment/decrement in assignment operations. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.4.2" name="Changes with njs 0.4.2"> - -<para> -Release Date: -07 July 2020 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>RegExp.prototype[Symbol.replace]</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced line level backtrace. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>%TypedArray%.prototype.sort()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -extended -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> module. -Added -<link doc="reference.xml" id="fs_mkdirsync"><literal>mkdir()</literal></link>, -<link doc="reference.xml" id="fs_readdirsync"><literal>readdir()</literal></link>, -<link doc="reference.xml" id="fs_rmdirsync"><literal>rmdir()</literal></link>, -and friends. -</para> -</listitem> - -<listitem> -<para> -Improvement: -parser refactoring. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed TypedScript API description for HTTP headers. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed TypedScript API description for <literal>NjsByteString</literal> type. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.repeat()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.replace()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of flags for regexp literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed index generation for global objects in generator. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>%TypedArray%.prototype.copyWithin()</literal> -with nonzero byte offset. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.splice()</literal> -for sparse arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.reverse()</literal> -for sparse arrays. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.sort()</literal> -for sparse arrays. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.4.1" name="Changes with njs 0.4.1"> - -<para> -Release Date: -19 May 2020 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added support for multi-value headers in -<link doc="reference.xml" id="r_headers_in"><literal>r.headersIn{}</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced <literal>raw headers</literal> API: -<link doc="reference.xml" id="r_raw_headers_in"><literal>r.rawHeadersIn[]</literal></link> -and -<link doc="reference.xml" id="r_raw_headers_out"><literal>r.rawHeadersOut[]</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <link doc="typescript.xml">TypeScript</link> API description. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype.slice()</literal> for sparse arrays. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.4.0" name="Changes with njs 0.4.0"> - -<para> -Release Date: -23 April 2020 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added support for multi-value headers in -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>js_import</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_import">http</link> and -<link doc="../stream/ngx_stream_js_module.xml" id="js_import">stream</link>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -improved iteration over -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link> -with special headers. -</para> -</listitem> - -<listitem> -<para> -Improvement: -improved iteration over -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link> -with duplicates. -</para> -</listitem> - -<listitem> -<para> -Change: -<link doc="reference.xml" id="r_response_body"><literal>r.responseBody</literal></link> -property handler now returns -<literal>undefined</literal> -instead of throwing an exception if the response body is not available. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added script arguments support in CLI. -</para> -</listitem> - -<listitem> -<para> -Feature: -converting externals values to native js objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed NULL-pointer dereference -in <literal>__proto__</literal> property handler. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of no-newline at the end of the script. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>RegExp()</literal> constructor -with empty pattern and non-empty flags. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.replace()</literal> -when function returns non-string. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed reading of pseudofiles in -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.9" name="Changes with njs 0.3.9"> - -<para> -Release Date: -03 March 2020 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added detached mode for -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link>. -Responses to detached subrequests are ignored. -Unlike ordinary subrequests, -a detached subrequest can be created inside a variable handler. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>promises</literal> API for -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> module. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -extended <link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> -module. -Added -<link doc="reference.xml" id="fs_accesssync"><literal>access()</literal></link>, -<link doc="reference.xml" id="fs_symlinksync"><literal>symlink()</literal></link>, -<link doc="reference.xml" id="fs_unlinksync"><literal>unlink()</literal></link>, -<link doc="reference.xml" id="fs_realpathsync"><literal>realpath()</literal></link>, -and friends. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Improvement: -introduced memory-efficient ordinary arrays. -</para> -</listitem> - -<listitem> -<para> -Improvement: -lexer refactoring. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed matching of native functions in backtraces. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed callback invocations in -<link doc="reference.xml" id="njs_api_fs"><literal>fs</literal></link> module. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Object.getOwnPropertySymbols()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>njs_json_append_string()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>encodeURI()</literal> -and -<literal>decodeURI()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Number.prototype.toPrecision()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of space argument in -<literal>JSON.stringify()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>JSON.stringify()</literal> -with -<literal>Number()</literal> and -<literal>String()</literal> -objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed Unicode Escaping in -<literal>JSON.stringify()</literal> -according to specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed non-native module importing. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>njs.dump()</literal> with the -<literal>Date()</literal> -instance in a container. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.8" name="Changes with njs 0.3.8"> - -<para> -Release Date: -21 January 2020 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>Promise</literal> support for -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link>. -If a callback is not provided, -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link> -returns an ordinary -<literal>Promise</literal> object -that resolves to a subrequest response object. -</para> -</listitem> - -<listitem> -<para> -Change: -<link doc="reference.xml" id="r_parent"><literal>r.parent</literal></link> -property handler now returns -<literal>undefined</literal> -instead of throwing an exception if a parent object is not available. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>Promise</literal> support. -Implemented according to the specification without: -<literal>Promise.all()</literal>, -<literal>Promise.allSettled()</literal>, -<literal>Promise.race()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added initial Typed-arrays support. -Thanks to Tiago Natel de Moura. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>ArrayBuffer</literal> support. -Thanks to Tiago Natel de Moura. -</para> -</listitem> - -<listitem> -<para> -Feature: -added initial <literal>Symbol</literal> support. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added externals support for -<literal>JSON.stringify()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>Object.is()</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>Object.setPrototypeOf()</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced nullish coalescing operator. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.getPrototypeOf()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.prototype.valueOf()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>JSON.stringify()</literal> -with unprintable values and replacer function. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed operator <literal>in</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.defineProperties()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.create()</literal> -according to the specification. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Number.prototype.toString(radix)</literal> -when fast-math is enabled. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>RegExp()</literal> instance properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed import segfault. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.7" name="Changes with njs 0.3.7"> - -<para> -Release Date: -19 November 2019 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Improvement: -refactored iteration over external objects. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added <literal>Object.assign()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>Array.prototype.copyWithin()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for labels in <literal>console.time()</literal>. -</para> -</listitem> - -<listitem> -<para> -Change: -removed <literal>console.help()</literal> from CLI. -</para> -</listitem> - -<listitem> -<para> -Improvement: -moved constructors and top-level objects to global object. -</para> -</listitem> - -<listitem> -<para> -Improvement: -arguments validation for configure script. -</para> -</listitem> - -<listitem> -<para> -Improvement: -refactored JSON methods. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>njs_array_reverse_iterator()</literal> function. -The following functions were affected: -<literal>Array.prototype.lastIndexOf()</literal>, -<literal>Array.prototype.reduceRight()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>[[Prototype]]</literal> slot of <literal>NativeErrors</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>NativeError.prototype.message</literal> properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -added conversion of -<literal>this</literal> value to object in -<literal>Array.prototype functions</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed iterator for -<literal>Array.prototype.find()</literal> and -<literal>Array.prototype.findIndex()</literal> -functions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.includes()</literal> and -<literal>Array.prototype.join()</literal> with -<literal>undefined</literal> argument. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>constructor</literal> property of -<literal>Hash</literal> and -<literal>Hmac</literal> -objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>__proto__</literal> property of getters and setters. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Date</literal> object string formatting. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of -<literal>NaN</literal> and <literal>-0</literal> arguments in -<literal>Math.min()</literal> and -<literal>Math.max()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Math.round()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -reimplemented <literal>bound</literal> functions -according to the specification. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.6" name="Changes with njs 0.3.6"> - -<para> -Release Date: -22 October 2019 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Improvement: -getting special headers from -<link doc="reference.xml" id="r_headers_in"><literal>r.headersIn{}</literal></link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added new <literal>Function()</literal> support. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>Number.prototype.toFixed()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>Number.prototype.toPrecision()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added <literal>Number.prototype.toExponential()</literal>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -making <literal>prototype</literal> property of function instances writable. -</para> -</listitem> - -<listitem> -<para> -Improvement: -limiting recursion depth while compiling. -</para> -</listitem> - -<listitem> -<para> -Improvement: -moving global functions to the global object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed prototype mutation for object literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow while parsing regexp literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed integer-overflow while parsing exponent of number literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>parseFloat()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>Array.prototype</literal> functions -according to the specification. -The following functions were fixed: -<literal>every</literal>, -<literal>includes</literal>, -<literal>indexOf</literal>, -<literal>filter</literal>, -<literal>find</literal>, -<literal>findIndex</literal>, -<literal>forEach</literal>, -<literal>lastIndexOf</literal>, -<literal>map</literal>, -<literal>pop</literal>, -<literal>push</literal>, -<literal>reduce</literal>, -<literal>reduceRight</literal>, -<literal>shift</literal>, -<literal>some</literal>, -<literal>unshift</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handing of accessor descriptors in <literal>Object.freeze()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.replace()</literal> -when first argument is not a string. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed stack-use-after-scope in <literal>Array.prototype.map()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -<literal>Date.prototype.toUTCString()</literal> -format was aligned to ES9. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed buffer overflow in -<literal>Number.prototype.toString(radix)</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Regexp.prototype.test()</literal> -for regexps with backreferences. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.map()</literal> -for objects with nonexistent values. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.pop()</literal> and -<literal>shift()</literal> for sparse objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Date.UTC()</literal> -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Date()</literal> constructor -according to the specification. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed type of -<literal>Date.prototype</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Date.prototype.setTime()</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed default number of arguments expected by built-in functions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>caller</literal> and -<literal>arguments</literal> -properties of a function instance. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.5" name="Changes with njs 0.3.5"> - -<para> -Release Date: -15 August 2019 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed module importing using <literal>require()</literal>. -The bug was introduced in <link id="0.3.4"/>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>[[SetPrototypeOf]]</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.4" name="Changes with njs 0.3.4"> - -<para> -Release Date: -13 August 2019 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<literal>Object</literal> -shorthand methods and computed property names. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added getter/setter literal support. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="fs_renamesync"><literal>fs.renameSync()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>String.prototype.trimEnd()</literal> -and -<literal>String.prototype.trimStart()</literal>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added memory-sanitizer support. -</para> -</listitem> - -<listitem> -<para> -Improvement: -Unicode case tables updated to version 12.1. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added UTF8 validation for string literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed reading files with zero size in -<link doc="reference.xml" id="readfilesync"><literal>fs.readFileSync()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -extended the list of space separators in -<literal>String.prototype.trim()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed using of uninitialized value in -<literal>String.prototype.padStart()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.replace()</literal> -for <literal>$0</literal> and <literal>$&</literal> replacement string. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.replace()</literal> -for byte strings with regex argument. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed global match in -<literal>String.prototype.replace()</literal> -with regexp argument. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.slice()</literal> -for primitive types. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow while importing module. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed UTF-8 character escaping. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.values()</literal> -and -<literal>Object.entries()</literal> -for shared objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed uninitialized memory access in -<literal>String.prototype.match()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.match()</literal> -for byte strings with regex argument. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.lastIndexOf()</literal> -with undefined arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.substring()</literal> -with empty substring. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed invalid memory access in -<literal>String.prototype.substring()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.fromCharCode()</literal> -for code points more than <literal>65535</literal> and <literal>NaN</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.toLowerCase()</literal> -and -<literal>String.prototype.toUpperCase()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Error()</literal> -constructor with no arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>in</literal> -operator for values with accessor descriptors. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.defineProperty()</literal> -for non-boolean descriptor props. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Error.prototype.toString()</literal> -with UTF8 string properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Error.prototype.toString()</literal> -with non-string values for <literal>name</literal> and <literal>message</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.3" name="Changes with njs 0.3.3"> - -<para> -Release Date: -25 June 2019 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Improvement: -getting of special response headers in -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -working with unknown methods in -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added support for null as a second argument of -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing empty output chain in stream body filter. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added runtime support for property getter/setter. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<link doc="reference.xml" id="process"><literal>process</literal></link> -global object. -</para> -</listitem> - -<listitem> -<para> -Feature: -writable most of built-in properties and methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -added generic implementation of -<literal>Array.prototype.fill()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed integer-overflow in -<literal>String.prototype.concat()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed setting of object properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.toString()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Date.prototype.toJSON()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed overwriting “constructor” property of built-in prototypes. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing of invalid surrogate pairs in strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing of invalid surrogate pairs in JSON strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>toUpperCase()</literal> -and -<literal>toLowerCase()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed escaping lone closing square brackets in -<literal>RegExp()</literal> constructor. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling zero byte characters inside RegExp pattern strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.toBytes()</literal> -for ASCII strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed truth value of JSON numbers in -<literal>JSON.parse()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed use-of-uninitialized-value in -<literal>njs_string_replace_join()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>parseInt('-0')</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.2" name="Changes with njs 0.3.2"> - -<para> -Release Date: -21 May 2019 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added support for template literals. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -executing command from command line arguments. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for RegExp <literal>groups</literal> object (ES9). -</para> -</listitem> - -<listitem> -<para> -Feature: -added block scoped function definitions support. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for building with GNU Readline library. -</para> -</listitem> - -<listitem> -<para> -Feature: -made configurable -<literal>length</literal>, -<literal>name</literal>, -and most of built-in methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -made all constructor properties configurable. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Regexp.prototype.exec()</literal> -for Unicode-only regexps. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>njs_vm_value_dump()</literal> -for empty string values. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed RegExp constructor for regexp value arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed walking over prototypes chain during iteration over an object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed overflow in -<literal>Array.prototype.concat()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed length calculation for UTF-8 string with escape characters. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing surrogate pair presents as UTF-16 escape sequences. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing the “*” quantifier for -<literal>String.prototype.match()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Date()</literal> -constructor with one argument. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed arrays expansion. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>String.prototype.replace()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>String.prototype.lastIndexOf()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed regexp literals parsing with escaped backslash -and backslash in square brackets. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed regexp literals with lone closing brackets. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed uninitialized-memory-access in -<literal>Object.defineProperties()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing the “*” quantifier for -<literal>String.prototype.replace()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.slice()</literal> -for UTF8-invalid byte strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.prototype.split()</literal> -for UTF8-invalid byte strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of empty block statements. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.1" name="Changes with njs 0.3.1"> - -<para> -Release Date: -16 April 2019 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added arrow functions support. -Thanks to 洪志道 (Hong Zhi Dao) and Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>Object.getOwnPropertyNames()</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>Object.getOwnPropertyDescriptors()</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Feature: -making <literal>__proto__</literal> accessor descriptor -of <literal>Object</literal> instances mutable. -</para> -</listitem> - -<listitem> -<para> -Feature: -added shebang support in CLI. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for module mode execution in CLI. -In module mode global, this is unavailable. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed editline detection. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Function.prototype.bind()</literal>. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed checking of duplication of parameters for functions. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function declaration with the same name as a variable. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Improvement: -code related to parsing of objects, variables and -functions is refactored. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Improvement: -large-value output improved in <literal>console.log()</literal>. -</para> -</listitem> - -<listitem> -<para> -Improvement: -string output improved in <literal>console.log()</literal> -in a compliant way (without escaping and quotes). -</para> -</listitem> - -<listitem> -<para> -Improvement: -using ES6 version of -<literal>ToInt32()</literal>, -<literal>ToUint32()</literal>, -<literal>ToLength()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.3.0" name="Changes with njs 0.3.0"> - -<para> -Release Date: -26 March 2019 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -added the <literal>js_path</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_path">http</link> and -<link doc="../stream/ngx_stream_js_module.xml" id="js_path">stream</link>. -</para> -</listitem> - -<listitem> -<para> -Change: -returning undefined value instead of empty strings -for absent properties in the following objects: -<link doc="reference.xml" id="r_args"><literal>r.args{}</literal></link>, -<link doc="reference.xml" id="r_headers_in"><literal>r.headersIn{}</literal></link>, -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link>, -<link doc="reference.xml" id="r_variables"><literal>r.variables{}</literal></link>, -<link doc="reference.xml" id="s_variables"><literal>s.variables{}</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Change: -returning undefined value instead of throwing an exception for -<link doc="reference.xml" id="r_request_body"><literal>r.requestBody</literal></link> -when request body is unavailable. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed crash while iterating over -<link doc="reference.xml" id="r_args"><literal>r.args{}</literal></link> -when a value is absent in a key-value pair. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added initial ES6 modules support. -Default import and default export statements are supported. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>Object.prototype.propertyIsEnumerable()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -reporting file name and function name in disassembler output. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed function redeclarations in interactive shell. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed RegExp literals parsing. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed setting length of UTF8 string in -<link doc="reference.xml" id="readfilesync"><literal>fs.readFileSync()</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>nxt_file_dirname()</literal> for paths with no dir component. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.8" name="Changes with njs 0.2.8"> - -<para> -Release Date: -26 February 2019 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Change: -properties of HTTP request deprecated in <link id="njs0.2.2">0.2.2</link> -are removed. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for delete operation in -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link>. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for setting nginx variables. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest()</literal></link> -for empty body value. -</para> -</listitem> - -<listitem> -<para> -Improvement: -setting special response headers in -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut{}</literal></link>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added labels support. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>setImmediate()</literal> method. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support for shorthand property names for Object literals. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Function.prototype.bind()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of string literals containing newline characters. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed line number in reporting variable reference errors. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed creation of long UTF8 strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -setting special response headers in -<literal>String.prototype.split()</literal> -for Unicode strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>String.prototype.split()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.fill()</literal>. -Thanks to Artem S. Povalyukhin. -</para> -</listitem> - -<listitem> -<para> -Improvement: -code related to function invocation is refactored. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Improvement: -code related to variables is refactored. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Improvement: parser is refactored. -Thanks to 洪志道 (Hong Zhi Dao). -</para> -</listitem> - -<listitem> -<para> -Improvement: -reporting filenames in exceptions. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.7" name="Changes with njs 0.2.7"> - -<para> -Release Date: -25 December 2018 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -rest parameters syntax (destructuring is not supported). -Thanks to Alexander Pyshchev. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>Object.entries()</literal> -method. -</para> -</listitem> - -<listitem> -<para> -Feature: -added -<literal>Object.values()</literal> -method. -</para> -</listitem> - -<listitem> -<para> -Improvement: -code generator refactored and simplified. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed automatic semicolon insertion. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed assignment expression from compound assignment. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed comparison of Byte and UTF8 strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed type of iteration variable in <literal>for-in</literal> with array values. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed building on platforms without librt. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.6" name="Changes with njs 0.2.6"> - -<para> -Release Date: -27 November 2018 -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -making built-in prototypes mutable. -</para> -</listitem> - -<listitem> -<para> -Feature: -making global object mutable. -</para> -</listitem> - -<listitem> -<para> -Feature: -<link doc="reference.xml" id="console_time"><literal>console.time()</literal></link> -and -<link doc="reference.xml" id="console_time_end"><literal>console.timeEnd()</literal></link> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -allowing variables and functions to be redeclared. -</para> -</listitem> - -<listitem> -<para> -Feature: -extending <literal>Object.defineProperty()</literal> spec conformance. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced quiet mode for CLI to handle simple expressions from stdin. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced compact form of backtraces to handle stack overflows. -</para> -</listitem> - -<listitem> -<para> -Improvement: -improved wording for various exceptions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed closure values handling. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed equality operator for various value types. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of <literal>this</literal> keyword in various scopes. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling non-object values in -<literal>Object.keys()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of throw statement inside -<literal>if</literal> statement. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of newline after throw statement. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed parsing of statements in if statement without newline. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed size <literal>uint32_t</literal> overflow -in <literal>njs_array_expand()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>typeof</literal> operator -for <literal>object_value</literal> type. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.5" name="Changes with njs 0.2.5"> - -<para> -Release Date: -30 October 2018 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed counting pending events in stream module. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>s.off()</literal> in stream module. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed processing of data chunks in -<literal>js_filter</literal> in stream module. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed http -<literal>status</literal> and -<literal>contentType</literal> -getter in http module. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed http response and parent getters in http module. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -arguments object support. -</para> -</listitem> - -<listitem> -<para> -Feature: -non-integer fractions support. -</para> -</listitem> - -<listitem> -<para> -Improvement: -handling non-array values in -<literal>Array.prototype.slice()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Array.prototype.length</literal> setter -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>njs_array_alloc()</literal> for length > 2**31. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -handling int overflow in -<literal>njs_array_alloc()</literal> on 32bit archs. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed code size mismatch error message. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed delete operator in a loop. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.getOwnPropertyDescriptor()</literal> -for complex object (inherited from -<literal>Array</literal> and -<literal>string</literal> values). -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.prototype.hasOwnProperty()</literal> -for non-object properties -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.4" name="Changes with njs 0.2.4"> - -<para> -Release Date: -18 September 2018 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Change: -stream module handlers refactored. -</para> - -<para> -New methods and properties: -<link doc="reference.xml" id="s_on"><literal>s.on()</literal></link>, -<link doc="reference.xml" id="s_off"><literal>s.off()</literal></link>, -<link doc="reference.xml" id="s_allow"><literal>s.allow()</literal></link>, -<link doc="reference.xml" id="s_done"><literal>s.done()</literal></link>, -<link doc="reference.xml" id="s_decline"><literal>s.decline()</literal></link>, -<link doc="reference.xml" id="s_deny"><literal>s.deny()</literal></link>. -</para> - -<para> -Removed properties of the -<link doc="reference.xml" id="stream">Stream</link> object: -<literal>s.OK</literal>, -<literal>s.ABORT</literal>, -<literal>s.AGAIN</literal>, -<literal>s.DECLINED</literal>, -<literal>s.ERROR</literal> -(replaced with -<link doc="reference.xml" id="s_allow"><literal>s.allow()</literal></link>, -<link doc="reference.xml" id="s_done"><literal>s.done()</literal></link>, -<link doc="reference.xml" id="s_deny"><literal>s.deny()</literal></link>). -</para> - -<para> -<literal>s.buffer</literal> -(for reading replaced with data argument of -the corresponding callback, for writing use -<link doc="reference.xml" id="s_send"><literal>s.send()</literal></link>). -</para> - -<para> -<literal>s.fromUpstream</literal> -(replaced with a callback for a corresponding event). -</para> - -<para> -<literal>s.eof</literal> -(replaced with <literal></literal> -<link doc="reference.xml" id="s_on_callback_last"><literal>flags.last</literal></link>). -</para> - -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added -<literal>Function.prototype.length</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -introduced sandboxing mode. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added exception strings where appropriate. -</para> -</listitem> - -<listitem> -<para> -Improvement: -improved wording for primitive type conversion exception. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -throwing <literal>TypeError</literal> -for attempts to change frozen properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.defineProperty()</literal> for existing properties. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -respecting the enumerable attribute while iterating by for in. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -respecting writable attribute for property handlers. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed exception handling in arguments of a function. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object.prototype.toString</literal> -for different value types. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Object()</literal> -constructor for object types arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed comparison of objects and strings. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>String.slice()</literal> -for undefined arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.3" name="Changes with njs 0.2.3"> - -<para> -Release Date: -31 July 2018 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -making a subrequest from a -<literal>Reply</literal> -object caused a segmentation fault. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -getting the parent property of the main -<link doc="reference.xml" id="http">HTTP Request</link> -object caused a segmentation fault. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added the pretty string representation for values. -</para> -</listitem> - -<listitem> -<para> -Feature: -correctly printing floating point numbers. -</para> -</listitem> - -<listitem> -<para> -Feature: -correctly parsing floating point numbers. -</para> -</listitem> - -<listitem> -<para> -Feature: -<link doc="reference.xml" id="string_bytesfrom"><literal>String.bytesFrom()</literal></link> method -(decoding <literal>hex</literal>, -<literal>base64</literal>, -<literal>base64url</literal> into a byte string). -</para> -</listitem> - -<listitem> -<para> -Feature: -<literal>String.padStart()</literal> and -<literal>String.padEnd()</literal> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -added support of binary literals. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added information about illegal token in number parsing. -</para> -</listitem> - -<listitem> -<para> -Improvement: -allowed uppercased <literal>O</literal> in octal literal values. -</para> -</listitem> - -<listitem> -<para> -Improvement: -added support for multiple arguments in <literal>console.log()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed applying <literal>call()</literal> to methods of external values. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed addition operator applied to an object. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed exception handling in -<literal>njs_vm_value_to_ext_string()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed -<literal>Number()</literal> with boolean, null and undefined arguments. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed error handling of setting non-numeric <literal>Array.length</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed autocompletion for global objects. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.2" name="Changes with njs 0.2.2"> - -<para> -Release Date: -19 June 2018 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Change: -merged HTTP <literal>Response</literal> and <literal>Reply</literal> -into <link doc="reference.xml" id="http">HTTP Request</link>. -New members of <literal>Request</literal>: - -<list type="bullet"> - -<listitem> -<para> -<literal>req.status</literal> (<literal>res.status</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.parent</literal> (<literal>reply.parent</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.requestBody</literal> (<literal>req.body</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.responseBody</literal> (<literal>reply.body</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.headersIn</literal> (<literal>req.headers</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.headersOut</literal> (<literal>res.headers</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.sendHeader()</literal> (<literal>res.sendHeader()</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.send()</literal> (<literal>res.send()</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.finish()</literal> (<literal>res.finish()</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.return()</literal> (<literal>res.return()</literal>) -</para> -</listitem> - -</list> -Deprecated members of <literal>Request</literal>: - -<list type="bullet"> - -<listitem> -<para> -<literal>req.body</literal> (use <literal>req.requestBody</literal> -or <literal>req.responseBody</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.headers</literal> (use <literal>req.headersIn</literal> -or <literal>req.headersOut</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>req.response</literal> -</para> -</listitem> - -</list> -Deprecated members of <literal>Response</literal>: - -<list type="bullet"> - -<listitem> -<para> -<literal>res.contentLength</literal> (use -<link doc="reference.xml" id="r_headers_out"><literal>req.headersOut</literal></link><literal>['Content-Length']</literal>) -</para> -</listitem> - -<listitem> -<para> -<literal>res.contentType</literal> (use <link doc="reference.xml" id="r_headers_out"><literal>req.headersOut</literal></link><literal>['Content-Type']</literal>) -</para> -</listitem> - -</list> -The deprecated properties will be removed in -<link id="njs0.2.8">next</link> releases. -</para> -</listitem> - -<listitem> -<para> -Feature: -HTTP <link doc="reference.xml" id="r_internal_redirect">internalRedirect()</link> -method. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Bugfix: -fixed heap-buffer-overflow in -<literal>crypto.createHmac()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.1" name="Changes with njs 0.2.1"> - -<para> -Release Date: -31 May 2018 -</para> - -<para> -nginx modules: -<list type="bullet"> - -<listitem> -<para> -Feature: -HTTP request body getter. -</para> -</listitem> - -<listitem> -<para> -Improvement: -moved njs vm to the <literal>main</literal> configuration. -</para> -</listitem> - -<listitem> -<para> -Improvement: -improved logging for -<link doc="../http/ngx_http_js_module.xml" id="js_set"/> and -<link doc="../http/ngx_http_js_module.xml" id="js_content"/> directives. -</para> -</listitem> - -<listitem> -<para> -Improvement: -setting status code to 500 by default in the -<link doc="../http/ngx_http_js_module.xml" id="js_content"/> handler -</para> -</listitem> - -<listitem> -<para> -Improvement: -added the debug for the returned status code in -<link doc="../http/ngx_http_js_module.xml" id="js_content"/> handler -</para> -</listitem> - -<listitem> -<para> -Bugfix: fixed error logging in -<link doc="../http/ngx_http_js_module.xml" id="js_include"/>. -</para> -</listitem> - -</list> -</para> - -<para> -Core: -<list type="bullet"> - -<listitem> -<para> -Feature: -added array length setter. -</para> -</listitem> - -<listitem> -<para> -Improvement: -public header <literal>cleanup. njscript.h</literal> is renamed to -<literal>njs.h</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed crypto <literal>update()</literal> method after -<literal>digest()</literal> is called. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>crypto.createHmac()</literal> for keys with size <= alg size -and > 64. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>JSON.stringify()</literal> for arrays with empty cells. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed exception type for unsupported types in -<literal>JSON.stringify()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of undefined arguments of functions. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of missing <literal>arg</literal> of -<literal>Object.getOwnPropertyDescriptor()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed handling of properties in -<literal>Object.getOwnPropertyDescriptor()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed the writeable flag of <literal>Array.length</literal> property. -</para> -</listitem> - -<listitem> -<para> -Bugfix: fixed return value type of <literal>clearTimeout()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -fixed <literal>njs_vm_external_bind()</literal>. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.2.0" name="Changes with njs 0.2.0"> - -<para> -Release Date: -03 April 2018 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -reporting njs version by CLI. -</para> -</listitem> - -<listitem> -<para> -Feature: -textual description for type converting exceptions. -</para> -</listitem> - -<listitem> -Feature: -<literal>setTimeout()</literal> and -<literal>clearTimeout()</literal> methods. -</listitem> - -<listitem> -<para> -Feature: -Byte string to -<literal>hex</literal>, -<literal>base64</literal>, -<literal>base64url</literal> encodings. -</para> -</listitem> - -<listitem> -<para> -Feature: -<link url="https://nodejs.org/api/crypto.html#crypto_class_hash">Node.js style</link> -<literal>Crypto</literal> methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -HTTP and stream -<literal>warn()</literal> and -<literal>error()</literal> methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -HTTP <literal>subrequest()</literal> method. -</para> -</listitem> - -<listitem> -<para> -Feature: -HTTP <literal>return()</literal> method. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed in the core and -interactive shell. -</para> -</listitem> - -</list> -</para> - -</section> - -<section id="njs0.1.15" name="Changes with njs 0.1.15"> - -<para> -Release Date: -20 November 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -<literal>Error</literal>, -<literal>EvalError</literal>, -<literal>InternalError</literal>, -<literal>RangeError</literal>, -<literal>ReferenceError</literal>, -<literal>SyntaxError</literal>, -<literal>TypeError</literal>, -<literal>URIError</literal> objects. -</para> -</listitem> - -<listitem> -<para> -Feature: -octal literals support. -</para> -</listitem> - -<listitem> -<para> -Feature: -<link url="https://nodejs.org/api/fs.html#fs_file_system">Node.js style</link> -<literal>File system</literal> access methods: -<literal>fs.readFile()</literal>, -<literal>fs.readFileSync()</literal>, -<literal>fs.appendFile()</literal>, -<literal>fs.appendFileSync()</literal>, -<literal>fs.writeFile()</literal>, -<literal>fs.writeFileSync()</literal>. -</para> -</listitem> - -<listitem> -<para> -Feature: -nginx modules print backtrace on exception. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.14" name="Changes with njs 0.1.14"> - -<para> -Release Date: -09 October 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -JSON object. -</para> -</listitem> - -<listitem> -<para> -Feature: -object level completions in interactive shell. -</para> -</listitem> - -<listitem> -<para> -Feature: -various configure improvements. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs have been fixed in the core and -interactive shell. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.13" name="Changes with njs 0.1.13"> - -<para> -Release Date: -31 August 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -<literal>console.log()</literal> and -<literal>console.help()</literal> -methods in interactive shell. -</para> -</listitem> - -<listitem> -<para> -Feature: -interactive shell prints backtrace on exception. -</para> -</listitem> - -<listitem> -<para> -Feature: -interactive shell by default -if <literal>libedit</literal> is available. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -processing of large files from -<literal>stdin</literal> in command line mode. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -improved <literal>editline</literal> detection. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.12" name="Changes with njs 0.1.12"> - -<para> -Release Date: -08 August 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -Interactive shell. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -in <literal>Object.isSealed()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.11" name="Changes with njs 0.1.11"> - -<para> -Release Date: -27 June 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -<literal>Object.keys()</literal>, -<literal>Object.prototype.hasOwnProperty()</literal> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -<literal>Object.defineProperty()</literal>, -<literal>Object.defineProperties()</literal>, -<literal>Object.getOwnPropertyDescriptor()</literal> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -<literal>Object.getPrototypeOf()</literal>, -<literal>Object.prototype.isPrototypeOf()</literal> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -<literal>Object.preventExtensions()</literal>, -<literal>Object.isExtensible()</literal>, -<literal>Object.freeze()</literal>, -<literal>Object.isFrozen()</literal>, -<literal>Object.seal()</literal>, -<literal>Object.isSealed()</literal> -methods. -</para> -</listitem> - -<listitem> -<para> -Feature: -scientific notation (<literal>3.35e10</literal>) literals support. -</para> -</listitem> - -<listitem> -<para> -Feature: -hexadecimal (<literal>0x1123</literal>) literals support. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -processing of large array indexes. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -in <literal>parseInt()</literal> and -<literal>Date.parse()</literal>. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.10" name="Changes with njs 0.1.10"> - -<para> -Release Date: -04 April 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Feature: -nested functions and function closures. -</para> -</listitem> - -<listitem> -<para> -Feature: -<literal>Array.of()</literal>, -<literal>Array.prototype.fill()</literal>, -<literal>Array.prototype.find()</literal>, -<literal>Array.prototype.findIndex()</literal> -methods. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.9" name="Changes with njs 0.1.9"> - -<para> -Release Date: -01 February 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Bugfix: -global variables were not initialized when njs was used -in nginx. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.8" name="Changes with njs 0.1.8"> - -<para> -Release Date: -24 January 2017 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Change: -the <literal>strict</literal> mode is enforced, -variables must be explicitly declared. -</para> -</listitem> - - -<listitem> -<para> -Feature: -<literal>for</literal> and -<literal>for-in</literal> loops support variable declaration. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -global and function scopes have been fixed. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -now <literal>for-in</literal> loop does not discard the last value -of property variable. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.7" name="Changes with njs 0.1.7"> - -<para> -Release Date: -27 December 2016 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Change: -the <link doc="../http/ngx_http_js_module.xml" id="js_include"/> directive -has been disabled at server and location levels. -</para> -</listitem> - -<listitem> -<para> -Feature: -exponentiation operators. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - - -<section id="njs0.1.6" name="Changes with njs 0.1.6"> - -<para> -Release Date: -13 December 2016 -</para> - -<para> -<list type="bullet"> - -<listitem> -<para> -Change: -the <link doc="../http/ngx_http_js_module.xml" id="js_set"/> directive -has been disabled at server and location levels. -</para> -</listitem> - -<listitem> -<para> -Feature: -ES6 <literal>Math</literal> methods. -</para> -</listitem> - -<listitem> -<para> -Bugfix: -miscellaneous bugs and segmentation faults have been fixed. -</para> -</listitem> - -</list> -</para> - -</section> - -</article>
--- a/xml/en/docs/njs/cli.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,66 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Command-line interface" - link="/en/docs/njs/cli.html" - lang="en" - rev="4"> - -<section> -<para> -njs scripts development and debugging can be performed -from the command-line. -The command-line utility is available after the installation of -the Linux <link doc="install.xml" id="install_package">package</link> -or after building from the -<link doc="install.xml" id="install_sources">sources</link>. -Compared to njs running inside nginx, -nginx objects -(<link doc="reference.xml" id="http">HTTP</link> and -<link doc="reference.xml" id="stream">Stream</link>) -are not available in the utility. -<example> -$ 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] -} ->> -</example> -</para> - -</section> - -</article>
--- a/xml/en/docs/njs/compatibility.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1266 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Compatibility" - link="/en/docs/njs/compatibility.html" - lang="en" - rev="44" - toc="no"> - -<section> - -<para> -njs is created in compliance with -<link url="http://www.ecma-international.org/ecma-262/5.1/">ECMAScript 5.1</link> -(strict mode) with some -<link url="http://www.ecma-international.org/ecma-262/6.0/">ECMAScript 6</link> -and later extensions. -The compliance is still evolving. -</para> - -<para> -Definitions of njs specific properties and methods -not compliant with ECMAScript can be found in -<link doc="reference.xml">Reference</link>. -Definitions of njs properties and methods -compliant with ECMAScript can be found in -<link url="http://www.ecma-international.org/ecma-262/">ECMAScript -specification</link>. -</para> - -</section> - - -<section id="supported" name="What is currently supported"> - -<para> -<list type="bullet" compact="no"> - -<listitem> -Boolean values, numbers, strings, objects, arrays, -functions, function constructors -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>), -and regular expressions -</listitem> - -<listitem> -ES5.1 operators, ES7 exponentiation operators -</listitem> - -<listitem> -ES5.1 statements: -<literal>break</literal>, -<literal>catch</literal>, -<literal>continue</literal>, -<literal>do while</literal>, -<literal>else</literal>, -<literal>finally</literal>, -<literal>for</literal>, -<literal>for in</literal>, -<literal>if</literal>, -<literal>return</literal>, -<literal>switch</literal>, -<literal>throw</literal>, -<literal>try</literal>, -<literal>var</literal>, -<literal>while</literal>, -labeled statements (<link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</listitem> - -<listitem> -ES6 statements: -<literal>let</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>), -<literal>const</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>), -<literal>async</literal> (<link doc="changes.xml" id="njs0.7.0">0.7.0</link>), -<literal>await</literal> (<link doc="changes.xml" id="njs0.7.0">0.7.0</link>) -</listitem> - -<listitem> -<literal>Math</literal> properties: -<list type="bullet"> - -<listitem> -ES6: -<literal>E</literal>, -<literal>LN10</literal>, -<literal>LN2</literal>, -<literal>LOG10E</literal>, -<literal>LOG2E</literal>, -<literal>PI</literal>, -<literal>SQRT1_2</literal>, -<literal>SQRT2</literal> -</listitem> -</list> -</listitem> - -<listitem> -<literal>Math</literal> methods: -<list type="bullet"> - -<listitem> -ES6: -<literal>abs</literal>, -<literal>acos</literal>, -<literal>acosh</literal>, -<literal>asin</literal>, -<literal>asinh</literal>, -<literal>atan</literal>, -<literal>atan2</literal>, -<literal>atanh</literal>, -<literal>cbrt</literal>, -<literal>ceil</literal>, -<literal>clz32</literal>, -<literal>cos</literal>, -<literal>cosh</literal>, -<literal>exp</literal>, -<literal>expm1</literal>, -<literal>floor</literal>, -<literal>fround</literal>, -<literal>hypot</literal>, -<literal>imul</literal>, -<literal>log</literal>, -<literal>log10</literal>, -<literal>log1p</literal>, -<literal>log2</literal>, -<literal>max</literal>, -<literal>min</literal>, -<literal>pow</literal>, -<literal>random</literal>, -<literal>round</literal>, -<literal>sign</literal>, -<literal>sin</literal>, -<literal>sinh</literal>, -<literal>sqrt</literal>, -<literal>tan</literal>, -<literal>tanh</literal>, -<literal>trunc</literal> -</listitem> -</list> -</listitem> - -<listitem> -<literal>Number</literal> properties: -<list type="bullet"> - -<listitem> -ES6: -<literal>EPSILON</literal>, -<literal>MAX_SAFE_INTEGER</literal>, -<literal>MAX_VALUE</literal>, -<literal>MIN_SAFE_INTEGER</literal>, -<literal>MIN_VALUE</literal>, -<literal>NEGATIVE_INFINITY</literal>, -<literal>NaN</literal>, -<literal>POSITIVE_INFINITY</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Number</literal> methods: -<list type="bullet"> - -<listitem> -ES6: -<literal>isFinite</literal>, -<literal>isInteger</literal>, -<literal>isNaN</literal>, -<literal>isSafeInteger</literal>, -<literal>parseFloat</literal>, -<literal>parseInt</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Number</literal> prototype methods: -<list type="bullet"> - -<listitem> -ES6: -<literal>toExponential</literal> -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>), -<literal>toFixed</literal> -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>), -<literal>toPrecision</literal> -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>) -</listitem> -</list> - -</listitem> - -<listitem> -<literal>String</literal> methods: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>fromCharCode</literal> -</listitem> - -<listitem> -ES6: -<literal>fromCodePoint</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>String</literal> prototype methods: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>charAt</literal>, -<literal>concat</literal>, -<literal>indexOf</literal>, -<literal>lastIndexOf</literal>, -<literal>match</literal>, -<literal>replace</literal>, -<literal>search</literal>, -<literal>slice</literal>, -<literal>split</literal>, -<literal>substr</literal>, -<literal>substring</literal>, -<literal>toLowerCase</literal>, -<literal>trim</literal>, -<literal>toUpperCase</literal> -</listitem> - -<listitem> -ES6: -<literal>codePointAt</literal>, -<literal>endsWith</literal>, -<literal>includes</literal>, -<literal>repeat</literal>, -<literal>startsWith</literal> -</listitem> - -<listitem> -ES8: -<literal>padEnd</literal>, -<literal>padStart</literal> -</listitem> - -<listitem> -ES9: -<literal>trimEnd</literal> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>), -<literal>trimStart</literal> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>) -</listitem> - -<listitem> -ES12: -<literal>replaceAll</literal> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>) -</listitem> - -</list> - -</listitem> - -<listitem> -<literal>Object</literal> methods: -<list type="bullet"> -<listitem> -ES5.1: -<literal>create</literal> (support without properties list), -<literal>defineProperties</literal> (accessor descriptors support -since <link doc="changes.xml" id="njs0.3.3">0.3.3</link>), -<literal>defineProperty</literal> (accessor descriptors support -since <link doc="changes.xml" id="njs0.3.3">0.3.3</link>), -<literal>freeze</literal>, -<literal>getOwnPropertyDescriptor</literal>, -<literal>getOwnPropertyDescriptors</literal> -(<link doc="changes.xml" id="njs0.3.1">0.3.1</link>), -<literal>getOwnPropertyNames</literal> -(<link doc="changes.xml" id="njs0.3.1">0.3.1</link>), -<literal>getPrototypeOf</literal>, -<literal>isExtensible</literal>, -<literal>isFrozen</literal>, -<literal>isSealed</literal>, -<literal>keys</literal>, -<literal>preventExtensions</literal>, -<literal>seal</literal> -</listitem> - -<listitem> -ES6: -<literal>assign</literal> -(<link doc="changes.xml" id="njs0.3.7">0.3.7</link>) -</listitem> - -<listitem> -ES8: -<literal>entries</literal> -(<link doc="changes.xml" id="njs0.2.7">0.2.7</link>), -<literal>values</literal> -(<link doc="changes.xml" id="njs0.2.7">0.2.7</link>) -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Object</literal> prototype methods: -<list type="bullet"> -<listitem> -ES5.1: -<literal>hasOwnProperty</literal>, -<literal>isPrototypeOf</literal>, -(<link doc="changes.xml" id="njs0.3.0">0.3.0</link>), -<literal>propertyIsEnumerable</literal>, -<literal>toString</literal>, -<literal>valueOf</literal> -</listitem> - -<listitem> -ES6: -<literal>is</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>), -<literal>setPrototypeOf</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>) -</listitem> - -</list> -</listitem> - -<listitem> -<literal>Array</literal> methods: -<list type="bullet"> -<listitem> -ES5.1: -<literal>isArray</literal> -</listitem> - -<listitem> -ES6: -<literal>of</literal> -</listitem> - -<listitem> -ES13: -<literal>from</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Array</literal> prototype methods: -<list type="bullet"> -<listitem> -ES5.1: -<literal>concat</literal>, -<literal>every</literal>, -<literal>filter</literal>, -<literal>forEach</literal>, -<literal>indexOf</literal>, -<literal>join</literal>, -<literal>lastIndexOf</literal>, -<literal>map</literal>, -<literal>pop</literal>, -<literal>push</literal>, -<literal>reduce</literal>, -<literal>reduceRight</literal>, -<literal>reverse</literal>, -<literal>shift</literal>, -<literal>slice</literal>, -<literal>some</literal>, -<literal>sort</literal>, -<literal>splice</literal>, -<literal>unshift</literal> -</listitem> - -<listitem> -ES6: -<literal>copyWithin</literal> -(<link doc="changes.xml" id="njs0.3.7">0.3.7</link>), -<literal>fill</literal>, -<literal>find</literal>, -<literal>findIndex</literal> -</listitem> - -<listitem> -ES7: <literal>includes</literal> -</listitem> - -<listitem> -ES13: -<literal>toReversed</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<literal>toSorted</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<literal>toSpliced</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</listitem> -</list> - -</listitem> - -<listitem> -<literal>ArrayBuffer</literal> methods -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>isView</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>ArrayBuffer</literal> prototype methods -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>slice</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Typed-array</literal> constructors -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>Int8Array</literal>, -<literal>Uint8Array</literal>, -<literal>Uint8ClampedArray</literal>, -<literal>Int16Array</literal>, -<literal>Uint16Array</literal>, -<literal>Int32Array</literal>, -<literal>Uint32Array</literal>, -<literal>Float32Array</literal>, -<literal>Float64Array</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Typed-array</literal> prototype methods -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>copyWithin</literal>, -<literal>every</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>fill</literal>, -<literal>filter</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>find</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>findIndex</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>forEach</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>includes</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>indexOf</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>join</literal>, -<literal>lastIndexOf</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>map</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>reduce</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>reduceRight</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>reverse</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>set</literal>, -<literal>slice</literal>, -<literal>some</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>sort</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<literal>subarray</literal>, -<literal>toString</literal> -</listitem> - -<listitem> -ES13: -<literal>toReversed</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -<literal>toSorted</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</listitem> - -</list> - -</listitem> - -<listitem> -<literal>Buffer</literal> methods -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>): -<list type="bullet"> -<listitem> -<link doc="reference.xml" id="buffer_alloc"><literal>alloc</literal></link>, -<link doc="reference.xml" id="buffer_alloc_unsafe"><literal>allocUnsafe</literal></link>, -<link doc="reference.xml" id="buffer_bytelength"><literal>byteLength</literal></link>, -<link doc="reference.xml" id="buffer_compare"><literal>compare</literal></link>, -<link doc="reference.xml" id="buffer_concat"><literal>concat</literal></link>, -<link doc="reference.xml" id="buffer_from_array"><literal>from</literal></link>, -<link doc="reference.xml" id="buffer_is_buffer"><literal>isBuffer</literal></link>, -<link doc="reference.xml" id="buffer_is_encoding"><literal>isEncoding</literal></link> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Buffer</literal> prototype methods: -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>): -<list type="bullet"> -<listitem> -<link doc="reference.xml" id="buf_compare"><literal>compare</literal></link>, -<link doc="reference.xml" id="buf_copy"><literal>copy</literal></link>, -<link doc="reference.xml" id="buf_equals"><literal>equals</literal></link>, -<link doc="reference.xml" id="buf_fill"><literal>fill</literal></link>, -<link doc="reference.xml" id="buf_includes"><literal>includes</literal></link>, -<link doc="reference.xml" id="buf_indexof"><literal>indexOf</literal></link>, -<link doc="reference.xml" id="buf_lastindexof"><literal>lastIndexOf</literal></link>, -<link doc="reference.xml" id="buf_readintbe"><literal>readIntBE</literal></link>, -<literal>readInt8</literal>, -<literal>readInt16BE</literal>, -<literal>readInt32BE</literal>, -<link doc="reference.xml" id="buf_readintle"><literal>readIntLE</literal></link>, -<literal>readInt8</literal>, -<literal>readInt16LE</literal>, -<literal>readInt32LE</literal>, -<link doc="reference.xml" id="buf_readuintbe"><literal>readUIntBE</literal></link>, -<literal>readUInt8</literal>, -<literal>readUInt16BE</literal>, -<literal>readUInt32BE</literal>, -<link doc="reference.xml" id="buf_readuintle"><literal>readUIntLE</literal></link>, -<literal>readUInt8</literal>, -<literal>readUInt16LE</literal>, -<literal>readUInt32LE</literal>, -<link doc="reference.xml" id="buf_readdobulebe"><literal>readDoubleBE</literal></link>, -<link doc="reference.xml" id="buf_readdobulele"><literal>readDoubleLE</literal></link>, -<link doc="reference.xml" id="buf_readfloatbe"><literal>readFloatBE</literal></link>, -<link doc="reference.xml" id="buf_readfloatle"><literal>readFloatLE</literal></link>, -<link doc="reference.xml" id="buf_subarray"><literal>subarray</literal></link>, -<link doc="reference.xml" id="buf_slice"><literal>slice</literal></link>, -<link doc="reference.xml" id="buf_swap16"><literal>swap16</literal></link>, -<link doc="reference.xml" id="buf_swap32"><literal>swap32</literal></link>, -<link doc="reference.xml" id="buf_swap64"><literal>swap64</literal></link>, -<link doc="reference.xml" id="buf_tojson"><literal>toJSON</literal></link>, -<link doc="reference.xml" id="buf_tostring"><literal>toString</literal></link>, -<link doc="reference.xml" id="buf_write"><literal>write</literal></link>, -<link doc="reference.xml" id="buf_writeintbe"><literal>writeIntBE</literal></link>, -<literal>writeInt8</literal>, -<literal>writeInt16BE</literal>, -<literal>writeInt32BE</literal>, -<link doc="reference.xml" id="buf_writeintle"><literal>writeIntLE</literal></link>, -<literal>writeInt8</literal>, -<literal>writeInt16LE</literal>, -<literal>writeInt32LE</literal>, -<link doc="reference.xml" id="buf_writeuintbe"><literal>writeUIntBE</literal></link>, -<literal>writeUInt8</literal>, -<literal>writeUInt16BE</literal>, -<literal>writeUInt32BE</literal>, -<link doc="reference.xml" id="buf_writeuintle"><literal>writeUIntLE</literal></link>, -<literal>writeUInt8</literal>, -<literal>writeUInt16LE</literal>, -<literal>writeUInt32LE</literal>, -<link doc="reference.xml" id="buf_writedoublebe"><literal>writeDoubleBE</literal></link>, -<link doc="reference.xml" id="buf_writedoublele"><literal>writeDoubleLE</literal></link>, -<link doc="reference.xml" id="buf_writefloatbe"><literal>writeFloatBE</literal></link>, -<link doc="reference.xml" id="buf_writefloatle"><literal>writeFloatLE</literal></link> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Promise</literal> methods -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>any</literal> -(<link doc="changes.xml" id="njs0.6.2">0.6.2</link>), -<literal> all</literal> -(<link doc="changes.xml" id="njs0.6.2">0.6.2</link>), -<literal> allSettled</literal> -(<link doc="changes.xml" id="njs0.6.2">0.6.2</link>), -<literal>reject</literal>, -<literal>resolve</literal>, -<literal>race</literal> (<link doc="changes.xml" id="njs0.6.2">0.6.2</link>) -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Promise</literal> prototype methods -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>catch</literal>, -<literal>finally</literal>, -<literal>then</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Function</literal> prototype methods: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>apply</literal>, -<literal>bind</literal>, -<literal>call</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>RegExp</literal> prototype accessor properties: -<list type="bullet"> - -<listitem> -<literal>flags</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>), -<literal>global</literal>, -<literal>ignoreCase</literal>, -<literal>multiline</literal>, -<literal>source</literal>, -<literal>sticky</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>) -</listitem> -</list> - -</listitem> - -<listitem> -<literal>RegExp</literal> prototype methods: -<list type="bullet"> - -<listitem> -<literal>[@@replace]</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<literal>[@@split]</literal> -(<link doc="changes.xml" id="njs0.6.0">0.6.0</link>) -</listitem> - -<listitem> -ES5.1: -<literal>exec</literal>, -<literal>test</literal>, -<literal>toString</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>RegExp</literal> instance properties: -<list type="bullet"> - -<listitem> -<literal>lastIndex</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>RegExp</literal> -ES9 named capture groups (<link doc="changes.xml" id="njs0.3.2">0.3.2</link>) -</listitem> - -<listitem> -<literal>DataView</literal> prototype methods -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>): -<list type="bullet"> - -<listitem> -ES6: -<literal>getFloat32</literal>, -<literal>getFloat64</literal>, -<literal>getInt16</literal>, -<literal>getInt32</literal>, -<literal>getInt8</literal>, -<literal>getUint16</literal>, -<literal>getUint32</literal>, -<literal>getUint8</literal>, -<literal>setFloat32</literal>, -<literal>setFloat64</literal>, -<literal>setInt16</literal>, -<literal>setInt32</literal>, -<literal>setInt8</literal>, -<literal>setUint16</literal>, -<literal>setUint32</literal>, -<literal>setUint8</literal> -</listitem> - -</list> -</listitem> - -<listitem> -<literal>Date</literal> methods: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>now</literal>, -<literal>parse</literal>, -<literal>UTC</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Date</literal> prototype methods: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>getDate</literal>, -<literal>getDay</literal>, -<literal>getFullYear</literal>, -<literal>getHours</literal>, -<literal>getMilliseconds</literal>, -<literal>getMinutes</literal>, -<literal>getMonth</literal>, -<literal>getSeconds</literal>, -<literal>getTime</literal>, -<literal>getTimezoneOffset</literal>, -<literal>getUTCDate</literal>, -<literal>getUTCDay</literal>, -<literal>getUTCFullYear</literal>, -<literal>getUTCHours</literal>, -<literal>getUTCMilliseconds</literal>, -<literal>getUTCMinutes</literal>, -<literal>getUTCMonth</literal>, -<literal>getUTCSeconds</literal>, -<literal>toDateString</literal>, -<literal>toISOString</literal>, -<literal>toLocaleDateString</literal>, -<literal>toLocaleString</literal>, -<literal>toLocaleTimeString</literal>, -<literal>toTimeString</literal>, -<literal>toUTCString</literal>, -<literal>setDate</literal>, -<literal>setFullYear</literal>, -<literal>setHours</literal>, -<literal>setMinutes</literal>, -<literal>setMilliseconds</literal>, -<literal>setMonth</literal>, -<literal>setSeconds</literal>, -<literal>setTime</literal>, -<literal>setUTCDate</literal>, -<literal>setUTCFullYear</literal>, -<literal>setUTCHours</literal>, -<literal>setUTCMilliseconds</literal>, -<literal>setUTCMinutes</literal>, -<literal>setUTCMonth</literal>, -<literal>setUTCSeconds</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>JSON</literal> methods: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>parse</literal>, -<literal>stringify</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>Symbol</literal> methods -(<link doc="changes.xml" id="njs0.7.6">0.7.6</link>): -<list type="bullet"> - -<listitem> -<literal>for</literal>, -<literal>keyfor</literal> -</listitem> -</list> - -</listitem> - -<listitem> -ES5.1 <literal>arguments</literal> object -(<link doc="changes.xml" id="njs0.2.5">0.2.5</link>) -</listitem> - -<listitem> -ES6 rest parameters syntax (without destructuring support) -(<link doc="changes.xml" id="njs0.2.7">0.2.7</link>) -</listitem> - -<listitem> -ES5.1 global functions: -<literal>decodeURI</literal>, -<literal>decodeURIComponent</literal>, -<literal>encodeURI</literal>, -<literal>encodeURIComponent</literal>, -<literal>isFinite</literal>, -<literal>isNaN</literal>, -<literal>parseFloat</literal>, -<literal>parseInt</literal> -</listitem> - -<listitem> -Global functions (<link doc="changes.xml" id="njs0.7.6">0.7.6</link>): -<link doc="reference.xml" id="atob"><literal>atob</literal></link>, -<link doc="reference.xml" id="btoa"><literal>btoa</literal></link> -</listitem> - -<listitem> -<literal>Error</literal> objects: -<literal>Error</literal>, -<literal>EvalError</literal>, -<literal>InternalError</literal>, -<literal>RangeError</literal>, -<literal>ReferenceError</literal>, -<literal>SyntaxError</literal>, -<literal>TypeError</literal>, -<literal>URIError</literal> -</listitem> - -<listitem> -<link doc="reference.xml" id="cleartimeout"><literal>clearTimeout</literal></link> -and -<link doc="reference.xml" id="settimeout"><literal>setTimeout</literal></link> -functions -(<link doc="changes.xml" id="njs0.2.0">0.2.0</link>) -</listitem> - -<listitem> -<literal>File system</literal> methods: -<link doc="reference.xml" id="fs_accesssync"><literal>fs.accessSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="appendfilesync"><literal>fs.appendFileSync</literal></link>, -<link doc="reference.xml" id="fs_closesync"><literal>fs.closeSync</literal></link>, -<link doc="reference.xml" id="fs_existssync"><literal>fs.existsSync</literal></link> -(<link doc="changes.xml" id="njs0.8.2">0.8.2</link>), -<link doc="reference.xml" id="fs_filehandle"><literal>fs.FileHandle</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_fstatsync"><literal>fs.fstatSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_lstatsync"><literal>fs.lstatSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.1</link>), -<link doc="reference.xml" id="fs_mkdirsync"><literal>fs.mkdirSync</literal></link> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<link doc="reference.xml" id="fs_opensync"><literal>fs.openSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_promises_open"><literal>fs.promises.open</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_readdirsync"><literal>fs.readdirSync</literal></link> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<link doc="reference.xml" id="readfilesync"><literal>fs.readFileSync</literal></link>, -<link doc="reference.xml" id="fs_readsync"><literal>fs.readSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_realpathsync"><literal>fs.realpathSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="fs_renamesync"><literal>fs.renameSync</literal></link> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>), -<link doc="reference.xml" id="fs_rmdirsync"><literal>fs.rmdirSync</literal></link> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<link doc="reference.xml" id="fs_symlinksync"><literal>fs.symlinkSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="fs_unlinksync"><literal>fs.unlinkSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="fs_writefilesync"><literal>fs.writeFileSync</literal></link> -<link doc="reference.xml" id="fs_writesync_buf"><literal>fs.writeSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>) -</listitem> - -<listitem> -<literal>fs.promises</literal> API (<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -asynchronous version of file system methods. -</listitem> - -<listitem> -<link doc="reference.xml" id="crypto"><literal>Crypto</literal></link> methods -(<link doc="changes.xml" id="njs0.2.0">0.2.0</link>): -<link doc="reference.xml" id="crypto_createhash"><literal>crypto.createHash</literal></link>, -<link doc="reference.xml" id="crypto_createhmac"><literal>crypto.createHmac</literal></link> -</listitem> - -<listitem id="querysting"> -<link doc="reference.xml" id="querystring"><literal>Query String</literal></link> -methods -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>): -<link doc="reference.xml" id="querystring_decode"><literal>querystring.decode</literal></link>, -<link doc="reference.xml" id="querystring_encode"><literal>querystring.encode</literal></link>, -<link doc="reference.xml" id="querystring_escape"><literal>querystring.escape</literal></link>, -<link doc="reference.xml" id="querystring_parse"><literal>querystring.parse</literal></link>, -<link doc="reference.xml" id="querystring_stringify"><literal>querystring.stringify</literal></link>, -<link doc="reference.xml" id="querystring_unescape"><literal>querystring.unescape</literal></link> -</listitem> - -<listitem id="textdecoder"> -<link doc="reference.xml" id="textdecoder"><literal>TextDecoder</literal></link> -methods -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>): -<link doc="reference.xml" id="textdecoder_encoding"><literal>encoding</literal></link>, -<link doc="reference.xml" id="textdecoder_fatal"><literal>fatal</literal></link>, -<link doc="reference.xml" id="textdecoder_ignorebom"><literal>ignoreBOM</literal></link>, -<link doc="reference.xml" id="textdecoder_ignorebom"><literal>decode</literal></link> -</listitem> - -<listitem id="textencoder"> -<link doc="reference.xml" id="textencoder"><literal>TextEncoder</literal></link> -methods -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>): -<link doc="reference.xml" id="textencoder_encode"><literal>encode</literal></link>, -<link doc="reference.xml" id="textencoder_encodeinto"><literal>encodeInto</literal></link> -</listitem> - -<listitem id="xml"> -<link doc="reference.xml" id="xml"><literal>XML</literal></link> -methods -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>): -<link doc="reference.xml" id="xml_parse"><literal>parse</literal></link>, -<link doc="reference.xml" id="xml_c14n"><literal>xml.c14n</literal></link>, -<link doc="reference.xml" id="xml_exclusiveC14n"><literal>xml.exclusiveC14n</literal></link> -</listitem> - -<listitem id="zlib"> -<link doc="reference.xml" id="zlib"><literal>zlib</literal></link> -methods -(<link doc="changes.xml" id="njs0.7.12">0.7.12</link>): -<link doc="reference.xml" id="zlib_deflaterawsync"><literal>deflateRawSync</literal></link>, -<link doc="reference.xml" id="zlib_deflatesync"><literal>deflateSync</literal></link>, -<link doc="reference.xml" id="zlib_inflaterawsync"><literal>inflateRawSync</literal></link> -<link doc="reference.xml" id="zlib_inflatesync"><literal>inflateSync</literal></link> -</listitem> - -<listitem> -ES6 modules support: -default <literal>export</literal> and -default <literal>import</literal> -statements -(<link doc="changes.xml" id="njs0.3.0">0.3.0</link>) -</listitem> - -<listitem> -ES6 arrow functions -(<link doc="changes.xml" id="njs0.3.1">0.3.1</link>) -</listitem> - -<listitem> -Template literals: -multiline strings, expression interpolation, nesting templates -(<link doc="changes.xml" id="njs0.3.2">0.3.2</link>) -</listitem> - -<listitem> -Global objects -(<link doc="changes.xml" id="njs0.3.3">0.3.3</link>): -<list type="bullet"> - -<listitem> -<link doc="reference.xml" id="console"><literal>console</literal></link> -(<link doc="changes.xml" id="njs0.8.2">0.8.2</link>): -<link doc="reference.xml" id="console_error"><literal>error</literal></link>, -<link doc="reference.xml" id="console_info"><literal>info</literal></link>, -<link doc="reference.xml" id="console_log"><literal>log</literal></link>, -<link doc="reference.xml" id="console_time"><literal>time</literal></link>, -<link doc="reference.xml" id="console_time_end"><literal>timeEnd</literal></link>, -<link doc="reference.xml" id="console_warn"><literal>warn</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="builtin_crypto"><literal>crypto</literal></link> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>): -<link doc="reference.xml" id="crypto_get_random_values"><literal>getRandomValues</literal></link>, -<link doc="reference.xml" id="crypto_subtle_encrypt"><literal>subtle.encrypt</literal></link>, -<link doc="reference.xml" id="crypto_subtle_decrypt"><literal>subtle.decrypt</literal></link>, -<link doc="reference.xml" id="crypto_subtle_derive_bits"><literal>subtle.deriveBits</literal></link>, -<link doc="reference.xml" id="crypto_subtle_derive_key"><literal>subtle.deriveKey</literal></link>, -<link doc="reference.xml" id="crypto_subtle_digest"><literal>subtle.digest</literal></link> -<link doc="reference.xml" id="crypto_subtle_export_key"><literal>subtle.exportKey</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>), -<link doc="reference.xml" id="crypto_subtle_generate_key"><literal>subtle.generateKey</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>), -<link doc="reference.xml" id="crypto_subtle_import_key"><literal>subtle.importKey</literal></link>, -<link doc="reference.xml" id="crypto_subtle_sign"><literal>subtle.sign</literal></link>, -<link doc="reference.xml" id="crypto_subtle_verify"><literal>subtle.verify</literal></link> -</listitem> - -<listitem> -<literal>globalThis</literal> alias -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>), -</listitem> - -<listitem> -<link doc="reference.xml" id="njs"><literal>njs</literal></link>: -<link doc="reference.xml" id="njs_version"><literal>version</literal></link>, -<link doc="reference.xml" id="njs_version_number"><literal>version_number</literal></link> -(<link doc="changes.xml" id="njs0.7.4">0.7.4</link>), -<link doc="reference.xml" id="njs_dump"><literal>dump</literal></link>, -<link doc="reference.xml" id="njs_memory_stats"><literal>memoryStats</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="njs_on"><literal>on</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="process"><literal>process</literal></link>: -<link doc="reference.xml" id="process_argv"><literal>argv</literal></link>, -<link doc="reference.xml" id="process_env"><literal>env</literal></link>, -<link doc="reference.xml" id="process_pid"><literal>pid</literal></link>, -<link doc="reference.xml" id="process_ppid"><literal>ppid</literal></link> -</listitem> - -</list> -</listitem> - -<listitem> -nginx object methods: -<list type="bullet"> - -<listitem> -<link doc="reference.xml" id="http"><literal>HTTP Request</literal></link>: -<link doc="reference.xml" id="r_done"><literal>r.done</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>), -<link doc="reference.xml" id="r_error"><literal>r.error</literal></link>, -<link doc="reference.xml" id="r_finish"><literal>r.finish</literal></link>, -<link doc="reference.xml" id="r_internal_redirect"><literal>r.internalRedirect</literal></link>, -<link doc="reference.xml" id="r_log"><literal>r.log</literal></link>, -<link doc="reference.xml" id="r_return"><literal>r.return</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_send"><literal>r.send</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_sendbuffer"><literal>r.sendBuffer</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>), -<link doc="reference.xml" id="r_send_header"><literal>r.sendHeader</literal></link>, -<link doc="reference.xml" id="r_set_return_value"><literal>r.setReturnValue</literal></link> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>), -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest</literal></link>, -<link doc="reference.xml" id="r_warn"><literal>r.warn</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="stream"><literal>Stream Session</literal></link>: -<link doc="reference.xml" id="s_allow"><literal>s.allow</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_decline"><literal>s.decline</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_deny"><literal>s.deny</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_done"><literal>s.done</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_error"><literal>s.error</literal></link>, -<link doc="reference.xml" id="s_log"><literal>s.log</literal></link>, -<link doc="reference.xml" id="s_off"><literal>s.off</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_on"><literal>s.on</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_send"><literal>s.send</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_send_downstream"><literal>s.sendDownstream</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="s_send_upstream"><literal>s.sendUpstream</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="s_set_return_value"><literal>s.setReturnValue</literal></link> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>), -<link doc="reference.xml" id="s_warn"><literal>s.warn</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="headers"><literal>Headers</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>): -<link doc="reference.xml" id="headers_append"><literal>append</literal></link>, -<link doc="reference.xml" id="headers_delete"><literal>delete</literal></link>, -<link doc="reference.xml" id="headers_get"><literal>get</literal></link>, -<link doc="reference.xml" id="headers_getall"><literal>getAll</literal></link>, -<link doc="reference.xml" id="headers_foreach"><literal>forEach</literal></link>, -<link doc="reference.xml" id="headers_has"><literal>has</literal></link>, -<link doc="reference.xml" id="headers_set"><literal>set</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="request"><literal>Request</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>): -<link doc="reference.xml" id="request_arraybuffer"><literal>arrayBuffer</literal></link>, -<link doc="reference.xml" id="request_headers"><literal>headers</literal></link>, -<link doc="reference.xml" id="request_json"><literal>json</literal></link>, -<link doc="reference.xml" id="request_text"><literal>text</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="response"><literal>Response</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>): -<link doc="reference.xml" id="response_arraybuffer"><literal>arrayBuffer</literal></link>, -<link doc="reference.xml" id="response_headers"><literal>headers</literal></link>, -<link doc="reference.xml" id="response_json"><literal>json</literal></link>, -<link doc="reference.xml" id="response_text"><literal>text</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx"><literal>ngx</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>): -<link doc="reference.xml" id="ngx_fetch"><literal>fetch</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>), -<link doc="reference.xml" id="ngx_log"><literal>log</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx_shared"><literal>ngx.shared</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>): -<link doc="reference.xml" id="dict_add"><literal>add</literal></link>, -<link doc="reference.xml" id="dict_clear"><literal>clear</literal></link>, -<link doc="reference.xml" id="dict_delete"><literal>delete</literal></link>, -<link doc="reference.xml" id="dict_freespace"><literal>freeSpace</literal></link>, -<link doc="reference.xml" id="dict_get"><literal>get</literal></link>, -<link doc="reference.xml" id="dict_has"><literal>has</literal></link>, -<link doc="reference.xml" id="dict_incr"><literal>incr</literal></link>, -<link doc="reference.xml" id="dict_items"><literal>items</literal></link>, -<link doc="reference.xml" id="dict_keys"><literal>keys</literal></link>, -<link doc="reference.xml" id="dict_pop"><literal>pop</literal></link>, -<link doc="reference.xml" id="dict_replace"><literal>replace</literal></link>, -<link doc="reference.xml" id="dict_set"><literal>set</literal></link>, -<link doc="reference.xml" id="dict_size"><literal>size</literal></link> -</listitem> - -</list> -</listitem> - -<listitem> -nginx object properties: -<list type="bullet"> - -<listitem> -<link doc="reference.xml" id="http"><literal>HTTP Request</literal></link>: -<link doc="reference.xml" id="r_args"><literal>r.args</literal></link>, -<link doc="reference.xml" id="r_headers_in"><literal>r.headersIn</literal></link>, -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut</literal></link>, -<link doc="reference.xml" id="r_http_version"><literal>r.httpVersion</literal></link>, -<link doc="reference.xml" id="r_internal"><literal>r.internal</literal></link>, -<link doc="reference.xml" id="r_method"><literal>r.method</literal></link>, -<link doc="reference.xml" id="r_parent"><literal>r.parent</literal></link>, -<link doc="reference.xml" id="r_raw_headers_in"><literal>r.rawHeadersIn</literal></link> -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>), -<link doc="reference.xml" id="r_raw_headers_out"><literal>r.rawHeadersOut</literal></link> -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>), -<link doc="reference.xml" id="r_raw_variables"><literal>r.rawVariables</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_remote_address"><literal>r.remoteAddress</literal></link>, -<link doc="reference.xml" id="r_request_buffer"><literal>r.requestBuffer</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_request_text"><literal>r.requestText</literal></link>, -<link doc="reference.xml" id="r_response_buffer"><literal>r.responseBuffer</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_response_text"><literal>r.responseText</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_status"><literal>r.status</literal></link>, -<link doc="reference.xml" id="r_uri"><literal>r.uri</literal></link>, -<link doc="reference.xml" id="r_variables"><literal>r.variables</literal></link> -(<link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="stream"><literal>Stream Session</literal></link>: -<link doc="reference.xml" id="s_remote_address"><literal>s.remoteAddress</literal></link>, -<link doc="reference.xml" id="s_raw_variables"><literal>s.rawVariables</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="s_status"><literal>s.status</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>), -<link doc="reference.xml" id="s_variables"><literal>s.variables</literal></link> -(<link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="periodic_session"><literal>Periodic Session</literal></link> -(<link doc="changes.xml" id="njs0.8.1">0.8.1</link>): -<link doc="reference.xml" id="periodic_session_raw_variables"><literal>PeriodicSession.rawVariables</literal></link>, -<link doc="reference.xml" id="periodic_session_variables"><literal>PeriodicSession.variables</literal></link> -</listitem> - - -<listitem> -<link doc="reference.xml" id="request"><literal>Request</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>): -<link doc="reference.xml" id="request_bodyused"><literal>bodyUsed</literal></link>, -<link doc="reference.xml" id="request_cache"><literal>cache</literal></link>, -<link doc="reference.xml" id="request_credentials"><literal>credentials</literal></link>, -<link doc="reference.xml" id="request_method"><literal>method</literal></link>, -<link doc="reference.xml" id="request_mode"><literal>mode</literal></link>, -<link doc="reference.xml" id="request_url"><literal>url</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="response"><literal>Response</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>): -<link doc="reference.xml" id="response_bodyused"><literal>bodyUsed</literal></link>, -<link doc="reference.xml" id="response_ok"><literal>ok</literal></link>, -<link doc="reference.xml" id="response_redirect"><literal>redirected</literal></link>, -<link doc="reference.xml" id="response_status"><literal>status</literal></link>, -<link doc="reference.xml" id="response_statustext"><literal>statusText</literal></link>, -<link doc="reference.xml" id="response_type"><literal>type</literal></link>, -<link doc="reference.xml" id="response_url"><literal>url</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx"><literal>ngx</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>): -<link doc="reference.xml" id="ngx_build"><literal>build</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_conf_file_path"><literal>conf_file_path</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_conf_prefix"><literal>conf_prefix</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="ngx_error_log_path"><literal>error_log_path</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_prefix"><literal>prefix</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_version"><literal>version</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_version_number"><literal>version_number</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_worker_id"><literal>worker_id</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx_shared"><literal>ngx.shared</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>): -<link doc="reference.xml" id="dict_capacity"><literal>capacity</literal></link>, -<link doc="reference.xml" id="dict_name"><literal>name</literal></link>, -<link doc="reference.xml" id="dict_name"><literal>type</literal></link> -</listitem> - -</list> -</listitem> - -</list> -</para> - -</section> - -</article>
--- a/xml/en/docs/njs/examples.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,332 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Examples" - link="/en/docs/njs/examples.html" - lang="en" - rev="22"> - -<section id="summary"> - -<para> -The examples work since -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>. -</para> - -</section> - - -<section id="helloword" name="Hello World"> - -<para> -<path>nginx.conf</path>: -<example> -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} -</example> -</para> - -<para> -<literal>http.js</literal>: -<example> -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; -</example> -</para> - -</section> - - -<section id="http_auth" name="HTTP Аuthorization"> - - -<section id="jwt" name="Creating HS JWT"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -js_set $jwt http.jwt; -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - - -<section id="secure_link" name="Creating secure_link Hash"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -js_set $new_foo http.create_secure_link; -#... - -location / { - secure_link $cookie_foo; - secure_link_md5 "$uri mykey"; - # -} - -location @login { - add_header Set-Cookie "foo=$new_foo; Max-Age=60"; - return 302 /; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -function create_secure_link(r) { - return require('crypto').createHash('md5') - .update(r.uri).update(" mykey") - .digest('base64url'); -} - -export default {create_secure_link}; -</example> -</para> - -</section> - - -<section id="jwt_field" name="Getting Arbitrary Field from JWT - as nginx Variable"> - -<para> -In the following example, the <literal>sub</literal> field -is extracted from JWT payload. -The JWT token is taken from the <header>Authorization</header> header. -</para> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -js_set $jwt_payload_sub http.jwt_payload_sub; - -server { - #... - - location /jwt { - return 200 $jwt_payload_sub; - } -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - -</section> - - -<section id="http_proxying" name="HTTP Proxying"> - - -<section id="fast_response" name="Returning Fastest Response from Proxy"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -location /start { - js_content http.content; -} - -location /foo { - proxy_pass http://backend1; -} - -location /bar { - proxy_pass http://backend2; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - - -<section id="subrequests_chaining" name="Subrequests Chaining"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -location /start { - js_content http.content; -} - -location /auth { - proxy_pass http://auth_backend; -} - -location /backend { - proxy_pass http://backend; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - -</section> - - -<section id="misc" name="Miscellaneous"> - - -<section id="redirect" name="Internal Redirect"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -location /redirect { - js_content http.redirect; -} - -location @named { - return 200 named; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -function redirect(r) { - r.internalRedirect('@named'); -} - -export default {redirect}; -</example> -</para> - -</section> - -</section> - -</article>
--- a/xml/en/docs/njs/index.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,233 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="njs scripting language" - link="/en/docs/njs/index.html" - lang="en" - rev="34" - toc="no"> - -<section id="summary"> - -<para> -njs is a subset of the JavaScript language that allows -extending nginx functionality. -njs is created in compliance with -<link url="http://www.ecma-international.org/ecma-262/5.1/">ECMAScript 5.1</link> -(strict mode) with some -<link url="http://www.ecma-international.org/ecma-262/6.0/">ECMAScript 6</link> -and later extensions. -The compliance is still <link doc="compatibility.xml">evolving</link>. -</para> - -</section> - - -<section id="links"> - -<para> -<list type="bullet"> - -<listitem> -<link doc="install.xml"/> -</listitem> - -<listitem> -<link doc="changes.xml"/> -</listitem> - -<listitem> -<link doc="reference.xml"/> -</listitem> - -<listitem> -<link url="https://github.com/nginx/njs-examples/">Examples</link> -</listitem> - -<listitem> -<link doc="security.xml"/> -</listitem> - -<listitem> -<link doc="compatibility.xml"/> -</listitem> - -<listitem> -<link doc="cli.xml"/> -</listitem> - -<listitem> -<link doc="preload_objects.xml"/> -</listitem> - -<listitem> -<link id="tested_os_and_platforms">Tested OS and platforms</link> -</listitem> - -</list> -</para> - -<para> -<list type="bullet"> - -<listitem> -<link doc="../http/ngx_http_js_module.xml"> -ngx_http_js_module</link> -</listitem> - -<listitem> -<link doc="../stream/ngx_stream_js_module.xml"> -ngx_stream_js_module</link> -</listitem> - -</list> -</para> - -<para> -<list type="bullet"> - -<listitem> -<link doc="typescript.xml"/> -</listitem> - -<listitem> -<link doc="node_modules.xml"/> -</listitem> - -</list> -</para> - -</section> - - -<section id="usecases" name="Use cases"> - -<para> -<list type="bullet"> - -<listitem> -Complex access control and security checks in njs -before a request reaches an upstream server -</listitem> - -<listitem> -Manipulating response headers -</listitem> - -<listitem> -Writing flexible asynchronous content handlers and filters -</listitem> - -</list> -See <link url="https://github.com/nginx/njs-examples/">examples</link> and -<link url="https://www.nginx.com/blog/tag/nginx-javascript-module/">blog posts</link> -for more njs use cases. -</para> - -</section> - - -<section id="example" name="Basic HTTP Example"> - -<para> -To use njs in nginx: -<list type="bullet"> - -<listitem> -<para> -<link doc="install.xml">install</link> njs scripting language -</para> -</listitem> - -<listitem id="hello_world"> -<para> -create an njs script file, for example, <path>http.js</path>. -See <link doc="reference.xml">Reference</link> -for the list of njs properties and methods. -<example> -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; -</example> -</para> -</listitem> - -<listitem> - -<para> -in the <path>nginx.conf</path> file, enable -<link doc="../http/ngx_http_js_module.xml">ngx_http_js_module</link> module -and specify the -<link doc="../http/ngx_http_js_module.xml" id="js_import">js_import</link> -directive -with the <path>http.js</path> script file: -<example> -load_module modules/ngx_http_js_module.so; - -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} -</example> -</para> -</listitem> - -</list> -There is also a standalone <link doc="cli.xml">command line</link> utility -that can be used independently of nginx for njs development and debugging. -</para> - -</section> - - -<section id="tested_os_and_platforms" - name="Tested OS and platforms"> - -<para> -<list type="bullet"> - -<listitem> -FreeBSD / amd64; -</listitem> - -<listitem> -Linux / x86, amd64, arm64, ppc64el; -</listitem> - -<listitem> -Solaris 11 / amd64; -</listitem> - -<listitem> -macOS / x86_64; -</listitem> - -</list> -</para> - -</section> - - -<section id="presentation" name="Presentation at nginx.conf 2018"> - -<para><video id="Jc_L6UffFOs" /></para> - -</section> - -</article>
--- a/xml/en/docs/njs/install.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Download and install" - link="/en/docs/njs/install.html" - lang="en" - rev="3"> - -<section id="install_package" name="Installing as a Linux package"> - -<para> -For Linux, njs modules -<link doc="../../linux_packages.xml" id="dynmodules">packages</link> can be used: -<list type="bullet"> - -<listitem> -<literal>nginx-module-njs</literal> — njs -<link doc="../ngx_core_module.xml" id="load_module">dynamic</link> modules -</listitem> - -<listitem> -<literal>nginx-module-njs-dbg</literal> — debug symbols for the -<literal>nginx-module-njs</literal> package -</listitem> - -</list> -</para> - -<para> -After package installation, njs dynamic modules need to be loaded with the -<link doc="../ngx_core_module.xml" id="load_module"><literal>load_module</literal></link> -directive: -<example> -load_module modules/ngx_http_js_module.so; -</example> -or -<example> -load_module modules/ngx_stream_js_module.so; -</example> -</para> - -</section> - - -<section id="install_sources" name="Building from the sources"> - -<para> -The <link url="http://hg.nginx.org/njs">repository</link> -with njs sources can be cloned with the following command: -(requires <link url="https://www.mercurial-scm.org">Mercurial</link> client): -<example> -hg clone http://hg.nginx.org/njs -</example> -Then the modules should be compiled from -<link doc="../configure.xml">nginx</link> root directory using the -<literal>--add-module</literal> configuration parameter: -<example> -./configure --add-module=<value>path-to-njs</value>/nginx -</example> -The modules can also be built as -<link doc="../ngx_core_module.xml" id="load_module">dynamic</link>: -<example> -./configure --add-dynamic-module=<value>path-to-njs</value>/nginx -</example> -</para> - -<para> -To build only njs command-line <link doc="cli.xml">utility</link>, run -<literal>./configure</literal> and <literal>make njs</literal> commands -from njs root directory. -The utility is available as <literal>./build/njs</literal>. -</para> - -</section> - -</article>
--- a/xml/en/docs/njs/node_modules.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,543 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Using node modules with njs" - link="/en/docs/njs/node_modules.html" - lang="en" - rev="6"> - -<section id="intro"> - -<para> -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 -<link url="https://nodejs.org/">Node.js</link> code in njs. -</para> - -<note> -Examples in this article use features that appeared in -<link doc="index.xml">njs</link> -<link doc="changes.xml" id="njs0.3.8">0.3.8</link> -</note> - -<para> -There is a number of issues -that may arise when 3rd-party code is added to njs: - -<list type="bullet"> - -<listitem> -Multiple files that reference each other and their dependencies -</listitem> - -<listitem> -Platform-specific APIs -</listitem> - -<listitem> -Modern standard language constructions -</listitem> - -</list> -</para> - -<para> -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. - -<list type="bullet"> - -<listitem> -Multiple files that reference each other, and their dependencies -<para> -This can be solved by merging all the interdependent code into a single file. -Tools like -<link url="http://browserify.org/">browserify</link> or -<link url="https://webpack.js.org/">webpack</link> -accept an entire project and produce a single file containing -your code and all the dependencies. -</para> -</listitem> - -<listitem> -Platform-specific APIs -<para> -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 -<link url="https://polyfill.io/v3/">polyfill</link> approach. -</para> -</listitem> - -<listitem> -Modern standard language constructions -<para> -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, <link url="https://babeljs.io/"> babel</link> project -can be used to this purpose. -</para> -</listitem> - -</list> -</para> - -<para> -In this guide, we will use two relatively large npm-hosted libraries: - -<list type="bullet"> - -<listitem> -<link url="https://www.npmjs.com/package/protobufjs">protobufjs</link>— -a library for creating and parsing protobuf messages used by the -<link url="https://grpc.io/">gRPC</link> protocol -</listitem> - -<listitem> -<link url="https://www.npmjs.com/package/dns-packet">dns-packet</link>— -a library for processing DNS protocol packets -</listitem> - -</list> -</para> - -</section> - - -<section id="environment" name="Environment"> - -<para> -<note> -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. -</note> -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: -<example> -$ 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 -</example> -</para> - -</section> - - -<section id="protobuf" name="Protobufjs"> - -<para> -The library provides a parser -for the <literal>.proto</literal> interface definitions -and a code generator for message parsing and generation. -</para> - -<para> -In this example, we will use the -<link url="https://github.com/grpc/grpc/blob/master/examples/protos/helloworld.proto">helloworld.proto</link> -file -from the gRPC examples. -Our goal is to create two messages: -<literal>HelloRequest</literal> and -<literal>HelloResponse</literal>. -We will use the -<link url="https://github.com/protobufjs/protobuf.js/blob/master/README.md#reflection-vs-static-code">static</link> -mode of protobufjs instead of dynamically generating classes, because -njs doesn't support adding new functions dynamically -due to security considerations. -</para> - -<para> -Next, the library is installed and -the JavaScript code implementing message marshalling -is generated from the protocol definition: -<example> -$ npm install protobufjs -$ npx pbjs -t static-module helloworld.proto > static.js -</example> -</para> - -<para> -Thus, the <literal>static.js</literal> file becomes our new dependency, -storing all the code we need to implement message processing. -The <literal>set_buffer()</literal> function contains code that uses the -library to create a buffer with the serialized -<literal>HelloRequest</literal> message. -The code resides in the <literal>code.js</literal> file: -<example> -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); -</example> -</para> - -<para> -To ensure it works, we execute the code using node: -<example> -$ node ./code.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] -</example> -You can see that this got us a properly encoded <literal>gRPC</literal> frame. -Now let's run it with njs: -<example> -$ njs ./code.js -Thrown: -Error: Cannot find module "./static.js" - at require (native) - at main (native) -</example> -</para> - -<para> -Modules are not supported, so we've received an exception. -To overcome this issue, let's use <literal>browserify</literal> -or other similar tool. -</para> - -<para> -An attempt to process our existing <literal>code.js</literal> 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. -<note> -In this guide, we use -njs <link doc="cli.xml">cli</link> in all examples for the sake of simplicity. -In real life, you will be using nginx njs module to run your code. -</note> -</para> - -<para> -The <literal>load.js</literal> file contains the library-loading code that -stores its handle in the global namespace: -<example> -global.hello = require('./static.js'); -</example> -This code will be replaced with merged content. -Our code will be using the "<literal>global.hello</literal>" handle to access -the library. -</para> - -<para> -Next, we process it with <literal>browserify</literal> -to get all dependencies into a single file: -<example> -$ npx browserify load.js -o bundle.js -d -</example> -The result is a huge file that contains all our dependencies: -<example> -(function(){function...... -... -... -},{"protobufjs/minimal":9}]},{},[1]) -//# sourceMappingURL.............. -</example> -To get final "<literal>njs_bundle.js</literal>" file we concatenate -"<literal>bundle.js</literal>" and the following code: -<example> -// 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); -</example> -Let's run the file using node to make sure things still work: -<example> -$ node ./njs_bundle.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] -</example> -Now let's proceed further with njs: -<example> -$ njs ./njs_bundle.js -Uint8Array [0,0,0,0,12,10,10,84,101,115,116,83,116,114,105,110,103] -</example> -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 -<literal>return frame; }</literal>: -<example> -if (global.njs) { - return String.bytesFrom(frame) -} -</example> -Finally, we got it working: -<example> -$ 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 -</example> -This is the intended result. -Response parsing can be implemented similarly: -<example> -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); -} -</example> -</para> - -</section> - - -<section id="dnspacket" name="DNS-packet"> - -<para> -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. -</para> - -<para> -Additional node packages are needed: -<example> -$ npm install @babel/core @babel/cli @babel/preset-env babel-loader -$ npm install webpack webpack-cli -$ npm install buffer -$ npm install dns-packet -</example> -The configuration file, webpack.config.js: -<example> -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'] - } - } - }] - } -}; -</example> -Note we are using "<literal>production</literal>" mode. -In this mode webpack does not use "<literal>eval</literal>" construction -not supported by njs. -The referenced <literal>load.js</literal> file is our entry point: -<example> -global.dns = require('dns-packet') -global.Buffer = require('buffer/').Buffer -</example> -We start the same way, by producing a single file for the libraries: -<example> -$ npx browserify load.js -o bundle.js -d -</example> -Next, we process the file with webpack, which itself invokes babel: -<example> -$ npx webpack --config webpack.config.js -</example> -This command produces the <literal>dist/wp_out.js</literal> file, which is a -transpiled version of <literal>bundle.js</literal>. -We need to concatenate it with <literal>code.js</literal> -that stores our code: -<example> -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; -} -</example> -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 "<literal>dist</literal>" directory: -<example> -$ cat dist/wp_out.js code.js > njs_dns_bundle.js -</example> -Let's call our code at the end of a file: -<example> -var b = set_buffer(global.dns); -console.log(b); -</example> -And execute it using node: -<example> -$ 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 -] -</example> -Make sure this works as expected, and then run it with njs: -<example> -$ 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] -</example> - -</para> - -<para> -The response can be parsed as follows: -<example> -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 -} -</example> -</para> - -</section> - -</article>
--- a/xml/en/docs/njs/preload_objects.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,74 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Understanding preloaded objects" - link="/en/docs/njs/preload_objects.html" - lang="en" - rev="2" - toc="no"> - -<section id="summary"> - -<para> -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. -</para> - -<para> -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. -</para> - -</section> - - -<section id="working_with_preload_objects" - name="Working with preload objects"> - -<para> -Here are some examples of how to work with a preload object in njs: - -<list type="bullet"> - -<listitem> -access properties by name: -<programlisting> -preloaded_object.prop_name -preloaded_object[prop_name] -</programlisting> -</listitem> - -<listitem> -enumerate properties: -<programlisting> -for (i in preloaded_object_name) { - ... -} -</programlisting> -</listitem> - -<listitem> -apply non-modifying built-in methods using <literal>call()</literal>: -<programlisting> -Array.prototype.filter.call(preloaded_object_name, ...) -</programlisting> -</listitem> - -</list> -</para> - -</section> - -</article>
--- a/xml/en/docs/njs/reference.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,6641 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Reference" - link="/en/docs/njs/reference.html" - lang="en" - rev="121"> - -<section id="summary"> - -<para> -<link doc="index.xml">njs</link> provides objects, methods and properties -for extending nginx functionality. -</para> - -<para> -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 -<link url="http://www.ecma-international.org/ecma-262/">ECMAScript -specification</link>. -List of all njs properties and methods can be found in -<link doc="compatibility.xml">Compatibility</link>. -</para> - -</section> - - -<section id="http_stream" name="nginx objects"> - - -<section id="http" name="HTTP Request"> - -<para> -<table width="100%"> -<tr><td><link id="r_args"><literal>r.args{}</literal></link></td></tr> -<tr><td><link id="r_done"><literal>r.done()</literal></link></td></tr> -<tr><td><link id="r_error"><literal>r.error()</literal></link></td></tr> -<tr><td><link id="r_finish"><literal>r.finish()</literal></link></td></tr> -<tr><td><link id="r_headers_in"><literal>r.headersIn{}</literal></link></td></tr> -<tr><td><link id="r_headers_out"><literal>r.headersOut{}</literal></link></td></tr> -<tr><td><link id="r_http_version"><literal>r.httpVersion</literal></link></td></tr> -<tr><td><link id="r_internal"><literal>r.internal</literal></link></td></tr> -<tr><td><link id="r_internal_redirect"><literal>r.internalRedirect()</literal></link></td></tr> -<tr><td><link id="r_log"><literal>r.log()</literal></link></td></tr> -<tr><td><link id="r_method"><literal>r.method</literal></link></td></tr> -<tr><td><link id="r_parent"><literal>r.parent</literal></link></td></tr> -<tr><td><link id="r_remote_address"><literal>r.remoteAddress</literal></link></td></tr> -<tr><td><link id="r_request_body"><literal>r.requestBody</literal></link></td></tr> -<tr><td><link id="r_request_buffer"><literal>r.requestBuffer</literal></link></td></tr> -<tr><td><link id="r_request_text"><literal>r.requestText</literal></link></td></tr> -<tr><td><link id="r_raw_headers_in"><literal>r.rawHeadersIn[]</literal></link></td></tr> -<tr><td><link id="r_raw_headers_out"><literal>r.rawHeadersOut[]</literal></link></td></tr> -<tr><td><link id="r_response_body"><literal>r.responseBody</literal></link></td></tr> -<tr><td><link id="r_response_buffer"><literal>r.responseBuffer</literal></link></td></tr> -<tr><td><link id="r_response_text"><literal>r.responseText</literal></link></td></tr> -<tr><td><link id="r_return"><literal>r.return()</literal></link></td></tr> -<tr><td><link id="r_send"><literal>r.send()</literal></link></td></tr> -<tr><td><link id="r_sendbuffer"><literal>r.sendBuffer()</literal></link></td></tr> -<tr><td><link id="r_send_header"><literal>r.sendHeader()</literal></link></td></tr> -<tr><td><link id="r_set_return_value"><literal>r.setReturnValue()</literal></link></td></tr> -<tr><td><link id="r_status"><literal>r.status</literal></link></td></tr> -<tr><td><link id="r_subrequest"><literal>r.subrequest()</literal></link></td></tr> -<tr><td><link id="r_uri"><literal>r.uri</literal></link></td></tr> -<tr><td><link id="r_raw_variables"><literal>r.rawVariables{}</literal></link></td></tr> -<tr><td><link id="r_variables"><literal>r.variables{}</literal></link></td></tr> -<tr><td><link id="r_warn"><literal>r.warn()</literal></link></td></tr> -</table> -</para> - -<para> -The HTTP request object is available only in the -<link doc="../http/ngx_http_js_module.xml">ngx_http_js_module</link> module. -All string properties of the object are -<link id="string">byte strings</link>. - -<list type="tag"> - -<tag-name id="r_args"><literal>r.args{}</literal></tag-name> -<tag-desc> -request arguments object, read-only. -<para> -The query string is returned as an object. -Since <link doc="changes.xml" id="njs0.7.6">0.7.6</link>, -duplicate keys are returned as an array, -keys are case-sensitive, both keys and values are percent-decoded. -</para> - -<para> -For example, the query string -<example> -'a=1&b=%32&A=3&b=4&B=two%20words' -</example> -is converted to <literal>r.args</literal> as: -<example> -{a: "1", b: ["2", "4"], A: "3", B: "two words"} -</example> -More advanced parsing scenarios can be achieved with the -<link id="querystring">Query String</link> module -and with the -<link doc="../http/ngx_http_core_module.xml" id="var_args"><literal>$args</literal></link> -variable, for example: - -<example> -import qs from 'querystring'; - -function args(r) { - return qs.parse(r.variables.args); -} -</example> -The argument object -is evaluated at the first access to <literal>r.args</literal>. -If only a single argument is needed, for example <literal>foo</literal>, -<link doc="../varindex.xml">nginx variables</link> can be used: -<example> -r.variables.arg_foo -</example> -Here, <link id="r_variables">nginx variables object</link> -returns the first value for a given key, -case-insensitive, without percent-decoding. -</para> - -<para> -To convert <literal>r.args</literal> back to a string, -the Query String -<link id="querystring_stringify"><literal>stringify</literal></link> -method can be used. -</para> -</tag-desc> - -<tag-name id="r_done"><literal>r.done()</literal></tag-name> -<tag-desc> -after calling this function, -next data chunks will be passed to client without calling -<link doc="../http/ngx_http_js_module.xml" id="js_body_filter"/> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>). -May be called only from the -<link doc="../http/ngx_http_js_module.xml" id="js_body_filter"/> function -</tag-desc> - -<tag-name id="r_error"><literal>r.error(<value>string</value>)</literal></tag-name> -<tag-desc> -writes a <literal>string</literal> to the error log -on the <literal>error</literal> level of logging -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -<tag-name id="r_finish"><literal>r.finish()</literal></tag-name> -<tag-desc> -finishes sending a response to the client -</tag-desc> - -<tag-name id="r_headers_in"><literal>r.headersIn{}</literal></tag-name> -<tag-desc> -incoming headers object, read-only. -<para> -The <literal>Foo</literal> request header -can be accessed with the syntax: -<literal>headersIn.foo</literal> or <literal>headersIn['Foo']</literal>. -</para> - -<para> -The -<header>Authorization</header>, -<header>Content-Length</header>, -<header>Content-Range</header>, -<header>Content-Type</header>, -<header>ETag</header>, -<header>Expect</header>, -<header>From</header>, -<header>Host</header>, -<header>If-Match</header>, -<header>If-Modified-Since</header>, -<header>If-None-Match</header>, -<header>If-Range</header>, -<header>If-Unmodified-Since</header>, -<header>Max-Forwards</header>, -<header>Proxy-Authorization</header>, -<header>Referer</header>, -<header>Transfer-Encoding</header>, and -<header>User-Agent</header> -request headers can have only one field value -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>). -Duplicate field values in <header>Cookie</header> headers -are separated by semicolon (<literal>;</literal>). -Duplicate field values in all other request headers are separated by commas. -</para> -</tag-desc> - -<tag-name id="r_headers_out"><literal>r.headersOut{}</literal></tag-name> -<tag-desc> -outgoing headers object for the main request, writable. - -<para> -If <literal>r.headersOut{}</literal> is the response object of -a <link id="r_subrequest">subrequest</link>, it represents response headers. -In this case, field values in -<header>Accept-Ranges</header>, -<header>Connection</header>, -<header>Content-Disposition</header>, -<header>Content-Encoding</header>, -<header>Content-Length</header>, -<header>Content-Range</header>, -<header>Date</header>, -<header>Keep-Alive</header>, -<header>Server</header>, -<header>Transfer-Encoding</header>, -<header>X-Accel-*</header> -response headers may be omitted. -</para> - -<para> -The <header>Foo</header> response header -can be accessed with the syntax: -<literal>headersOut.foo</literal> or <literal>headersOut['Foo']</literal>. -</para> - -<para> -Outgoing headers should be set before a response header is sent to a client, -otherwise header update will be ignored. -This means that <literal>r.headersOut{}</literal> is effectively writable in: - -<list type="bullet"> - -<listitem> -the <link doc="../http/ngx_http_js_module.xml" id="js_content"/> handler before -<link id="r_send_header"><literal>r.sendHeader()</literal></link> or -<link id="r_return"><literal>r.return()</literal></link> are called -</listitem> - -<listitem> -the <link doc="../http/ngx_http_js_module.xml" id="js_header_filter"/> handler -</listitem> - -</list> -</para> - -<para> -Field values of multi-value response headers -(<link doc="changes.xml" id="njs0.4.0">0.4.0</link>) -can be set with the syntax: -<example> -r.headersOut['Foo'] = ['a', 'b'] -</example> -where the output will be: -<example> -Foo: a -Foo: b -</example> -All previous field values of the <header>Foo</header> response header -will be deleted. -</para> - -<para> -For standard response headers -that accept only a single field value such as -<header>Content-Type</header>, -only the last element of the array will take effect. -Field values of the <header>Set-Cookie</header> response header -are always returned as an array. -Duplicate field values in -<header>Age</header>, -<header>Content-Encoding</header>, -<header>Content-Length</header>, -<header>Content-Type</header>, -<header>ETag</header>, -<header>Expires</header>, -<header>Last-Modified</header>, -<header>Location</header>, -<header>Retry-After</header> -response headers are ignored. -Duplicate field values in all other response headers -are separated by commas. -</para> -</tag-desc> - -<tag-name id="r_http_version"><literal>r.httpVersion</literal></tag-name> -<tag-desc> -HTTP version, read-only -</tag-desc> - -<tag-name id="r_internal"><literal>r.internal</literal></tag-name> -<tag-desc> -boolean value, true for -<link doc="../http/ngx_http_core_module.xml" id="internal">internal</link> -locations -</tag-desc> - -<tag-name id="r_internal_redirect"><literal>r.internalRedirect(<value>uri</value>)</literal></tag-name> -<tag-desc> -performs an -<link doc="../dev/development_guide.xml" id="http_request_redirection">internal -redirect</link> -to the specified <literal>uri</literal>. -If the uri starts with the “<literal>@</literal>” prefix, -it is considered a named location. -Redirected requests become internal and can access the -<link doc="../http/ngx_http_core_module.xml" id="internal">internal</link> -locations. -The actual redirect happens after the handler execution is completed. -<para> -<note> -After redirect, -a new njs VM is started in the target location, -the VM in the original location is stopped. -Values of <link doc="../varindex.xml">nginx variables</link> are kept -and can be used to pass information to the target location. -Since <link doc="changes.xml" id="njs0.5.3">0.5.3</link>, -the variable declared with the <literal>js_var</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_var">http</link> or -<link doc="../stream/ngx_stream_js_module.xml" id="js_var">stream</link> -can be used. -</note> -</para> - -<para> -<note> -Since <link doc="changes.xml" id="njs0.7.4">0.7.4</link>, -the method accepts escaped URIs. -</note> -</para> - -</tag-desc> - -<tag-name id="r_log"><literal>r.log(<value>string</value>)</literal></tag-name> -<tag-desc> -writes a <literal>string</literal> to the error log -on the <literal>info</literal> level of logging -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -<tag-name id="r_method"><literal>r.method</literal></tag-name> -<tag-desc> -HTTP method, read-only -</tag-desc> - -<tag-name id="r_parent"><literal>r.parent</literal></tag-name> -<tag-desc> -references the parent request object -</tag-desc> - -<tag-name id="r_remote_address"><literal>r.remoteAddress</literal></tag-name> -<tag-desc> -client address, read-only -</tag-desc> - -<tag-name id="r_request_body"><literal>r.requestBody</literal></tag-name> -<tag-desc> -the property was made obsolete in -<link doc="changes.xml" id="njs0.5.0">0.5.0</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -The <link id="r_request_buffer"><literal>r.requestBuffer</literal></link> or -<link id="r_request_text"><literal>r.requestText</literal></link> property -should be used instead. -</tag-desc> - -<tag-name id="r_request_buffer"><literal>r.requestBuffer</literal></tag-name> -<tag-desc> -client request body if it has not been written to a temporary file -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>). -To ensure that the client request body is in memory, -its size should be limited by -<link doc="../http/ngx_http_core_module.xml" id="client_max_body_size"/>, -and a sufficient buffer size should be set using -<link doc="../http/ngx_http_core_module.xml" id="client_body_buffer_size"/>. -The property is available only in the -<link doc="../http/ngx_http_js_module.xml" id="js_content"/> directive. -</tag-desc> - -<tag-name id="r_request_text"><literal>r.requestText</literal></tag-name> -<tag-desc> -the same as <link id="r_request_buffer"><literal>r.requestBuffer</literal></link>, -but returns a <literal>string</literal>. -Note that -it may convert bytes invalid in UTF-8 encoding into the replacement character. -</tag-desc> - -<tag-name id="r_raw_headers_in"><literal>r.rawHeadersIn[]</literal></tag-name> -<tag-desc> -returns an array of key-value pairs -exactly as they were received from the client -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>). -<para> -For example, with the following request headers: -<example> -Host: localhost -Foo: bar -foo: bar2 -</example> -the output of <literal>r.rawHeadersIn</literal> will be: -<example> -[ - ['Host', 'localhost'], - ['Foo', 'bar'], - ['foo', 'bar2'] -] -</example> -All <literal>foo</literal> headers -can be collected with the syntax: -<example> -r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1]) -</example> -the output will be: -<example> -['bar', 'bar2'] -</example> -Header field names are not converted to lower case, -duplicate field values are not merged. -</para> -</tag-desc> - -<tag-name id="r_raw_headers_out"><literal>r.rawHeadersOut[]</literal></tag-name> -<tag-desc> -returns an array of key-value pairs of response headers -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>). -Header field names are not converted to lower case, -duplicate field values are not merged. -</tag-desc> - -<tag-name id="r_response_body"><literal>r.responseBody</literal></tag-name> -<tag-desc> -the property was made obsolete in -<link doc="changes.xml" id="njs0.5.0">0.5.0</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -The <link id="r_response_buffer"><literal>r.responseBuffer</literal></link> -or -the <link id="r_response_text"><literal>r.responseText</literal></link> -property -should be used instead. -</tag-desc> - -<tag-name id="r_response_buffer"><literal>r.responseBuffer</literal></tag-name> -<tag-desc> -holds the <link id="r_subrequest">subrequest</link> response body, -read-only -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>). -The size of <literal>r.responseBuffer</literal> is limited by the -<link doc="../http/ngx_http_core_module.xml" id="subrequest_output_buffer_size"/> -directive. -</tag-desc> - -<tag-name id="r_response_text"><literal>r.responseText</literal></tag-name> -<tag-desc> -the same as <link id="r_response_buffer"><literal>r.responseBuffer</literal></link> -but returns a string -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>). -Note that -it may convert bytes invalid in UTF-8 encoding into the replacement character. -</tag-desc> - -<tag-name id="r_return"><literal>r.return(status[, -string | Buffer])</literal></tag-name> -<tag-desc> -sends the entire response -with the specified <literal>status</literal> to the client. -The response can be a string or Buffer -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>). -<para> -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 -</para> -</tag-desc> - -<tag-name id="r_send"><literal>r.send(string -| Buffer)</literal></tag-name> -<tag-desc> -sends a part of the response body to the client. -The data sent can be a string or Buffer -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>) -</tag-desc> - -<tag-name id="r_sendbuffer"><literal>r.sendBuffer(<value>data</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -adds data to the chain of data chunks to be forwarded to the next body filter -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>). -The actual forwarding happens later, -when the all the data chunks of the current chain are processed. -<para> -The data can be a string or Buffer. -The <literal>options</literal> 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: -<list type="tag"> - -<tag-name><literal>last</literal></tag-name> -<tag-desc> -boolean, -true if the buffer is the last buffer -</tag-desc> - -<tag-name><literal>flush</literal></tag-name> -<tag-desc> -boolean, -true if the buffer should have the <literal>flush</literal> flag -</tag-desc> -</list> -</para> -The method may be called only from the -<link doc="../http/ngx_http_js_module.xml" id="js_body_filter"/> function. -</tag-desc> - -<tag-name id="r_send_header"><literal>r.sendHeader()</literal></tag-name> -<tag-desc> -sends the HTTP headers to the client -</tag-desc> - -<tag-name id="r_set_return_value"><literal>r.setReturnValue(<value>value</value>)</literal></tag-name> -<tag-desc> -sets the return value of the -<link doc="../http/ngx_http_js_module.xml" id="js_set"/> handler -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>). -Unlike an ordinary return statement, -this method should be used when the handler is JS async function. -For example: -<example> -async function js_set(r) { - const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host); - r.setReturnValue(digest); -} -</example> -</tag-desc> - -<tag-name id="r_status"><literal>r.status</literal></tag-name> -<tag-desc> -status, writable -</tag-desc> - -<tag-name id="r_subrequest"><literal>r.subrequest(<value>uri</value>[, -<value>options</value>[, <value>callback</value>]])</literal></tag-name> -<tag-desc> -creates a subrequest with the given <literal>uri</literal> and -<literal>options</literal>, and installs -an optional completion <literal>callback</literal>. - -<para> -A -<link doc="../dev/development_guide.xml.xml" id="http_subrequests">subrequest</link> -shares its input headers with the client request. -To send headers different from original headers to a proxied server, the -<link doc="../http/ngx_http_proxy_module.xml" id="proxy_set_header"/> -directive can be used. -To send a completely new set of headers to a proxied server, the -<link doc="../http/ngx_http_proxy_module.xml" id="proxy_pass_request_headers"/> -directive can be used. -</para> - -<para> -If <literal>options</literal> is a string, then it -holds the subrequest arguments string. -Otherwise, <literal>options</literal> is expected to be -an object with the following keys: -<list type="tag"> -<tag-name><literal>args</literal></tag-name> -<tag-desc> -arguments string, by default an empty string is used -</tag-desc> -<tag-name><literal>body</literal></tag-name> -<tag-desc> -request body, -by default the request body of the parent request object is used -</tag-desc> - -<tag-name><literal>method</literal></tag-name> -<tag-desc> -HTTP method, by default the <literal>GET</literal> method is used -</tag-desc> - -<tag-name><literal>detached</literal></tag-name> -<tag-desc> -boolean flag (<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -if <literal>true</literal>, 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 <literal>detached</literal> flag and callback argument -are mutually exclusive. -</tag-desc> - -</list> -</para> - -<para> -The completion <literal>callback</literal> receives -a <link id="http">subrequest response object</link> with methods and properties -identical to the parent request object. -</para> - -<para> -Since <link doc="changes.xml" id="njs0.3.8">0.3.8</link>, -if a <literal>callback</literal> is not provided, -the <literal>Promise</literal> object -that resolves to the <link id="http">subrequest response object</link> -is returned. -</para> - -<para> -For example, to view all response headers in the subrequest: -<example> -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); -} -</example> -</para> - -</tag-desc> - -<tag-name id="r_uri"><literal>r.uri</literal></tag-name> -<tag-desc> -current <link doc="../http/ngx_http_core_module.xml" id="var_uri">URI</link> -in request, -<link doc="../http/ngx_http_core_module.xml" id="location">normalized</link>, -read-only -</tag-desc> - -<tag-name id="r_raw_variables"><literal>r.rawVariables{}</literal></tag-name> -<tag-desc> -nginx <link id="r_variables">variables</link> as Buffers, -writable -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>) -</tag-desc> - -<tag-name id="r_variables"><literal>r.variables{}</literal></tag-name> -<tag-desc> -<link doc="../varindex.xml">nginx variables</link> object, writable -(since <link doc="changes.xml" id="njs0.2.8">0.2.8</link>). - -<para> -For example, to get the <literal>$foo</literal> variable, -one of the following syntax can be used: -<example> -r.variables['foo'] -r.variables.foo -</example> -nginx treats variables referenced in <literal>nginx.conf</literal> -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 -<link doc="../http/ngx_http_core_module.xml" id="var_request_id">$request_id</link> -variable is only accessed from njs, -it has a new value every time it is evaluated. -But, when the -<link doc="../http/ngx_http_core_module.xml" id="var_request_id">$request_id</link> -is referenced, for example: -<example> -proxy_set_header X-Request-Id $request_id; -</example> -the <literal>r.variables.request_id</literal> returns the same value every time. -</para> - -<para> -A variable is writable if: -<list type="bullet"> - -<listitem> -it was created using the <literal>js_var</literal> directive for -<link doc="../http/ngx_http_js_module.xml" id="js_var">http</link> or -<link doc="../stream/ngx_stream_js_module.xml" id="js_var">stream</link> -(since <link doc="changes.xml" id="njs0.5.3">0.5.3</link>) -</listitem> - -<listitem> -it is referenced in nginx configuration file -</listitem> - -</list> -Even so, some embedded variables still cannot be assigned a value (for example, -<link doc="../http/ngx_http_core_module.xml" id="var_http_"><literal>$http_</literal></link>). -</para> -</tag-desc> - -<tag-name id="r_warn"><literal>r.warn(<value>string</value>)</literal></tag-name> -<tag-desc> -writes a <literal>string</literal> to the error log -on the <literal>warning</literal> level of logging -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="stream" name="Stream Session"> - -<para> -<table width="100%"> -<tr><td><link id="s_allow"><literal>s.allow()</literal></link></td></tr> -<tr><td><link id="s_decline"><literal>s.decline()</literal></link></td></tr> -<tr><td><link id="s_deny"><literal>s.deny()</literal></link></td></tr> -<tr><td><link id="s_done"><literal>s.done()</literal></link></td></tr> -<tr><td><link id="s_error"><literal>s.error()</literal></link></td></tr> -<tr><td><link id="s_log"><literal>s.log()</literal></link></td></tr> -<tr><td><link id="s_off"><literal>s.off()</literal></link></td></tr> -<tr><td><link id="s_on"><literal>s.on()</literal></link></td></tr> -<tr><td><link id="s_remote_address"><literal>s.remoteAddress</literal></link></td></tr> -<tr><td><link id="s_raw_variables"><literal>s.rawVariables{}</literal></link></td></tr> -<tr><td><link id="s_send"><literal>s.send()</literal></link></td></tr> -<tr><td><link id="s_send_downstream"><literal>s.sendDownstream()</literal></link></td></tr> -<tr><td><link id="s_send_upstream"><literal>s.sendUpstream()</literal></link></td></tr> -<tr><td><link id="s_status"><literal>s.status</literal></link></td></tr> -<tr><td><link id="s_set_return_value"><literal>s.setReturnValue()</literal></link></td></tr> -<tr><td><link id="s_variables"><literal>s.variables{}</literal></link></td></tr> -<tr><td><link id="s_warn"><literal>s.warn()</literal></link></td></tr> -</table> -</para> - -<para> -The stream session object is available only in the -<link doc="../stream/ngx_stream_js_module.xml">ngx_stream_js_module</link> -module. -All string properties of the object are <link id="string">byte strings</link>. -</para> - -<para> -<list type="tag"> - -<tag-name id="s_allow"><literal>s.allow()</literal></tag-name> -<tag-desc> -an alias to -<link id="s_done"><literal>s.done(0)</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_decline"><literal>s.decline()</literal></tag-name> -<tag-desc> -an alias to -<link id="s_done"><literal>s.done(-5)</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_deny"><literal>s.deny()</literal></tag-name> -<tag-desc> -an alias to -<link id="s_done"><literal>s.done(403)</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_done"><literal>s.done([<value>code</value>]</literal>)</tag-name> -<tag-desc> -sets an exit <literal>code</literal> for the current -<link doc="../stream/stream_processing.xml">phase</link> handler -to a code value, by default <literal>0</literal>. -The actual finalization happens when the js handler is completed -and all pending events, for example, from -<link id="ngx_fetch"><literal>ngx.fetch()</literal></link> or -<link id="settimeout"><literal>setTimeout()</literal></link>, -are processed -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>). -<para> -Possible code values: -<list type="bullet"> - -<listitem> -<literal>0</literal>— -successful finalization, passing control to the next phase -</listitem> - -<listitem> -<literal>-5</literal>— -undecided, passing control to the next handler of the current phase (if any) -</listitem> - -<listitem> -<literal>403</literal>— -access is forbidden -</listitem> - -</list> -</para> -May be called only from a phase handler function: -<link doc="../stream/ngx_stream_js_module.xml" id="js_access"><literal>js_access</literal></link> -or -<link doc="../stream/ngx_stream_js_module.xml" id="js_preread"><literal>js_preread</literal></link>. -</tag-desc> - -<tag-name id="s_error"><literal>s.error(<value>string</value>)</literal></tag-name> -<tag-desc> -writes a sent <literal>string</literal> to the error log -on the <literal>error</literal> level of logging -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -<tag-name id="s_log"><literal>s.log(<value>string</value>)</literal></tag-name> -<tag-desc> -writes a sent <value>string</value> to the error log -on the <literal>info</literal> level of logging -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -<tag-name id="s_off"><literal>s.off(<value>eventName</value>)</literal></tag-name> -<tag-desc> -unregisters the callback set by the <link id="s_on">s.on()</link> method -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_on"><literal>s.on(<value>event</value>, -<value>callback</value>)</literal></tag-name> -<tag-desc> -registers a <literal>callback</literal> -for the specified <literal>event</literal> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>). - -<para> -An <literal>event</literal> may be one of the following strings: -<list type="tag"> -<tag-name><literal>upload</literal></tag-name> -<tag-desc> -new data (string) from a client -</tag-desc> - -<tag-name><literal>download</literal></tag-name> -<tag-desc> -new data (string) to a client -</tag-desc> - -<tag-name><literal>upstream</literal></tag-name> -<tag-desc> -new data (Buffer) from a client -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>) -</tag-desc> - -<tag-name><literal>downstream</literal></tag-name> -<tag-desc> -new data (Buffer) to a client -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>) -</tag-desc> - -</list> -</para> - -<para> -The completion callback has the following prototype: -<literal>callback(data, flags)</literal>, where -<literal>data</literal> is string or Buffer (depending on the event type) -<literal>flags</literal> is an object -with the following properties: -<list type="tag"> -<tag-name id="s_on_callback_last"><literal>last</literal></tag-name> -<tag-desc> -a boolean value, true if data is a last buffer. -</tag-desc> - -</list> -</para> -</tag-desc> - -<tag-name id="s_remote_address"><literal>s.remoteAddress</literal></tag-name> -<tag-desc> -client address, read-only -</tag-desc> - -<tag-name id="s_raw_variables"><literal>s.rawVariables</literal></tag-name> -<tag-desc> -nginx <link id="s_variables">variables</link> as Buffers, -writable -(since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>) -</tag-desc> - -<tag-name id="s_send"><literal>s.send(<value>data</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -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 -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>). -The actual forwarding happens later, -when the all the data chunks of the current chain are processed. -<para> -The data can be a string or Buffer -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>). -The <literal>options</literal> 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: -<list type="tag"> - -<tag-name><literal>last</literal></tag-name> -<tag-desc> -boolean, -true if the buffer is the last buffer -</tag-desc> - -<tag-name><literal>flush</literal></tag-name> -<tag-desc> -boolean, -true if the buffer should have the <literal>flush</literal> flag -</tag-desc> -</list> -</para> -The method can be called multiple times per callback invocation. -</tag-desc> - -<tag-name id="s_send_downstream"><literal>s.sendDownstream()</literal></tag-name> -<tag-desc> -is identical to <link id="s_send">s.send()</link>, -except for it always sends data to a client -(since <link doc="changes.xml" id="njs0.7.8">0.7.8</link>). -</tag-desc> - -<tag-name id="s_send_upstream"><literal>s.sendUpstream()</literal></tag-name> -<tag-desc> -is identical to <link id="s_send">s.send()</link>, -except for it always sends data from a client -(since <link doc="changes.xml" id="njs0.7.8">0.7.8</link>). -</tag-desc> - -<tag-name id="s_status"><literal>s.status</literal></tag-name> -<tag-desc> -session status code, an alias to the -<link doc="../stream/ngx_stream_core_module.xml" id="var_status"><literal>$status</literal></link> -variable, -read only -(since <link doc="changes.xml" id="njs0.5.2">0.5.2</link>) -</tag-desc> - -<tag-name id="s_set_return_value"><literal>s.setReturnValue(<value>value</value>)</literal></tag-name> -<tag-desc> -sets the return value of the -<link doc="../stream/ngx_stream_js_module.xml" id="js_set"/> handler -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>). -Unlike an ordinary return statement, -this method should be used when the handler is JS async function. -For example: -<example> -async function js_set(r) { - const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host); - r.setReturnValue(digest); -} -</example> -</tag-desc> - -<tag-name id="s_variables"><literal>s.variables{}</literal></tag-name> -<tag-desc> -<link doc="../varindex.xml">nginx variables</link> object, writable -(since <link doc="changes.xml" id="njs0.2.8">0.2.8</link>). -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. -</tag-desc> - -<tag-name id="s_warn"><literal>s.warn(<value>string</value>)</literal></tag-name> -<tag-desc> -writes a sent <literal>string</literal> to the error log -on the <literal>warning</literal> level of logging -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="periodic_session" name="Periodic Session"> - -<para> -<table width="100%"> -<tr><td><link id="periodic_session_raw_variables"><literal>PeriodicSession.rawVariables{}</literal></link></td></tr> -<tr><td><link id="periodic_session_variables"><literal>PeriodicSession.variables{}</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>Periodic Session</literal> object is provided as the first argument -for the <literal>js_periodic</literal> handler for -<link doc="../http/ngx_http_js_module.xml" id="js_periodic">http</link> -and -<link doc="../stream/ngx_stream_js_module.xml" id="js_periodic">stream</link> -(since <link doc="changes.xml" id="njs0.8.1">0.8.1</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="periodic_session_raw_variables"><literal>PeriodicSession.rawVariables{}</literal></tag-name> -<tag-desc> -nginx <link id="periodic_session_variables">variables</link> as Buffers, -writable. -</tag-desc> - -<tag-name id="periodic_session_variables"><literal>PeriodicSession.variables{}</literal></tag-name> -<tag-desc> -<link doc="../varindex.xml">nginx variables</link> object, writable. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="headers" name="Headers"> - -<para> -<table width="100%"> -<tr><td><link id="headers_constructor"><literal>Headers()</literal></link></td></tr> -<tr><td><link id="headers_append"><literal>Headers.append()</literal></link></td></tr> -<tr><td><link id="headers_delete"><literal>Headers.delete()</literal></link></td></tr> -<tr><td><link id="headers_get"><literal>Headers.get()</literal></link></td></tr> -<tr><td><link id="headers_getall"><literal>Headers.getAll()</literal></link></td></tr> -<tr><td><link id="headers_foreach"><literal>Headers.forEach()</literal></link></td></tr> -<tr><td><link id="headers_has"><literal>Headers.has()</literal></link></td></tr> -<tr><td><link id="headers_set"><literal>Headers.set()</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>Headers</literal> interface of the -<link id="ngx_fetch"><literal>Fetch API</literal></link> -is available since <link doc="changes.xml" id="njs0.5.1">0.5.1</link>. -</para> - -<para> -A new <literal>Headers</literal> object can be created using the -<link id="headers_constructor"><literal>Headers()</literal></link> constructor: -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>): - -<list type="tag"> - -<tag-name id="headers_constructor"><literal>Headers([<value>init</value>])</literal></tag-name> -<tag-desc> - -<list type="tag"> - -<tag-name><literal>init</literal></tag-name> -<tag-desc> -An object containing HTTP headers for -prepopulating the <literal>Headers</literal> object, -can be a <literal>string</literal>, -an <literal>array</literal> of name-value pairs, -or an existing <literal>Headers</literal> object. -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -<para> -A new <literal>Headers</literal> object can be created -with the following properties and methods: - -<list type="tag"> - -<tag-name id="headers_append"><literal>append()</literal></tag-name> -<tag-desc> -Appends a new value into an existing header in the -<literal>Headers</literal> object, -or adds the header if it does not already exist -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -</tag-desc> - -<tag-name id="headers_delete"><literal>delete()</literal></tag-name> -<tag-desc> -Deletes a header from the <literal>Headers</literal> object -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -</tag-desc> - -<tag-name id="headers_get"><literal>get()</literal></tag-name> -<tag-desc> -Returns a string containing the values of all headers with the specified name -separated by a comma and a space. -</tag-desc> - -<tag-name id="headers_getall"><literal>getAll(<value>name</value>)</literal></tag-name> -<tag-desc> -Returns an array containing the values of all headers with the specified name. -</tag-desc> - -<tag-name id="headers_foreach"><literal>forEach()</literal></tag-name> -<tag-desc> -Executes a provided function once for each key/value pair -in the <literal>Headers</literal> object -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -</tag-desc> - -<tag-name id="headers_has"><literal>has()</literal></tag-name> -<tag-desc> -Returns a boolean value -indicating whether a header with the specified name exists. -</tag-desc> - -<tag-name id="headers_set"><literal>set()</literal></tag-name> -<tag-desc> -Sets a new value for an existing header inside -the <literal>Headers</literal> object, -or adds the header if it does not already exist -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -</tag-desc> - -</list> -</para> - -</section> - - -<section id="request" name="Request"> - -<para> -<table width="100%"> -<tr><td><link id="request_constructor"><literal>Request()</literal></link></td></tr> -<tr><td><link id="request_arraybuffer"><literal>Request.arrayBuffer()</literal></link></td></tr> -<tr><td><link id="request_bodyused"><literal>Request.bodyUsed</literal></link></td></tr> -<tr><td><link id="request_cache"><literal>Request.cache</literal></link></td></tr> -<tr><td><link id="request_credentials"><literal>Request.credentials</literal></link></td></tr> -<tr><td><link id="request_headers"><literal>Request.headers</literal></link></td></tr> -<tr><td><link id="request_json"><literal>Request.json()</literal></link></td></tr> -<tr><td><link id="request_method"><literal>Request.method</literal></link></td></tr> -<tr><td><link id="request_mode"><literal>Request.mode</literal></link></td></tr> -<tr><td><link id="request_text"><literal>Request.text()</literal></link></td></tr> -<tr><td><link id="request_url"><literal>Request.url</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>Request</literal> interface of the -<link id="ngx_fetch"><literal>Fetch API</literal></link> -is available since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>. -</para> - -<para> -A new <literal>Request</literal> object can be created using the -<link id="request_constructor"><literal>Request()</literal></link> constructor: - -<list type="tag"> - -<tag-name id="request_constructor"><literal>Request[<value>resource</value>[, -<value>options</value>]])</literal></tag-name> -<tag-desc> - -Creates a <literal>Request</literal> object to fetch -that can be passed later to -<link id="ngx_fetch"><literal>ngx.fetch()</literal></link>. -The <literal>resource</literal> can be a URL -or an existing <literal>Request</literal> object. -The <literal>options</literal> is an optional argument -that is expected to be an object with the following keys: - -<list type="tag"> - -<tag-name><literal>body</literal></tag-name> -<tag-desc> -The request body, by default is empty. -</tag-desc> - -<tag-name><literal>headers</literal></tag-name> -<tag-desc> -The response headers object— -the object containing HTTP headers for -prepopulating the <link id="headers"><literal>Headers</literal></link> object, -can be a <literal>string</literal>, -an <literal>array</literal> of name-value pairs, -or an existing <link id="headers"><literal>Headers</literal></link> object. -</tag-desc> - -<tag-name><literal>method</literal></tag-name> -<tag-desc> -The HTTP method, by default the GET method is used. -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -<para> -A new <literal>Request</literal> object can be created -with the following properties and methods: - -<list type="tag"> - -<tag-name id="request_arraybuffer"><literal>arrayBuffer()</literal></tag-name> -<tag-desc> -Returns a <literal>Promise</literal> that resolves with -an <literal>ArrayBuffer</literal>. -</tag-desc> - -<tag-name id="request_bodyused"><literal>bodyUsed</literal></tag-name> -<tag-desc> -A boolean value, <literal>true</literal> -if the body was used in the request. -</tag-desc> - -<tag-name id="request_cache"><literal>cache</literal></tag-name> -<tag-desc> -Contains the cache mode of the request. -</tag-desc> - -<tag-name id="request_credentials"><literal>credentials</literal></tag-name> -<tag-desc> -Contains the credentials of the request, -by default is <literal>same-origin</literal>. -</tag-desc> - -<tag-name id="request_headers"><literal>headers</literal></tag-name> -<tag-desc> -The <link id="headers"><literal>Headers</literal></link> read-only object -associated with the -<link id="request"><literal>Request</literal></link>. -</tag-desc> - -<tag-name id="request_json"><literal>json()</literal></tag-name> -<tag-desc> -Returns a <literal>Promise</literal> that resolves with -the result of parsing the request body as JSON. -</tag-desc> - -<tag-name id="request_method"><literal>method</literal></tag-name> -<tag-desc> -Contains the request method. -</tag-desc> - -<tag-name id="request_mode"><literal>mode</literal></tag-name> -<tag-desc> -Contains the mode of the request. -</tag-desc> - -<tag-name id="request_text"><literal>text()</literal></tag-name> -<tag-desc> -Returns a <literal>Promise</literal> that resolves with a -string representation of the request body. -</tag-desc> - -<tag-name id="request_url"><literal>url</literal></tag-name> -<tag-desc> -Contains the URL of the request. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="response" name="Response"> - -<para> -<table width="100%"> -<tr><td><link id="response_constructor"><literal>Response()</literal></link></td></tr> -<tr><td><link id="response_arraybuffer"><literal>Response.arrayBuffer()</literal></link></td></tr> -<tr><td><link id="response_bodyused"><literal>Response.bodyUsed</literal></link></td></tr> -<tr><td><link id="response_headers"><literal>Response.headers</literal></link></td></tr> -<tr><td><link id="response_json"><literal>Response.json()</literal></link></td></tr> -<tr><td><link id="response_ok"><literal>Response.ok</literal></link></td></tr> -<tr><td><link id="response_redirect"><literal>Response.redirected</literal></link></td></tr> -<tr><td><link id="response_status"><literal>Response.status</literal></link></td></tr> -<tr><td><link id="response_statustext"><literal>Response.statusText</literal></link></td></tr> -<tr><td><link id="response_text"><literal>Response.text()</literal></link></td></tr> -<tr><td><link id="response_type"><literal>Response.type</literal></link></td></tr> -<tr><td><link id="response_url"><literal>Response.url</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>Response</literal> interface is available since -<link doc="changes.xml" id="njs0.5.1">0.5.1</link>. -</para> - -<para> -A new <literal>Response</literal> object can be created using the -<link id="response_constructor"><literal>Response()</literal></link> constructor -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>): - -<list type="tag"> - -<tag-name id="response_constructor"><literal>Response[<value>body</value>[, -<value>options</value>]])</literal></tag-name> -<tag-desc> -Creates a <literal>Response</literal> object. -The <literal>body</literal> is an optional argument, -can be a <literal>string</literal> or a <literal>buffer</literal>, -by default is <literal>null</literal>. -The <literal>options</literal> is an optional argument -that is expected to be an object with the following keys: - -<list type="tag"> - -<tag-name><literal>headers</literal></tag-name> -<tag-desc> -The response headers object— -the object containing HTTP headers for -prepopulating the <link id="headers"><literal>Headers</literal></link> object, -can be a <literal>string</literal>, -an <literal>array</literal> of name-value pairs, -or an existing <link id="headers"><literal>Headers</literal></link> object. -</tag-desc> - -<tag-name><literal>status</literal></tag-name> -<tag-desc> -The status code of the response. -</tag-desc> - -<tag-name><literal>statusText</literal></tag-name> -<tag-desc> -The status message corresponding to the status code. -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -<para> -A new <literal>Response()</literal> object can be created -with the following properties and methods: - -<list type="tag"> - -<tag-name id="response_arraybuffer"><literal>arrayBuffer()</literal></tag-name> -<tag-desc> -Takes a <literal>Response</literal> stream and reads it to completion. -Returns a <literal>Promise</literal> that resolves with -an <literal>ArrayBuffer</literal>. -</tag-desc> - -<tag-name id="response_bodyused"><literal>bodyUsed</literal></tag-name> -<tag-desc> -A boolean value, <literal>true</literal> -if the body was read. -</tag-desc> - -<tag-name id="response_headers"><literal>headers</literal></tag-name> -<tag-desc> -The <link id="headers"><literal>Headers</literal></link> read-only object -associated with the -<link id="response"><literal>Response</literal></link>. -</tag-desc> - -<tag-name id="response_json"><literal>json()</literal></tag-name> -<tag-desc> -Takes a <literal>Response</literal> stream and reads it to completion. -Returns a <literal>Promise</literal> that resolves with -the result of parsing the body text as JSON. -</tag-desc> - -<tag-name id="response_ok"><literal>ok</literal></tag-name> -<tag-desc> -A boolean value, <literal>true</literal> -if the response was successful (status codes between 200–299). -</tag-desc> - -<tag-name id="response_redirect"><literal>redirected</literal></tag-name> -<tag-desc> -A boolean value, <literal>true</literal> -if the response is the result of a redirect. -</tag-desc> - -<tag-name id="response_status"><literal>status</literal></tag-name> -<tag-desc> -The status code of the response. -</tag-desc> - -<tag-name id="response_statustext"><literal>statusText</literal></tag-name> -<tag-desc> -The status message corresponding to the status code. -</tag-desc> - -<tag-name id="response_text"><literal>text()</literal></tag-name> -<tag-desc> -Takes a <literal>Response</literal> stream and reads it to completion. -Returns a <literal>Promise</literal> that resolves with a string. -</tag-desc> - -<tag-name id="response_type"><literal>type</literal></tag-name> -<tag-desc> -The type of the response. -</tag-desc> - -<tag-name id="response_url"><literal>url</literal></tag-name> -<tag-desc> -The URL of the response. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="ngx" name="ngx"> - -<para> -<table width="100%"> -<tr><td><link id="ngx_build"><literal>ngx.build</literal></link></td></tr> -<tr><td><link id="ngx_conf_file_path"><literal>ngx.conf_file_path</literal></link></td></tr> -<tr><td><link id="ngx_conf_prefix"><literal>ngx.conf_prefix</literal></link></td></tr> -<tr><td><link id="ngx_error_log_path"><literal>ngx.error_log_path</literal></link></td></tr> -<tr><td><link id="ngx_fetch"><literal>ngx.fetch()</literal></link></td></tr> -<tr><td><link id="ngx_log"><literal>ngx.log()</literal></link></td></tr> -<tr><td><link id="ngx_prefix"><literal>ngx.prefix</literal></link></td></tr> -<tr><td><link id="ngx_version"><literal>ngx.version</literal></link></td></tr> -<tr><td><link id="ngx_version_number"><literal>ngx.version_number</literal></link></td></tr> -<tr><td><link id="ngx_worker_id"><literal>ngx.worker_id</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>ngx</literal> global object is available -since <link doc="changes.xml" id="njs0.5.0">0.5.0</link>. -<list type="tag"> - -<tag-name id="ngx_build"><literal>ngx.build</literal></tag-name> -<tag-desc> -a string containing an optional nginx build name, corresponds to the -<link doc="../configure.xml" id="build"><literal>--build=name</literal></link> -argument -of the <link doc="../configure.xml">configure</link> script, -by default is <literal>""</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -<tag-name id="ngx_conf_file_path"><literal>ngx.conf_file_path</literal></tag-name> -<tag-desc> -a string containing the file path to current nginx configuration file -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -<tag-name id="ngx_conf_prefix"><literal>ngx.conf_prefix</literal></tag-name> -<tag-desc> -a string containing the file path to -<link doc="../configure.xml" id="conf_path">nginx configuration prefix</link>— -the directory where nginx is currently looking for configuration -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>) -</tag-desc> - -<tag-name id="ngx_error_log_path"><literal>ngx.error_log_path</literal></tag-name> -<tag-desc> -a string containing the file path to the current -<link doc="../ngx_core_module.xml" id="error_log">error log</link> file -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -<tag-name id="ngx_fetch"><literal>ngx.fetch(<value>resource</value>, -[<value>options</value>])</literal></tag-name> -<tag-desc> -<para> -Makes a request to fetch a <value>resource</value> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>), which can be an -URL or the <link id="request"><literal>Request</literal></link> object -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -Returns a <literal>Promise</literal> that resolves with -the <link id="response"><literal>Response</literal></link> object. -Since <link doc="changes.xml" id="njs0.7.0">0.7.0</link>, -the <literal>https://</literal> scheme is supported, -redirects are not handled. -</para> - -<para> -If the URL in the <value>resource</value> is specified as a domain name, -it is determined using a -<link doc="../http/ngx_http_core_module.xml" id="resolver"/>. -If the <literal>https://</literal> scheme is specified, the -<link doc="../http/ngx_http_js_module.xml" id="js_fetch_trusted_certificate"/> -directive should be configured -for the authentication of the <value>resource</value>'s HTTPS server. -</para> - -<para> -The <literal>options</literal> parameter is expected to be an object -with the following keys: -<list type="tag"> - -<tag-name id="fetch_body"><literal>body</literal></tag-name> -<tag-desc> -request body, -by default is empty -</tag-desc> - -<tag-name id="fetch_buffer_size"><literal>buffer_size</literal></tag-name> -<tag-desc> -the buffer size for reading the response, -by default is <literal>4096</literal> -</tag-desc> - -<tag-name id="fetch_headers"><literal>headers</literal></tag-name> -<tag-desc> -request <link id="headers">headers</link> object -</tag-desc> - -<tag-name id="fetch_get"><literal>max_response_body_size</literal></tag-name> -<tag-desc> -the maximum size of the response body in bytes, -by default is <literal>32768</literal> -</tag-desc> - -<tag-name id="fetch_method"><literal>method</literal></tag-name> -<tag-desc> -HTTP method, -by default the <literal>GET</literal> method is used -</tag-desc> - -<tag-name id="fetch_verify"><literal>verify</literal></tag-name> -<tag-desc> -enables or disables verification of the HTTPS server certificate, -by default is <literal>true</literal> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>) -</tag-desc> - -</list> -Example: -<example> -let reply = await ngx.fetch('http://nginx.org/'); -let body = await reply.text(); - -r.return(200, body); -</example> -</para> -</tag-desc> - -<tag-name id="ngx_log"><literal>ngx.log</literal>(<value>level</value>, -<value>message</value>)</tag-name> -<tag-desc> -writes a message to the error log with the specified level of logging. -The <value>level</value> parameter specifies one of the log levels, -the <value>message</value> parameter can be a string or Buffer. -The following log levels can be specified: -<literal>ngx.INFO</literal>, -<literal>ngx.WARN</literal>, and -<literal>ngx.ERR</literal>. -<para> -<note> -As nginx has a -<link doc="../dev/development_guide.xml" id="logging">hardcoded</link> -maximum line length limit, -only first 2048 bytes of the string can be logged. -</note> -</para> -</tag-desc> - -<tag-name id="ngx_prefix"><literal>ngx.prefix</literal></tag-name> -<tag-desc> -a string containing the file path to -<link doc="../configure.xml" id="prefix">nginx prefix</link>— -a directory that keeps server files -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -<tag-name id="ngx_version"><literal>ngx.version</literal></tag-name> -<tag-desc> -a string containing nginx version, -for example: <literal>1.25.0</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -<tag-name id="ngx_version_number"><literal>ngx.version_number</literal></tag-name> -<tag-desc> -a number containing nginx version, -for example: <literal>1025000</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -<tag-name id="ngx_worker_id"><literal>ngx.worker_id</literal></tag-name> -<tag-desc> -a number that corresponds to nginx internal worker id, -the value is between <literal>0</literal> and the value specified in the -<link doc="../ngx_core_module.xml" id="worker_processes"/> directive -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</tag-desc> - -</list> -</para> - -</section> - -<section id="ngx_shared" name="ngx.shared"> - -<para> -The <literal>ngx.shared</literal> global object is available -since <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -</para> - - -<section id="dict" name="SharedDict"> -<para> -<table width="100%"> -<tr><td><link id="dict_add"><literal>ngx.shared.SharedDict.add()</literal></link></td></tr> -<tr><td><link id="dict_capacity"><literal>ngx.shared.SharedDict.capacity</literal></link></td></tr> -<tr><td><link id="dict_clear"><literal>ngx.shared.SharedDict.clear()</literal></link></td></tr> -<tr><td><link id="dict_delete"><literal>ngx.shared.SharedDict.delete()</literal></link></td></tr> -<tr><td><link id="dict_freespace"><literal>ngx.shared.SharedDict.freeSpace()</literal></link></td></tr> -<tr><td><link id="dict_get"><literal>ngx.shared.SharedDict.get()</literal></link></td></tr> -<tr><td><link id="dict_has"><literal>ngx.shared.SharedDict.has()</literal></link></td></tr> -<tr><td><link id="dict_incr"><literal>ngx.shared.SharedDict.incr()</literal></link></td></tr> -<tr><td><link id="dict_items"><literal>ngx.shared.SharedDict.items()</literal></link></td></tr> -<tr><td><link id="dict_keys"><literal>ngx.shared.SharedDict.keys()</literal></link></td></tr> -<tr><td><link id="dict_name"><literal>ngx.shared.SharedDict.name</literal></link></td></tr> -<tr><td><link id="dict_pop"><literal>ngx.shared.SharedDict.pop()</literal></link></td></tr> -<tr><td><link id="dict_replace"><literal>ngx.shared.SharedDict.replace()</literal></link></td></tr> -<tr><td><link id="dict_set"><literal>ngx.shared.SharedDict.set()</literal></link></td></tr> -<tr><td><link id="dict_size"><literal>ngx.shared.SharedDict.size()</literal></link></td></tr> -<tr><td><link id="dict_type"><literal>ngx.shared.SharedDict.type</literal></link></td></tr> -</table> -</para> - -<para> -The shared dictionary object is available -since <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -The shared dictionary name, type, and size -are set with the <literal>js_shared_dict_zone</literal> directive in -<link doc="../http/ngx_http_js_module.xml" id="js_shared_dict_zone">http</link> -or -<link doc="../stream/ngx_stream_js_module.xml" id="js_shared_dict_zone">stream</link>. -</para> - -<para> -A <literal>SharedDict()</literal> object -has the following properties and methods: -<list type="tag"> - -<tag-name id="dict_add"><literal>ngx.shared.SharedDict.add(<value>key</value>, -<value>value</value>)</literal></tag-name> -<tag-desc> -Sets the <literal>value</literal> -for the specified <literal>key</literal> in the dictionary -only if the key does not exist yet. -The <literal>key</literal> is a string representing -the key of the item to add, -the <literal>value</literal> is the value of the item to add. -Returns <literal>true</literal> if the value has been successfully added -to the <literal>SharedDict</literal> dictionary, -<literal>false</literal> if the key already exists in the dictionary. -Throws <literal>SharedMemoryError</literal> if -there is not enough free space in the <literal>SharedDict</literal> dictionary. -Throws <literal>TypeError</literal> if the <literal>value</literal> is -of a different type than expected by this dictionary. -</tag-desc> - -<tag-name id="dict_capacity"><literal>ngx.shared.SharedDict.capacity</literal></tag-name> -<tag-desc> -Returns the capacity of the <literal>SharedDict</literal> dictionary, -corresponds to the <literal>size</literal> parameter of -<literal>js_shared_dict_zone</literal> directive in -<link doc="../http/ngx_http_js_module.xml" id="js_shared_dict_zone">http</link> -or -<link doc="../stream/ngx_stream_js_module.xml" id="js_shared_dict_zone">stream</link>. -</tag-desc> - -<tag-name id="dict_clear"><literal>ngx.shared.SharedDict.clear()</literal></tag-name> -<tag-desc> -Removes all items from the <literal>SharedDict</literal> dictionary. -</tag-desc> - -<tag-name id="dict_delete"><literal>ngx.shared.SharedDict.delete(<value>key</value>)</literal></tag-name> -<tag-desc> -Removes the item associated with the specified key -from the <literal>SharedDict</literal> dictionary, -<literal>true</literal> if the item in the dictionary existed and was removed, -<literal>false</literal> otherwise. -</tag-desc> - -<tag-name id="dict_freespace"><literal>ngx.shared.SharedDict.freeSpace()</literal></tag-name> -<tag-desc> -Returns the free page size in bytes. -If the size is zero, the <literal>SharedDict</literal> dictionary -will still accept new values if there is space in the occupied pages. -</tag-desc> - -<tag-name id="dict_get"><literal>ngx.shared.SharedDict.get(<value>key</value>)</literal></tag-name> -<tag-desc> -Retrieves the item by its <literal>key</literal>, -returns the value associated with the <literal>key</literal> -or <literal>undefined</literal> if there is none. -</tag-desc> - -<tag-name id="dict_has"><literal>ngx.shared.SharedDict.has(<value>key</value>)</literal></tag-name> -<tag-desc> -Searches for an item by its <literal>key</literal>, -returns <literal>true</literal> if such item exists or -<literal>false</literal> otherwise. -</tag-desc> - -<tag-name id="dict_incr"><literal>ngx.shared.SharedDict.incr(<value>key</value>,<value>delta</value>[,<value>init</value>])</literal></tag-name> -<tag-desc> -Increments the integer value associated with the <literal>key</literal> -by <literal>delta</literal>. -If the key does not exist, -the item will be initialized to <literal>init</literal>. -The <literal>key</literal> is a string, -the <literal>delta</literal> is the number -to increment or decrement the value by, -the <literal>init</literal> is a number to initialize the item with -if it does not exist, by default is <literal>0</literal>. -Returns the new value. -Throws <literal>SharedMemoryError</literal> if -there is not enough free space in the <literal>SharedDict</literal> dictionary. -Throws <literal>TypeError</literal> if this dictionary does not expect numbers. -<note> -This method can be used only if the dictionary type was declared with -<literal>type=number</literal> parameter of the -<literal>js_shared_dict_zone</literal> directive in -<link doc="../http/ngx_http_js_module.xml" id="js_shared_dict_zone">http</link> -or -<link doc="../stream/ngx_stream_js_module.xml" id="js_shared_dict_zone">stream</link>. -</note> -</tag-desc> - -<tag-name id="dict_items"><literal>ngx.shared.SharedDict.items([<value>maxCount</value>])</literal></tag-name> -<tag-desc> -Returns an array of the <literal>SharedDict</literal> dictionary -key-value items (since <link doc="changes.xml" id="njs0.8.1">0.8.1</link>). -The <literal>maxCount</literal> parameter -sets maximum number of items to retrieve, -by default is <literal>1024</literal>. - -</tag-desc> - -<tag-name id="dict_keys"><literal>ngx.shared.SharedDict.keys([<value>maxCount</value>])</literal></tag-name> -<tag-desc> -Returns an array of the <literal>SharedDict</literal> dictionary keys. -The <literal>maxCount</literal> parameter -sets maximum number of keys to retrieve, -by default is <literal>1024</literal>. -</tag-desc> - -<tag-name id="dict_name"><literal>ngx.shared.SharedDict.name</literal></tag-name> -<tag-desc> -Returns the name of the <literal>SharedDict</literal> dictionary, -corresponds to the <literal>zone=</literal> parameter of -<literal>js_shared_dict_zone</literal> directive in -<link doc="../http/ngx_http_js_module.xml" id="js_shared_dict_zone">http</link> -or -<link doc="../stream/ngx_stream_js_module.xml" id="js_shared_dict_zone">stream</link>. -</tag-desc> - -<tag-name id="dict_pop"><literal>ngx.shared.SharedDict.pop(<value>key</value>)</literal></tag-name> -<tag-desc> -Removes the item associated with the specified <literal>key</literal> -from the <literal>SharedDict</literal> dictionary, -returns the value associated with the <literal>key</literal> -or <literal>undefined</literal> if there is none. -</tag-desc> - -<tag-name id="dict_replace"><literal>ngx.shared.SharedDict.replace(<value>key</value>, -<value>value</value>)</literal></tag-name> -<tag-desc> -Replaces the <literal>value</literal> -for the specified <literal>key</literal> only if the key already exists, -returns <literal>true</literal> if the value was successfully replaced, -<literal>false</literal> if the key does not exist -in the <literal>SharedDict</literal> dictionary. -Throws <literal>SharedMemoryError</literal> if -there is not enough free space in the <literal>SharedDict</literal> dictionary. -Throws <literal>TypeError</literal> if the <literal>value</literal> is -of a different type than expected by this dictionary. -</tag-desc> - -<tag-name id="dict_set"><literal>ngx.shared.SharedDict.set(<value>key</value>, -<value>value</value>)</literal></tag-name> -<tag-desc> -Sets the <literal>value</literal> for the specified <literal>key</literal>, -returns this <literal>SharedDict</literal> dictionary (for method chaining). -</tag-desc> - -<tag-name id="dict_size"><literal>ngx.shared.SharedDict.size()</literal></tag-name> -<tag-desc> -Returns the number of items for the <literal>SharedDict</literal> dictionary. -</tag-desc> - -<tag-name id="dict_type"><literal>ngx.shared.SharedDict.type</literal></tag-name> -<tag-desc> -Returns <literal>string</literal> or <literal>number</literal> that -corresponds to the <literal>SharedDict</literal> dictionary type -set by the <literal>type=</literal> parameter of -<literal>js_shared_dict_zone</literal> directive in -<link doc="../http/ngx_http_js_module.xml" id="js_shared_dict_zone">http</link> -or -<link doc="../stream/ngx_stream_js_module.xml" id="js_shared_dict_zone">stream</link>. -</tag-desc> - -</list> -</para> - -</section> - -</section> - -</section> - - -<section id="builtin_objects" name="built-in objects"> - - -<section id="console" name="console"> - -<para> -<table width="100%"> -<tr><td><link id="console_error"><literal>console.error()</literal></link></td></tr> -<tr><td><link id="console_info"><literal>console.info()</literal></link></td></tr> -<tr><td><link id="console_log"><literal>console.log()</literal></link></td></tr> -<tr><td><link id="console_time"><literal>console.time()</literal></link></td></tr> -<tr><td><link id="console_time_end"><literal>console.timeEnd()</literal></link></td></tr> -<tr><td><link id="console_warn"><literal>console.warn()</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>console</literal> object is available -in nginx since <link doc="changes.xml" id="njs0.8.2">0.8.2</link>, -in CLI since <link doc="changes.xml" id="njs0.2.6">0.2.6</link>. -<list type="tag"> - -<tag-name id="console_error"><literal>console.error(<value>msg</value>[, <value>msg2</value> ...])</literal></tag-name> -<tag-desc> -Outputs one or more error messages. -The message may be a string or an object. -</tag-desc> - -<tag-name id="console_info"><literal>console.info(<value>msg</value>[, <value>msg2</value> ...])</literal></tag-name> -<tag-desc> -Outputs one or more info messages. -The message may be a string or an object. -</tag-desc> - -<tag-name id="console_log"><literal>console.log(<value>msg</value>[, <value>msg2</value> ...])</literal></tag-name> -<tag-desc> -Outputs one or more log messages. -The message may be a string or an object. -</tag-desc> - -<tag-name id="console_time"><literal>console.time(<value>label</value>)</literal></tag-name> -<tag-desc> -Starts a timer that can track how long an operation takes. -The <literal>label</literal> parameter allows naming different timers. -If <link id="console_time_end"><literal>console.timeEnd()</literal></link> -with the same name is called, -the time that elapsed since the timer was started will be output, -in milliseconds. -</tag-desc> - -<tag-name id="console_time_end"><literal>console.timeEnd(<value>label</value>)</literal></tag-name> -<tag-desc> -Stops a timer previously started by -<link id="console_time"><literal>console.time()</literal></link> -The <literal>label</literal> parameter allows naming different timers. -</tag-desc> - -<tag-name id="console_warn"><literal>console.warn(<value>msg</value>[, <value>msg2</value> ...])</literal></tag-name> -<tag-desc> -Outputs one or more warning messages. -The message may be a string or an object. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="builtin_crypto" name="crypto"> - -<para> -<table width="100%"> -<tr><td><link id="crypto_get_random_values"><literal>сrypto.getRandomValues()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_encrypt"><literal>сrypto.subtle.encrypt()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_decrypt"><literal>сrypto.subtle.decrypt()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_derive_bits"><literal>сrypto.subtle.deriveBits()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_derive_key"><literal>сrypto.subtle.deriveKey()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_digest"><literal>сrypto.subtle.digest()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_export_key"><literal>сrypto.subtle.exportKey()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_generate_key"><literal>сrypto.subtle.generateKey()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_import_key"><literal>сrypto.subtle.importKey()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_sign"><literal>сrypto.subtle.sign()</literal></link></td></tr> -<tr><td><link id="crypto_subtle_verify"><literal>сrypto.subtle.verify()</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>crypto</literal> object is a global object -that allows using cryptographic functionality -(since <link doc="changes.xml" id="njs0.7.0">0.7.0</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="crypto_get_random_values"><literal>сrypto.getRandomValues</literal>(<link id="crypto_get_random_values_array"><literal>typedArray</literal></link>)</tag-name> -<tag-desc> -Gets cryptographically strong random values. -Returns the same array passed as <literal>typedArray</literal> -but with its contents replaced with the newly generated random numbers. -Possible values: - -<list type="tag"> -<tag-name id="crypto_get_random_values_array"><literal>typedArray</literal></tag-name> -<tag-desc> -can be -<literal>Int8Array</literal>, -<literal>Int16Array</literal>, -<literal>Uint16Array</literal>, -<literal>Int32Array</literal>, or -<literal>Uint32Array</literal> -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_encrypt"><literal>сrypto.subtle.encrypt</literal>(<link id="crypto_encrypt_alg"><literal>algorithm</literal></link>, -<link id="crypto_encrypt_key"><literal>key</literal></link>, -<link id="crypto_encrypt_data"><literal>data</literal></link>)</tag-name> -<tag-desc> -Encrypts <link id="crypto_encrypt_data"><literal>data</literal></link> -using the provided -<link id="crypto_encrypt_algorithm"><literal>algorithm</literal></link> and -<link id="crypto_encrypt_key"><literal>key</literal></link>. -Returns a <literal>Promise</literal> that fulfills with -an <literal>ArrayBuffer</literal> containing the ciphertext. -Possible values: - -<list type="tag"> -<tag-name id="crypto_encrypt_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -an object that specifies -the algorithm to be used and any extra parameters if required: - -<list type="bullet"> -<listitem id="rsa_oaep_params"> -for <literal>RSA-OAEP</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>RSA-OAEP</literal>: -<para> -<example> -crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data) -</example> -</para> -</listitem> -</list> - -</listitem> - -<listitem id="aes_ctr_params"> -for <literal>AES-CTR</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>AES-CTR</literal> -</listitem> - -<listitem> -<literal>counter</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> — -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 -</listitem> - -<listitem> -<literal>length</literal> 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. -</listitem> -</list> - -</listitem> - -<listitem id="aes_cbc_params"> -for <literal>AES-CBC</literal>, pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>AES-CBC</literal> -</listitem> - -<listitem> -<literal>iv</literal> or the initialization vector, is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>, -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. -</listitem> -</list> - -</listitem> - -<listitem id="aes_gcm_params"> -for <literal>AES-GCM</literal>, pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>AES-GCM</literal> -</listitem> - -<listitem> -<literal>iv</literal> or the initialization vector, is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>, -must be 16 bytes, -and must be unique for every encryption operation carried out with a given key -</listitem> - -<listitem> -<literal>additionalData</literal> (optional) is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that contains additional data that -will not be encrypted but will be authenticated along with the encrypted data. -If <literal>additionalData</literal> is specified, -then the same data must be specified in the corresponding call to -<literal>decrypt()</literal>: -if the data given to the <literal>decrypt()</literal> call -does not match the original data, -the decryption will throw an exception. -The bit length of <literal>additionalData</literal> -must be smaller than <literal>2^64 - 1</literal>. -</listitem> - -<listitem> -<literal>tagLength</literal> (optional, default is <literal>128</literal>) - -a <literal>number</literal> 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: -<literal>32</literal>, -<literal>64</literal>, -<literal>96</literal>, -<literal>104</literal>, -<literal>112</literal>, -<literal>120</literal>, or -<literal>128</literal>. -The AES-GCM specification recommends that it should be -<literal>96</literal>, -<literal>104</literal>, -<literal>112</literal>, -<literal>120</literal>, or -<literal>128</literal>, -although -<literal>32</literal> or -<literal>64</literal> -bits may be acceptable in some applications. -</listitem> -</list> - -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_encrypt_key"><literal>key</literal></tag-name> -<tag-desc> -a <link id="cryptokey"><literal>CryptoKey</literal></link> that contains -the key to be used for encryption -</tag-desc> - -<tag-name id="crypto_encrypt_data"><literal>data</literal></tag-name> -<tag-desc> -an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that contains -the data to be encrypted (also known as the plaintext) -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_decrypt"><literal>сrypto.subtle.decrypt</literal>(<link id="crypto_decrypt_alg"><literal>algorithm</literal></link>, -<link id="crypto_decrypt_key"><literal>key</literal></link>, -<link id="crypto_decrypt_data"><literal>data</literal></link>)</tag-name> -<tag-desc> -Decrypts encrypted data. -Returns a <literal>Promise</literal> with the decrypted data. -Possible values: - -<list type="tag"> - -<tag-name id="crypto_decrypt_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -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 <literal>encrypt()</literal> call. - -<list type="bullet"> -<listitem> -for <literal>RSA-OAEP</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>RSA-OAEP</literal>: -<para> -<example> -crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data) -</example> -</para> -</listitem> -</list> -</listitem> - -<listitem> -for <literal>AES-CTR</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>AES-CTR</literal> -</listitem> - -<listitem> -<literal>counter</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> — -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. -</listitem> - -<listitem> -<literal>length</literal> 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. -</listitem> -</list> - -</listitem> - -<listitem> -for <literal>AES-CBC</literal>, pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>AES-CBC</literal> -</listitem> - -<listitem> -<literal>iv</literal> or the initialization vector, is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>, -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). -</listitem> -</list> - -</listitem> - -<listitem> -for <literal>AES-GCM</literal>, pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>AES-GCM</literal> -</listitem> - -<listitem> -<literal>iv</literal> or the initialization vector, is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>, -must be 16 bytes, -and must be unique for every encryption operation carried out with a given key -</listitem> - -<listitem> -<literal>additionalData</literal> (optional) is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that contains additional data that -will not be encrypted but will be authenticated along with the encrypted data. -If <literal>additionalData</literal> is specified, -then the same data must be specified in the corresponding call to -<literal>decrypt()</literal>: -if the data given to the <literal>decrypt()</literal> call -does not match the original data, -the decryption will throw an exception. -The bit length of <literal>additionalData</literal> -must be smaller than <literal>2^64 - 1</literal>. -</listitem> - -<listitem> -<literal>tagLength</literal> (optional, default is <literal>128</literal>) - -a <literal>number</literal> 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: -<literal>32</literal>, -<literal>64</literal>, -<literal>96</literal>, -<literal>104</literal>, -<literal>112</literal>, -<literal>120</literal>, or -<literal>128</literal>. -The AES-GCM specification recommends that it should be -<literal>96</literal>, -<literal>104</literal>, -<literal>112</literal>, -<literal>120</literal>, or -<literal>128</literal>, -although -<literal>32</literal> or -<literal>64</literal> -bits may be acceptable in some applications. -</listitem> -</list> - -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_decrypt_key"><literal>key</literal></tag-name> -<tag-desc> -a <link id="cryptokey"><literal>CryptoKey</literal></link> -that contains the key to be used for decryption. -If <literal>RSA-OAEP</literal> is used, this is the -<literal>privateKey</literal> property of the -<link id="cryptokeypair"><literal>CryptoKeyPair</literal></link> object. -</tag-desc> - -<tag-name id="crypto_decrypt_data"><literal>data</literal></tag-name> -<tag-desc> -an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that contains the data to be decrypted (also known as ciphertext) -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_derive_bits"><literal>сrypto.subtle.deriveBits</literal>(<link id="crypto_derive_bits_alg"><literal>algorithm</literal></link>, -<link id="crypto_derive_bits_basekey"><literal>baseKey</literal></link>, -<link id="crypto_derive_bits_length"><literal>length</literal></link>)</tag-name> -<tag-desc> -Derives an array of bits from a base key. -Returns a <literal>Promise</literal> -which will be fulfilled with an -<literal>ArrayBuffer</literal> that contains the derived bits. -Possible values: - -<list type="tag"> -<tag-name id="crypto_derive_bits_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -is an object that defines the derivation algorithm to use: - -<list type="bullet"> -<listitem id="hkdf_params"> -for <literal>HKDF</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>HKDF</literal> -</listitem> - -<listitem> -<literal>hash</literal> is a string with the digest algorithm to use: -<literal>SHA-1</literal>, -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>salt</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that represents random or pseudo-random value -with the same length as the output of the <literal>digest</literal> function. -Unlike the input key material passed into <literal>deriveKey()</literal>, -salt does not need to be kept secret. -</listitem> - -<listitem> -<literal>info</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -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. -</listitem> -</list> - -</listitem> - -<listitem id="pbkdf2_params"> -for <literal>PBKDF2</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>PBKDF2</literal> -</listitem> - -<listitem> -<literal>hash</literal> is a string with the digest algorithm to use: -<literal>SHA-1</literal>, -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>salt</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that represents random or pseudo-random value -of at least <literal>16</literal> bytes. -Unlike the input key material passed into <literal>deriveKey()</literal>, -salt does not need to be kept secret. -</listitem> - -<listitem> -<literal>iterations</literal> is a <literal>number</literal> -that represents the number of times the hash function will be executed -in <literal>deriveKey()</literal> -</listitem> -</list> - -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_derive_bits_basekey"><literal>baseKey</literal></tag-name> -<tag-desc> -is a <link id="cryptokey"><literal>CryptoKey</literal></link> -that represents the input to the derivation algorithm -- the initial key material for the derivation function: -for example, for <literal>PBKDF2</literal> it might be a password, -imported as a <link id="cryptokey"><literal>CryptoKey</literal></link> using -<link id="crypto_subtle_import_key"><literal>сrypto.subtle.importKey()</literal></link> -</tag-desc> - -<tag-name id="crypto_derive_bits_length"><literal>length</literal></tag-name> -<tag-desc> -is a number representing the number of bits to derive. -For browsers compatibility, -the number should be a multiple of <literal>8</literal> -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_derive_key"><literal>сrypto.subtle.deriveKey</literal>(<link id="crypto_derive_key_alg"><literal>algorithm</literal></link>, -<link id="crypto_derive_key_basekey"><literal>baseKey</literal></link>, -<link id="crypto_derive_key_derivedkeyalg"><literal>derivedKeyAlgorithm</literal></link>, -<link id="crypto_derive_key_extractable"><literal>extractable</literal></link>, -<link id="crypto_derive_key_keyusages"><literal>keyUsages</literal></link>)</tag-name> -<tag-desc> -Derives a secret key from a master key. -Possible values: - -<list type="tag"> -<tag-name id="crypto_derive_key_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -is an object that defines the derivation algorithm to use: - -<list type="bullet"> -<listitem> -for <literal>HKDF</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>HKDF</literal> -</listitem> - -<listitem> -<literal>hash</literal> is a string with the digest algorithm to use: -<literal>SHA-1</literal>, -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>salt</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that represents random or pseudo-random value -with the same length as the output of the <literal>digest</literal> function. -Unlike the input key material passed into <literal>deriveKey()</literal>, -salt does not need to be kept secret. -</listitem> - -<listitem> -<literal>info</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -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. -</listitem> -</list> - -</listitem> - -<listitem> -for <literal>PBKDF2</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>PBKDF2</literal> -</listitem> - -<listitem> -<literal>hash</literal> is a string with the digest algorithm to use: -<literal>SHA-1</literal>, -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>salt</literal> is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that represents random or pseudo-random value -of at least <literal>16</literal> bytes. -Unlike the input key material passed into <literal>deriveKey()</literal>, -salt does not need to be kept secret. -</listitem> - -<listitem> -<literal>iterations</literal> is a <literal>number</literal> -that represents the number of times the hash function will be executed -in <literal>deriveKey()</literal> -</listitem> -</list> - -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_derive_key_basekey"><literal>baseKey</literal></tag-name> -<tag-desc> -is a <link id="cryptokey"><literal>CryptoKey</literal></link> -that represents the input to the derivation algorithm -- the initial key material for the derivation function: -for example, for <literal>PBKDF2</literal> it might be a password, -imported as a <link id="cryptokey"><literal>CryptoKey</literal></link> using -<link id="crypto_subtle_import_key"><literal>сrypto.subtle.importKey()</literal></link>. -</tag-desc> - -<tag-name id="crypto_derive_key_derivedkeyalg"><literal>derivedKeyAlgorithm</literal></tag-name> -<tag-desc> -is an object -that defines the algorithm the derived key will be used for: - -<list type="bullet"> -<listitem> -for <literal>HMAC</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to <literal>HMAC</literal> -</listitem> - -<listitem> -<literal>hash</literal> is a string with the name of the digest function to use: -<literal>SHA-1</literal>, -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>length</literal> (optional) is a <literal>number</literal> -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 -</listitem> -</list> - -</listitem> - -<listitem> -for -<literal>AES-CTR</literal>, -<literal>AES-CBC</literal>, or -<literal>AES-GCM</literal>, -pass the object with the following keys: - -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, -should be set to -<literal>AES-CTR</literal>, -<literal>AES-CBC</literal>, or -<literal>AES-GCM</literal>, -depending on the algorithm used -</listitem> - -<listitem> -<literal>length</literal> is a <literal>number</literal> that represents -the length in bits of the key to generate: -<literal>128</literal>, -<literal>192</literal>, or -<literal>256</literal> -</listitem> -</list> - -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_derive_key_extractable"><literal>extractable</literal></tag-name> -<tag-desc> -is a boolean value -that indicates whether it will be possible to export the key -</tag-desc> - -<tag-name id="crypto_derive_key_keyusages"><literal>keyUsages</literal></tag-name> -<tag-desc> -is an <literal>Array</literal> -that indicates what can be done with the derived key. -The key usages must be allowed by the algorithm -set in <literal>derivedKeyAlgorithm</literal>. -Possible values: -<list type="tag"> - -<tag-name><literal>encrypt</literal></tag-name> -<tag-desc> -key for encrypting messages -</tag-desc> - -<tag-name><literal>decrypt</literal></tag-name> -<tag-desc> -key for decrypting messages -</tag-desc> - -<tag-name><literal>sign</literal></tag-name> -<tag-desc> -key for signing messages -</tag-desc> - -<tag-name><literal>verify</literal></tag-name> -<tag-desc> -key for verifying signatures -</tag-desc> - -<tag-name><literal>deriveKey</literal></tag-name> -<tag-desc> -key for deriving a new key -</tag-desc> - -<tag-name><literal>deriveBits</literal></tag-name> -<tag-desc> -key for deriving bits -</tag-desc> - -<tag-name><literal>wrapKey</literal></tag-name> -<tag-desc> -key for wrapping a key -</tag-desc> - -<tag-name><literal>unwrapKey</literal></tag-name> -<tag-desc> -key for unwrapping a key -</tag-desc> -</list> - -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_digest"><literal>сrypto.subtle.digest</literal>(<link id="crypto_digest_alg"><literal>algorithm</literal></link>, -<link id="crypto_digest_data"><literal>data</literal></link>)</tag-name> -<tag-desc> -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 <literal>Promise</literal> which will be fulfilled with the digest. -Possible values: - -<list type="tag"> -<tag-name id="crypto_digest_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -is a string that defines the hash function to use: -<literal>SHA-1</literal> (not for cryptographic applications), -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</tag-desc> - -<tag-name id="crypto_digest_data"><literal>data</literal></tag-name> -<tag-desc> -is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that contains the data to be digested -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_export_key"><literal>сrypto.subtle.exportKey</literal>(<link id="crypto_export_key_format"><literal>format</literal></link>, -<link id="crypto_export_key_keydata"><literal>key</literal></link>)</tag-name> -<tag-desc> -Exports a key: takes a key as -a <link id="cryptokey"><literal>CryptoKey</literal></link> object -and returns the key in an external, portable format -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -If the <literal>format</literal> was <literal>jwk</literal>, -then the <literal>Promise</literal> fulfills with a JSON object -containing the key. -Otherwise, the promise fulfills with an -<literal>ArrayBuffer</literal> containing the key. -Possible values: -<list type="tag"> - -<tag-name id="crypto_export_key_format"><literal>format</literal></tag-name> -<tag-desc> -a string that describes the data format in which the key should be exported, -can be the following: -<list type="tag"> - -<tag-name><literal>raw</literal></tag-name> -<tag-desc> -the raw data format -</tag-desc> - -<tag-name><literal>pkcs8</literal></tag-name> -<tag-desc> -the -<link url="https://datatracker.ietf.org/doc/html/rfc5208">PKCS #8</link> -format -</tag-desc> - -<tag-name><literal>spki</literal></tag-name> -<tag-desc> -the -<link url="https://datatracker.ietf.org/doc/html/rfc5280#section-4.1">SubjectPublicKeyInfo</link> -format -</tag-desc> - -<tag-name><literal>jwk</literal></tag-name> -<tag-desc> -the -<link url="https://datatracker.ietf.org/doc/html/rfc7517">JSON Web Key</link> -(JWK) format (since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>) -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="crypto_export_key_keydata"><literal>key</literal></tag-name> -<tag-desc> -the <link id="cryptokey"><literal>CryptoKey</literal></link> -that contains the key to be exported -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_generate_key"><literal>сrypto.subtle.generateKey</literal>(<link id="crypto_generate_key_alg"><literal>algorithm</literal></link>, -<link id="crypto_generate_key_extractable"><literal>extractable</literal></link>, -<link id="crypto_generate_key_usage"><literal>usage</literal></link>)</tag-name> -<tag-desc> -Generates a new key for symmetric algorithms -or key pair for public-key algorithms -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -Returns a <literal>Promise</literal> that fulfills with the generated key -as -a <link id="cryptokey"><literal>CryptoKey</literal></link> -or <link id="cryptokeypair"><literal>CryptoKeyPair</literal></link> object. -Possible values: -<list type="tag"> - -<tag-name id="crypto_generate_key_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -a dictionary object that defines the type of key to generate -and provides extra algorithm-specific parameters: - -<list type="bullet"> -<listitem> -for -<literal>RSASSA-PKCS1-v1_5</literal>, -<literal>RSA-PSS</literal>, or -<literal>RSA-OAEP</literal>, -pass the object with the following keys: - -<list type="bullet"> -<listitem> -<literal>name</literal> is a string, should be set to -<literal>RSASSA-PKCS1-v1_5</literal>, -<literal>RSA-PSS</literal>, or -<literal>RSA-OAEP</literal>, -depending on the used algorithm -</listitem> - -<listitem> -<literal>hash</literal> is a string that represents -the name of the <literal>digest</literal> function to use, can be -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> -</list> - -</listitem> - -<listitem> -for -<literal>ECDSA</literal>, -pass the object with the following keys: - -<list type="bullet"> -<listitem> -<literal>name</literal> is a string, should be set to <literal>ECDSA</literal> -</listitem> - -<listitem> -<literal>namedCurve</literal> is a string that represents -the name of the elliptic curve to use, may be -<literal>P-256</literal>, -<literal>P-384</literal>, or -<literal>P-521</literal> -</listitem> - -</list> -</listitem> - -<listitem> -for -<literal>HMAC</literal>, -pass the object with the following keys: - -<list type="bullet"> -<listitem> -<literal>name</literal> is a string, should be set to <literal>HMAC</literal> -</listitem> - - -<listitem> -<literal>hash</literal> is a string that represents -the name of the <literal>digest</literal> function to use, can be -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>length</literal> (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. -</listitem> -</list> - -</listitem> - -<listitem> -for -<literal>AES-CTR</literal>, -<literal>AES-CBC</literal>, or -<literal>AES-GCM</literal>, -pass the string identifying the algorithm or an object -of the form <literal>{ "name": "ALGORITHM" }</literal>, -where <literal>ALGORITHM</literal> is the name of the algorithm -</listitem> - -</list> -</tag-desc> - -<tag-name id="crypto_generate_key_extractable"><literal>extractable</literal></tag-name> -<tag-desc> -boolean value that indicates if it is possible to export the key -</tag-desc> - -<tag-name id="crypto_generate_key_usage"><literal>usage</literal></tag-name> -<tag-desc> -an <literal>array</literal> that indicates possible actions with the key: -<list type="tag"> - -<tag-name><literal>encrypt</literal></tag-name> -<tag-desc> -key for encrypting messages -</tag-desc> - -<tag-name><literal>decrypt</literal></tag-name> -<tag-desc> -key for decrypting messages -</tag-desc> - -<tag-name><literal>sign</literal></tag-name> -<tag-desc> -key for signing messages -</tag-desc> - -<tag-name><literal>verify</literal></tag-name> -<tag-desc> -key for verifying signatures -</tag-desc> - -<tag-name><literal>deriveKey</literal></tag-name> -<tag-desc> -key for deriving a new key -</tag-desc> - -<tag-name><literal>deriveBits</literal></tag-name> -<tag-desc> -key for deriving bits -</tag-desc> - -<tag-name><literal>wrapKey</literal></tag-name> -<tag-desc> -key for wrapping a key -</tag-desc> - -<tag-name><literal>unwrapKey</literal></tag-name> -<tag-desc> -key for unwrapping a key -</tag-desc> -</list> - -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_import_key"><literal>сrypto.subtle.importKey</literal>(<link id="crypto_import_key_format"><literal>format</literal></link>, -<link id="crypto_import_key_keydata"><literal>keyData</literal></link>, -<link id="crypto_import_key_alg"><literal>algorithm</literal></link>, -<link id="crypto_import_key_extractable"><literal>extractable</literal></link>, -<link id="crypto_import_key_keyusages"><literal>keyUsages</literal></link>)</tag-name> -<tag-desc> -Imports a key: takes as input a key in an external, portable format -and gives a <link id="cryptokey"><literal>CryptoKey</literal></link> object. -Returns a <literal>Promise</literal> that fulfills with the imported key -as a <link id="cryptokey"><literal>CryptoKey</literal></link> object. -Possible values: -<list type="tag"> - -<tag-name id="crypto_import_key_format"><literal>format</literal></tag-name> -<tag-desc> -a string that describes the data format of the key to import, -can be the following: -<list type="tag"> - -<tag-name><literal>raw</literal></tag-name> -<tag-desc> -the raw data format -</tag-desc> - -<tag-name><literal>pkcs8</literal></tag-name> -<tag-desc> -the -<link url="https://datatracker.ietf.org/doc/html/rfc5208">PKCS #8</link> -format -</tag-desc> - -<tag-name><literal>spki</literal></tag-name> -<tag-desc> -the -<link url="https://datatracker.ietf.org/doc/html/rfc5280#section-4.1">SubjectPublicKeyInfo</link> -format -</tag-desc> - -<tag-name><literal>jwk</literal></tag-name> -<tag-desc> -the -<link url="https://datatracker.ietf.org/doc/html/rfc7517">JSON Web Key</link> -(JWK) format (since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>) -</tag-desc> - -</list> - -</tag-desc> - -<tag-name id="crypto_import_key_keydata"><literal>keyData</literal></tag-name> -<tag-desc> -the -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -object that contains the key in the given format -</tag-desc> - -<tag-name id="crypto_import_key_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -a dictionary object that defines the type of key to import -and provides extra algorithm-specific parameters: - -<list type="bullet"> -<listitem> -for -<literal>RSASSA-PKCS1-v1_5</literal>, -<literal>RSA-PSS</literal>, or -<literal>RSA-OAEP</literal>, -pass the object with the following keys: - -<list type="bullet"> -<listitem> -<literal>name</literal> is a string, should be set to -<literal>RSASSA-PKCS1-v1_5</literal>, -<literal>RSA-PSS</literal>, or -<literal>RSA-OAEP</literal>, -depending on the used algorithm -</listitem> - -<listitem> -<literal>hash</literal> is a string that represents -the name of the <literal>digest</literal> function to use, can be -<literal>SHA-1</literal>, -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> -</list> - -</listitem> - -<listitem> -for -<literal>ECDSA</literal>, -pass the object with the following keys: - -<list type="bullet"> -<listitem> -<literal>name</literal> is a string, should be set to <literal>ECDSA</literal> -</listitem> - -<listitem> -<literal>namedCurve</literal> is a string that represents -the name of the elliptic curve to use, may be -<literal>P-256</literal>, -<literal>P-384</literal>, or -<literal>P-521</literal> -</listitem> - -</list> -</listitem> - -<listitem> -for -<literal>HMAC</literal>, -pass the object with the following keys: - -<list type="bullet"> -<listitem> -<literal>name</literal> is a string, should be set to <literal>HMAC</literal> -</listitem> - - -<listitem> -<literal>hash</literal> is a string that represents -the name of the <literal>digest</literal> function to use, can be -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -<listitem> -<literal>length</literal> (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. -</listitem> -</list> - -</listitem> - -<listitem> -for -<literal>AES-CTR</literal>, -<literal>AES-CBC</literal>, or -<literal>AES-GCM</literal>, -pass the string identifying the algorithm or an object -of the form <literal>{ "name": "ALGORITHM" }</literal>, -where <literal>ALGORITHM</literal> is the name of the algorithm -</listitem> - -<listitem> -for -<literal>PBKDF2</literal>, -pass the <literal>PBKDF2</literal> string -</listitem> - -<listitem> -for -<literal>HKDF</literal>, -pass the <literal>HKDF</literal> string -</listitem> - -</list> -</tag-desc> - -<tag-name id="crypto_import_key_extractable"><literal>extractable</literal></tag-name> -<tag-desc> -boolean value that indicates if it is possible to export the key -</tag-desc> - -<tag-name id="crypto_import_key_keyusages"><literal>keyUsages</literal></tag-name> -<tag-desc> -an <literal>array</literal> that indicates possible actions with the key: -<list type="tag"> - -<tag-name><literal>encrypt</literal></tag-name> -<tag-desc> -key for encrypting messages -</tag-desc> - -<tag-name><literal>decrypt</literal></tag-name> -<tag-desc> -key for decrypting messages -</tag-desc> - -<tag-name><literal>sign</literal></tag-name> -<tag-desc> -key for signing messages -</tag-desc> - -<tag-name><literal>verify</literal></tag-name> -<tag-desc> -key for verifying signatures -</tag-desc> - -<tag-name><literal>deriveKey</literal></tag-name> -<tag-desc> -key for deriving a new key -</tag-desc> - -<tag-name><literal>deriveBits</literal></tag-name> -<tag-desc> -key for deriving bits -</tag-desc> - -<tag-name><literal>wrapKey</literal></tag-name> -<tag-desc> -key for wrapping a key -</tag-desc> - -<tag-name><literal>unwrapKey</literal></tag-name> -<tag-desc> -key for unwrapping a key -</tag-desc> -</list> - -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="crypto_subtle_sign"><literal>сrypto.subtle.sign</literal>(<link id="crypto_sign_alg"><literal>algorithm</literal></link>, -<link id="crypto_sign_key"><literal>key</literal></link>, -<link id="crypto_sign_data"><literal>data</literal></link>)</tag-name> -<tag-desc> -Returns <literal>signature</literal> as a <literal>Promise</literal> -that fulfills with an <literal>ArrayBuffer</literal> containing the signature. -Possible values: - -<list type="tag"> -<tag-name id="crypto_sign_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -is a string or object that specifies the signature algorithm to use -and its parameters: - -<list type="bullet"> - -<listitem> -for <literal>RSASSA-PKCS1-v1_5</literal>, -pass the string identifying the algorithm or an object -of the form <literal>{ "name": "ALGORITHM" }</literal> -</listitem> - -<listitem> -for <literal>RSA-PSS</literal>, -pass the object with the following keys: -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, should be set to -<literal>RSA-PSS</literal> -</listitem> - -<listitem> -<literal>saltLength</literal> is a long <literal>integer</literal> -that represents the length of the random salt to use, in bytes -</listitem> - -</list> -</listitem> - -<listitem> -for <literal>ECDSA</literal>, -pass the object with the following keys: -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, should be set to -<literal>ECDSA</literal> -</listitem> - -<listitem> -<literal>hash</literal> is an identifier for the digest algorithm to use, -can be -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -</list> -</listitem> - -<listitem> -for <literal>HMAC</literal>, -pass the string identifying the algorithm or an object -of the form <literal>{ "name": "ALGORITHM" }</literal> -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_sign_key"><literal>key</literal></tag-name> -<tag-desc> -is a <link id="cryptokey"><literal>CryptoKey</literal></link> object -that the key to be used for signing. -If algorithm identifies a public-key cryptosystem, this is the private key. -</tag-desc> - -<tag-name id="crypto_sign_data"><literal>data</literal></tag-name> -<tag-desc> -is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -object that contains the data to be signed -</tag-desc> -</list> - -</tag-desc> - - -<tag-name id="crypto_subtle_verify"><literal>сrypto.subtle.verify</literal>(<link id="crypto_verify_alg"><literal>algorithm</literal></link>, -<link id="crypto_verify_key"><literal>key</literal></link>, -<link id="crypto_verify_signature"><literal>signature</literal></link>, -<link id="crypto_verify_data"><literal>data</literal></link>)</tag-name> -<tag-desc> -Verifies a digital signature, -returns a <literal>Promise</literal> that fulfills with a boolean value: -<literal>true</literal> if the signature is valid, -otherwise <literal>false</literal>. -Possible values: - -<list type="tag"> -<tag-name id="crypto_verify_alg"><literal>algorithm</literal></tag-name> -<tag-desc> -is a string or object that specifies the algorithm to use -and its parameters: - -<list type="bullet"> - -<listitem> -for <literal>RSASSA-PKCS1-v1_5</literal>, -pass the string identifying the algorithm or an object -of the form <literal>{ "name": "ALGORITHM" }</literal> -</listitem> - -<listitem> -for <literal>RSA-PSS</literal>, -pass the object with the following keys: -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, should be set to -<literal>RSA-PSS</literal> -</listitem> - -<listitem> -<literal>saltLength</literal> is a long <literal>integer</literal> -that represents the length of the random salt to use, in bytes -</listitem> - -</list> -</listitem> - -<listitem> -for <literal>ECDSA</literal>, -pass the object with the following keys: -<list type="bullet"> - -<listitem> -<literal>name</literal> is a string, should be set to -<literal>ECDSA</literal> -</listitem> - -<listitem> -<literal>hash</literal> is an identifier for the digest algorithm to use, -can be -<literal>SHA-256</literal>, -<literal>SHA-384</literal>, or -<literal>SHA-512</literal> -</listitem> - -</list> -</listitem> - -<listitem> -for <literal>HMAC</literal>, -pass the string identifying the algorithm or an object -of the form <literal>{ "name": "ALGORITHM" }</literal> -</listitem> -</list> - -</tag-desc> - -<tag-name id="crypto_verify_key"><literal>key</literal></tag-name> -<tag-desc> -is a <link id="cryptokey"><literal>CryptoKey</literal></link> 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. -</tag-desc> - -<tag-name id="crypto_verify_signature"><literal>signature</literal></tag-name> -<tag-desc> -is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -that contains the signature to verify -</tag-desc> - -<tag-name id="crypto_verify_data"><literal>data</literal></tag-name> -<tag-desc> -is an -<literal>ArrayBuffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -object that contains the data whose signature is to be verified -</tag-desc> -</list> - -</tag-desc> - -</list> -</para> - -</section> - - -<section id="cryptokey" name="CryptoKey"> - -<para> -<table width="100%"> -<tr><td><link id="cryptokey_alg"><literal>CryptoKey.algorithm</literal></link></td></tr> -<tr><td><link id="cryptokey_extractable"><literal>CryptoKey.extractable</literal></link></td></tr> -<tr><td><link id="cryptokey_type"><literal>CryptoKey.type</literal></link></td></tr> -<tr><td><link id="cryptokey_usages"><literal>CryptoKey.usages</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>CryptoKey</literal> object -represents a cryptographic <literal>key</literal> obtained -from one of the <literal>SubtleCrypto</literal> methods: -<link id="crypto_subtle_generate_key"><literal>сrypto.subtle.generateKey()</literal></link>, -<link id="crypto_subtle_derive_key"><literal>сrypto.subtle.deriveKey()</literal></link>, -<link id="crypto_subtle_import_key"><literal>сrypto.subtle.importKey()</literal></link>. -</para> - -<para> -<list type="tag"> - -<tag-name id="cryptokey_alg"><literal>CryptoKey.algorithm</literal></tag-name> -<tag-desc> -returns an object describing the algorithm for which this key can be used -and any associated extra parameters -(since <link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -read-only -</tag-desc> - -<tag-name id="cryptokey_extractable"><literal>CryptoKey.extractable</literal></tag-name> -<tag-desc> -a boolean value, <literal>true</literal> if the key can be exported -(since <link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -read-only -</tag-desc> - -<tag-name id="cryptokey_type"><literal>CryptoKey.type</literal></tag-name> -<tag-desc> -a string value that indicates which kind of key is represented by the object, -read-only. -Possible values: -<list type="tag"> - -<tag-name><literal>secret</literal></tag-name> -<tag-desc> -This key is a secret key for use with a symmetric algorithm. -</tag-desc> - -<tag-name><literal>private</literal></tag-name> -<tag-desc> -This key is the private half of an asymmetric algorithm's -<link id="cryptokeypair"><literal>CryptoKeyPair</literal></link> -</tag-desc> - -<tag-name><literal>public</literal></tag-name> -<tag-desc> -This key is the public half of an asymmetric algorithm's -<link id="cryptokeypair"><literal>CryptoKeyPair</literal></link>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="cryptokey_usages"><literal>CryptoKey.usages</literal></tag-name> -<tag-desc> -An array of strings indicating what this key can be used for -(since <link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -read-only. -Possible array values: -<list type="tag"> - -<tag-name><literal>encrypt</literal></tag-name> -<tag-desc> -key for encrypting messages -</tag-desc> - -<tag-name><literal>decrypt</literal></tag-name> -<tag-desc> -key for decrypting messages -</tag-desc> - -<tag-name><literal>sign</literal></tag-name> -<tag-desc> -key for signing messages -</tag-desc> - -<tag-name><literal>verify</literal></tag-name> -<tag-desc> -key for verifying signatures -</tag-desc> - -<tag-name><literal>deriveKey</literal></tag-name> -<tag-desc> -key for deriving a new key -</tag-desc> - -<tag-name><literal>deriveBits</literal></tag-name> -<tag-desc> -key for deriving bits -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="cryptokeypair" name="CryptoKeyPair"> - -<para> -<table width="100%"> -<tr><td><link id="cryptokeypair_privatekey"><literal>CryptoKeyPair.privateKey</literal></link></td></tr> -<tr><td><link id="cryptokeypair_publickey"><literal>CryptoKeyPair.publicKey</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>CryptoKeyPair</literal> is a dictionary object -of the <link id="builtin_crypto">WebCrypto API</link> -that represents an asymmetric key pair. -</para> - -<para> -<list type="tag"> - -<tag-name id="cryptokeypair_privatekey"><literal>CryptoKeyPair.privateKey</literal></tag-name> -<tag-desc> -A <link id="cryptokey"><literal>CryptoKey</literal></link> object -representing the private key. -</tag-desc> - -<tag-name id="cryptokeypair_publickey"><literal>CryptoKeyPair.publicKey</literal></tag-name> -<tag-desc> -A <link id="cryptokey"><literal>CryptoKey</literal></link> object -representing the public key. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="njs" name="njs"> - -<para> -<table width="100%"> -<tr><td><link id="njs_version"><literal>njs.version</literal></link></td></tr> -<tr><td><link id="njs_version_number"><literal>njs.version_number</literal></link></td></tr> -<tr><td><link id="njs_dump"><literal>njs.dump()</literal></link></td></tr> -<tr><td><link id="njs_memory_stats"><literal>njs.memoryStats</literal></link></td></tr> -<tr><td><link id="njs_on"><literal>njs.on()</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>njs</literal> object is a global object -that represents the current VM instance -(since <link doc="changes.xml" id="njs0.2.0">0.2.0</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="njs_version"><literal>njs.version</literal></tag-name> -<tag-desc> -Returns a string with the current version of njs -(for example, “0.7.4”). -</tag-desc> - -<tag-name id="njs_version_number"><literal>njs.version_number</literal></tag-name> -<tag-desc> -Returns a number with the current version of njs. -For example, “0.7.4” is returned as <literal>0x000704</literal> -(since <link doc="changes.xml" id="njs0.7.4">0.7.4</link>). -</tag-desc> - -<tag-name id="njs_dump"><literal>njs.dump(<value>value</value>)</literal></tag-name> -<tag-desc> -Returns the pretty-print string representation for a value. -</tag-desc> - -<tag-name id="njs_memory_stats"><literal>njs.memoryStats</literal></tag-name> -<tag-desc> -Object containing memory statistics for current VM instance -(since <link doc="changes.xml" id="njs0.7.8">0.7.8</link>). -<list type="tag"> - -<tag-name><literal>size</literal></tag-name> -<tag-desc> -amount of memory in bytes njs memory pool claimed from the operating system. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="njs_on"><literal>njs.on(<value>event</value>, -<value>callback</value>)</literal></tag-name> -<tag-desc> -Registers a callback for the specified VM event -(since <link doc="changes.xml" id="njs0.5.2">0.5.2</link>). -An event may be one of the following strings: -<list type="tag"> - -<tag-name><literal>exit</literal></tag-name> -<tag-desc> -is called before the VM is destroyed. -The callback is called without arguments. -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="process" name="process"> - -<para> -<table width="100%"> -<tr><td><link id="process_argv"><literal>process.argv</literal></link></td></tr> -<tr><td><link id="process_env"><literal>process.env</literal></link></td></tr> -<tr><td><link id="process_pid"><literal>process.pid</literal></link></td></tr> -<tr><td><link id="process_ppid"><literal>process.ppid</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>process</literal> object is a global object -that provides information about the current process -(<link doc="changes.xml" id="njs0.3.3">0.3.3</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="process_argv"><literal>process.argv</literal></tag-name> -<tag-desc> -Returns an array that contains the command line arguments -passed when the current process was launched. -</tag-desc> - -<tag-name id="process_env"><literal>process.env</literal></tag-name> -<tag-desc> -Returns an object containing the user environment. -<note> -By default, nginx removes all environment variables inherited -from its parent process except the TZ variable. -Use the <link doc="../ngx_core_module.xml" id="env"/> directive -to preserve some of the inherited variables. -</note> -</tag-desc> - -<tag-name id="process_pid"><literal>process.pid</literal></tag-name> -<tag-desc> -Returns the PID of the current process. -</tag-desc> - -<tag-name id="process_ppid"><literal>process.ppid</literal></tag-name> -<tag-desc> -Returns the PID of the current parent process. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="string" name="String"> - -<para> -By default all strings in njs are Unicode strings. -They correspond to ECMAScript strings that contain Unicode characters. -Before <link doc="changes.xml" id="njs0.8.0">0.8.0</link>, -byte strings were also supported. -</para> - -<section id="byte_string" name="Byte strings"> - -<para> -<note> -Since <link doc="changes.xml" id="njs0.8.0">0.8.0</link>, -the support for byte strings and byte string methods were removed. -When working with byte sequence, -the <link id="buffer">Buffer</link> object -and <literal>Buffer</literal> properties, such as -<link id="r_request_buffer"><literal>r.requestBuffer</literal></link>, -<link id="r_raw_variables"><literal>r.rawVariables</literal></link>, -should be used. -</note> -</para> - -<para> -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 <link id="string_toutf8">toUTF8()</link> method serializes -a Unicode string to a byte string using UTF-8 encoding: -<example> ->> '£'.toUTF8().toString('hex') -'c2a3' /* C2 A3 is the UTF-8 representation of 00A3 ('£') code point */ -</example> -The <link id="string_tobytes">toBytes()</link> method serializes -a Unicode string with code points up to 255 into a byte string, -otherwise, <literal>null</literal> is returned: -<example> ->> '£'.toBytes().toString('hex') -'a3' /* a3 is a byte equal to 00A3 ('£') code point */ -</example> - -<list type="tag"> - -<tag-name id="string_bytesfrom"><literal>String.bytesFrom(<value>array</value> -| <value>string</value>, <value>encoding</value>)</literal></tag-name> -<tag-desc> -The method was made obsolete in -<link doc="changes.xml" id="njs0.4.4">0.4.4</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -The <literal>Buffer.from</literal> method should be used instead: -<example> ->> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString() -'buffer' - ->> Buffer.from('YnVmZmVy', 'base64').toString() -'buffer' -</example> -Before <link doc="changes.xml" id="njs0.4.4">0.4.4</link>, -created a byte string either from an array that contained octets, -or from an encoded string -(<link doc="changes.xml" id="njs0.2.3">0.2.3</link>), -the encoding could be -<literal>hex</literal>, -<literal>base64</literal>, and -<literal>base64url</literal>. -</tag-desc> - -<tag-name id="string_frombytes"><literal>String.prototype.fromBytes(<value>start</value>[, -<value>end</value>])</literal></tag-name> -<tag-desc> -the property was made obsolete in -<link doc="changes.xml" id="njs0.7.7">0.7.7</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -Before <link doc="changes.xml" id="njs0.7.7">0.7.7</link>, -returned a new Unicode string from a byte string -where each byte was replaced with a corresponding Unicode code point. -</tag-desc> - -<tag-name id="string_fromutf8"><literal>String.prototype.fromUTF8(<value>start</value>[, -<value>end</value>])</literal></tag-name> -<tag-desc> -the property was made obsolete in -<link doc="changes.xml" id="njs0.7.7">0.7.7</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -The <link id="textedeoder"><literal>TextDecoder</literal></link> method -should be used instead. -Before <link doc="changes.xml" id="njs0.7.7">0.7.7</link>, -converted a byte string containing a valid UTF-8 string -into a Unicode string, -otherwise <literal>null</literal> was returned. -</tag-desc> - -<tag-name id="string_tobytes"><literal>String.prototype.toBytes(<value>start</value>[, -<value>end</value>])</literal></tag-name> -<tag-desc> -the property was made obsolete in -<link doc="changes.xml" id="njs0.7.7">0.7.7</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -Before <link doc="changes.xml" id="njs0.7.7">0.7.7</link>, -serialized a Unicode string to a byte string, -returned <literal>null</literal> if a character larger than 255 was -found in the string. -</tag-desc> - -<tag-name id="string_tostring"><literal>String.prototype.toString(<value>encoding</value>)</literal></tag-name> -<tag-desc> -<para> -the property was made obsolete in -<link doc="changes.xml" id="njs0.7.7">0.7.7</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -Before <link doc="changes.xml" id="njs0.7.7">0.7.7</link>, -encoded a string to -<literal>hex</literal>, -<literal>base64</literal>, or -<literal>base64url</literal>: -<example> ->> 'αβγδ'.toString('base64url') -'zrHOss6zzrQ' -</example> -Before version <link doc="changes.xml" id="njs0.4.3">0.4.3</link>, -only a <link id="string_tobytes">byte string</link> could be encoded: -<example> ->> 'αβγδ'.toUTF8().toString('base64url') -'zrHOss6zzrQ' -</example> -</para> -</tag-desc> - -<tag-name id="string_toutf8"><literal>String.prototype.toUTF8(<value>start</value>[, -<value>end</value>])</literal></tag-name> -<tag-desc> -the property was made obsolete in -<link doc="changes.xml" id="njs0.7.7">0.7.7</link> -and was removed in <link doc="changes.xml" id="njs0.8.0">0.8.0</link>. -The <link id="textencoder"><literal>TextEncoder</literal></link> method -should be used instead. -Before <link doc="changes.xml" id="njs0.7.7">0.7.7</link>, -serialized a Unicode string -to a byte string using UTF-8 encoding: -<example> ->> 'αβγδ'.toUTF8().length -8 ->> 'αβγδ'.length -4 -</example> -</tag-desc> - -</list> -</para> - -</section> - -</section> - -</section> - - -<section id="webapi" name="web API"> - - -<section id="textdecoder" name="Text Decoder"> - -<para> -<table width="100%"> -<tr><td><link id="textdecoder_constructor"><literal>TextDecoder()</literal></link></td></tr> -<tr><td><link id="textdecoder_encoding"><literal>TextDecoder.prototype.encoding</literal></link></td></tr> -<tr><td><link id="textdecoder_fatal"><literal>TextDecoder.prototype.fatal</literal></link></td></tr> -<tr><td><link id="textdecoder_ignorebom"><literal>TextDecoder.prototype.ignoreBOM</literal></link></td></tr> -<tr><td><link id="textdecoder_decode"><literal>TextDecoder.prototype.decode()</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>TextDecoder</literal> -produces a stream of code points -from a stream of bytes -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="textdecoder_constructor"><literal>TextDecoder([[<value>encoding</value>], -<value>options</value>])</literal></tag-name> -<tag-desc> -Creates a new <literal>TextDecoder</literal> object -for specified <literal>encoding</literal>, -currently, only UTF-8 is supported. -The <literal>options</literal> is -<literal>TextDecoderOptions</literal> dictionary with the property: - -<list type="tag"> - -<tag-name><literal>fatal</literal></tag-name> -<tag-desc> -boolean flag indicating if -<link id="textdecoder_decode"><literal>TextDecoder.decode()</literal></link> -must throw the <value>TypeError</value> exception when -a coding error is found, by default is <literal>false</literal>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="textdecoder_encoding"><literal>TextDecoder.prototype.encoding</literal></tag-name> -<tag-desc> -Returns a string with the name of the encoding used by -<link id="textdecoder"><literal>TextDecoder()</literal></link>, -read-only. -</tag-desc> - -<tag-name id="textdecoder_fatal"><literal>TextDecoder.prototype.fatal</literal></tag-name> -<tag-desc> -boolean flag, <literal>true</literal> if -the error mode is fatal, -read-only. -</tag-desc> - -<tag-name id="textdecoder_ignorebom"><literal>TextDecoder.prototype.ignoreBOM</literal></tag-name> -<tag-desc> -boolean flag, <literal>true</literal> if -the byte order marker is ignored, -read-only. -</tag-desc> - -<tag-name id="textdecoder_decode"><literal>TextDecoder.prototype.decode(<value>buffer</value>, -[<value>options</value>])</literal></tag-name> -<tag-desc> -Returns a string with the text -decoded from the <literal>buffer</literal> by -<link id="textdecoder"><literal>TextDecoder()</literal></link>. -The buffer can be <literal>ArrayBuffer</literal>. -The <literal>options</literal> is -<literal>TextDecodeOptions</literal> dictionary with the property: - -<list type="tag"> - -<tag-name><literal>stream</literal></tag-name> -<tag-desc> -boolean flag indicating if -additional data will follow in subsequent calls to <literal>decode()</literal>: -<literal>true</literal> if processing the data in chunks, and -<literal>false</literal> for the final chunk -or if the data is not chunked. -By default is <literal>false</literal>. -</tag-desc> - -</list> -<example> ->> (new TextDecoder()).decode(new Uint8Array([206,177,206,178])) -αβ -</example> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="textencoder" name="Text Encoder"> - -<para> -<table width="100%"> -<tr><td><link id="textencoder_constructor"><literal>TextEncoder()</literal></link></td></tr> -<tr><td><link id="textencoder_encode"><literal>TextEncoder.prototype.encode()</literal></link></td></tr> -<tr><td><link id="textencoder_encodeinto"><literal>TextEncoder.prototype.encodeInto()</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>TextEncoder</literal> object -produces a byte stream with UTF-8 encoding -from a stream of code points -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="textencoder_constructor"><literal>TextEncoder()</literal></tag-name> -<tag-desc> -Returns a newly constructed <literal>TextEncoder</literal> -that will generate a byte stream with UTF-8 encoding. -</tag-desc> - -<tag-name id="textencoder_encode"><literal>TextEncoder.prototype.encode(<value>string</value>)</literal></tag-name> -<tag-desc> -Encodes <literal>string</literal> into a <literal>Uint8Array</literal> -with UTF-8 encoded text. -</tag-desc> - -<tag-name id="textencoder_encodeinto"><literal>TextEncoder.prototype.encodeInto(<value>string</value>, -<value>uint8Array</value>)</literal></tag-name> -<tag-desc> -Encodes a <literal>string</literal> to UTF-8, -puts the result into destination <literal>Uint8Array</literal>, and -returns a dictionary object that shows the progress of the encoding. -The dictionary object contains two members: - -<list type="tag"> - -<tag-name><literal>read</literal></tag-name> -<tag-desc> -the number of UTF-16 units of code from the source <literal>string</literal> -converted to UTF-8 -</tag-desc> - -<tag-name><literal>written</literal></tag-name> -<tag-desc> -the number of bytes modified in the destination <literal>Uint8Array</literal> -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -</section> - -</section> - - -<section id="njs_api_timers" name="timers"> - -<para> -<table width="100%"> -<tr><td><link id="cleartimeout"><literal>clearTimeout()</literal></link></td></tr> -<tr><td><link id="settimeout"><literal>setTimeout()</literal></link></td></tr> -</table> -</para> - -<para> -<list type="tag"> - -<tag-name id="cleartimeout"><literal>clearTimeout(<value>timeout</value>)</literal></tag-name> -<tag-desc> -Cancels a <literal>timeout</literal> object -created by <link id="settimeout"><literal>setTimeout()</literal></link>. -</tag-desc> - -<tag-name id="settimeout"><literal>setTimeout(<value>function</value>, -<value>milliseconds</value>[, -<value>argument1</value>, -<value>argumentN</value>])</literal></tag-name> -<tag-desc> -Calls a <literal>function</literal> -after a specified number of <literal>milliseconds</literal>. -One or more optional <literal>arguments</literal> -can be passed to the specified function. -Returns a <literal>timeout</literal> object. -<example> -function handler(v) -{ - // ... -} - -t = setTimeout(handler, 12); - -// ... - -clearTimeout(t); -</example> -</tag-desc> - -</list> -</para> - -<section id="njs_global_functions" name="Global functions"> - -<para> -<table width="100%"> -<tr><td><link id="atob"><literal>atob()</literal></link></td></tr> -<tr><td><link id="btoa"><literal>btoa()</literal></link></td></tr> -</table> -</para> - -<para> -<list type="tag"> - -<tag-name id="atob"><literal>atob(<value>encodedData</value>)</literal></tag-name> -<tag-desc> -Decodes a string of data which has been encoded -using <literal>Base64</literal> encoding. -The <literal>encodedData</literal> parameter is a binary string -that contains Base64-encoded data. -Returns a string that contains decoded data from <literal>encodedData</literal>. -<para> -The similar <link id="btoa"><literal>btoa()</literal></link> method -can be used to encode and transmit data -which may otherwise cause communication problems, -then transmit it and use the <literal>atob()</literal> method -to decode the data again. -For example, you can encode, transmit, and decode control characters -such as ASCII values <literal>0</literal> through <literal>31</literal>. -<example> -const encodedData = btoa("text to encode"); // encode a string -const decodedData = atob(encodedData); // decode the string -</example> -</para> -</tag-desc> - -<tag-name id="btoa"><literal>btoa(<value>stringToEncode</value>)</literal></tag-name> -<tag-desc> -Creates a Base64-encoded ASCII string from a binary string. -The <literal>stringToEncode</literal> parameter is a binary string to encode. -Returns an ASCII string containing the Base64 representation of -<literal>stringToEncode</literal>. -<para> -The method can be used to encode data -which may otherwise cause communication problems, transmit it, -then use the <link id="atob"><literal>atob()</literal></link> method -to decode the data again. -For example, you can encode control characters -such as ASCII values <literal>0</literal> through <literal>31</literal>. -<example> -const encodedData = btoa("text to encode"); // encode a string -const decodedData = atob(encodedData); // decode the string -</example> -</para> -</tag-desc> - -</list> -</para> - -</section> - -</section> - - -<section id="builtin_modules" name="built-in modules"> - - -<section id="buffer" name="Buffer"> - -<para> -<table width="100%"> -<tr><td><link id="buffer_alloc"><literal>Buffer.alloc()</literal></link></td></tr> -<tr><td><link id="buffer_alloc_unsafe"><literal>Buffer.allocUnsafe()</literal></link></td></tr> -<tr><td><link id="buffer_bytelength"><literal>Buffer.byteLength()</literal></link></td></tr> -<tr><td><link id="buffer_compare"><literal>Buffer.compare()</literal></link></td></tr> -<tr><td><link id="buffer_concat"><literal>Buffer.concat()</literal></link></td></tr> -<tr><td><link id="buffer_from_array"><literal>Buffer.from(array)</literal></link></td></tr> -<tr><td><link id="buffer_from_arraybuffer"><literal>Buffer.from(arrayBuffer)</literal></link></td></tr> -<tr><td><link id="buffer_from_buffer"><literal>Buffer.from(buffer)</literal></link></td></tr> -<tr><td><link id="buffer_from_object"><literal>Buffer.from(object)</literal></link></td></tr> -<tr><td><link id="buffer_from_string"><literal>Buffer.from(string)</literal></link></td></tr> -<tr><td><link id="buffer_is_buffer"><literal>Buffer.isBuffer()</literal></link></td></tr> -<tr><td><link id="buffer_is_encoding"><literal>Buffer.isEncoding()</literal></link></td></tr> -<tr><td><link id="buf_index"><literal>buffer[]</literal></link></td></tr> -<tr><td><link id="buf_buffer"><literal>buf.buffer</literal></link></td></tr> -<tr><td><link id="buf_byte_offset"><literal>buf.byteOffset</literal></link></td></tr> -<tr><td><link id="buf_compare"><literal>buf.compare()</literal></link></td></tr> -<tr><td><link id="buf_copy"><literal>buf.copy()</literal></link></td></tr> -<tr><td><link id="buf_equals"><literal>buf.equals()</literal></link></td></tr> -<tr><td><link id="buf_fill"><literal>buf.fill()</literal></link></td></tr> -<tr><td><link id="buf_includes"><literal>buf.includes()</literal></link></td></tr> -<tr><td><link id="buf_indexof"><literal>buf.indexOf()</literal></link></td></tr> -<tr><td><link id="buf_lastindexof"><literal>buf.lastIndexOf()</literal></link></td></tr> -<tr><td><link id="buf_length"><literal>buf.length</literal></link></td></tr> -<tr><td><link id="buf_readintbe"><literal>buf.readIntBE()</literal></link></td></tr> -<tr><td><link id="buf_readintle"><literal>buf.readIntLE()</literal></link></td></tr> -<tr><td><link id="buf_readuintbe"><literal>buf.readUIntBE()</literal></link></td></tr> -<tr><td><link id="buf_readuintle"><literal>buf.readUIntLE()</literal></link></td></tr> -<tr><td><link id="buf_readdobulebe"><literal>buf.readDoubleBE</literal></link></td></tr> -<tr><td><link id="buf_readdobulele"><literal>buf.readDoubleLE()</literal></link></td></tr> -<tr><td><link id="buf_readfloatbe"><literal>buf.readFloatBE()</literal></link></td></tr> -<tr><td><link id="buf_readfloatle"><literal>buf.readFloatLE()</literal></link></td></tr> -<tr><td><link id="buf_subarray"><literal>buf.subarray()</literal></link></td></tr> -<tr><td><link id="buf_slice"><literal>buf.slice()</literal></link></td></tr> -<tr><td><link id="buf_swap16"><literal>buf.swap16()</literal></link></td></tr> -<tr><td><link id="buf_swap32"><literal>buf.swap32()</literal></link></td></tr> -<tr><td><link id="buf_swap64"><literal>buf.swap64()</literal></link></td></tr> -<tr><td><link id="buf_tojson"><literal>buf.toJSON()</literal></link></td></tr> -<tr><td><link id="buf_tostring"><literal>buf.toString()</literal></link></td></tr> -<tr><td><link id="buf_write"><literal>buf.write()</literal></link></td></tr> -<tr><td><link id="buf_writeintbe"><literal>buf.writeIntBE()</literal></link></td></tr> -<tr><td><link id="buf_writeintle"><literal>buf.writeIntLE()</literal></link></td></tr> -<tr><td><link id="buf_writeuintbe"><literal>buf.writeUIntBE()</literal></link></td></tr> -<tr><td><link id="buf_writeuintle"><literal>buf.writeUIntLE()</literal></link></td></tr> -<tr><td><link id="buf_writedoublebe"><literal>buf.writeDoubleBE()</literal></link></td></tr> -<tr><td><link id="buf_writedoublele"><literal>buf.writeDoubleLE()</literal></link></td></tr> -<tr><td><link id="buf_writefloatbe"><literal>buf.writeFloatBE()</literal></link></td></tr> -<tr><td><link id="buf_writefloatle"><literal>buf.writeFloatLE()</literal></link></td></tr> -</table> -</para> - -<para> -<list type="tag"> - -<tag-name id="buffer_alloc"><literal>Buffer.alloc(<value>size</value>[, -<value>fill</value>[, -<value>encoding</value>]]))</literal></tag-name> -<tag-desc> -<para> -Allocates a new Buffer of a specified <value>size</value>. -If <value>fill</value> is not specified, the Buffer will be zero-filled. -If <value>fill</value> is specified, -the allocated Buffer will be initialized by calling -<link id="buf_fill"><literal>buf.fill(fill)</literal></link>. -If <value>fill</value> and <value>encoding</value> are specified, -the allocated Buffer will be initialized by calling -<link id="buf_fill"><literal>buf.fill(fill, -encoding)</literal></link>. -</para> - -<para> -The <value>fill</value> parameter may be a -<value>string</value>, -<value>Buffer</value>, -<value>Uint8Array</value>, or -<value>integer</value>. -</para> -</tag-desc> - -<tag-name id="buffer_alloc_unsafe"><literal>Buffer.allocUnsafe(<value>size</value>)</literal></tag-name> -<tag-desc> -<para> -The same as -<link id="buffer_alloc"><literal>Buffer.alloc()</literal></link>, -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. -</para> -</tag-desc> - -<tag-name id="buffer_bytelength"><literal>Buffer.byteLength(<value>value</value>[, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -Returns the byte length of a specified value, -when encoded using <value>encoding</value>. -The value can be a -<literal>string</literal>, -<literal>Buffer</literal>, -<literal>TypedArray</literal>, -<literal>DataView</literal>, or -<literal>ArrayBuffer</literal>. -If the value is a <value>string</value>, -the <literal>encoding</literal> parameter is its encoding, can be -<value>utf8</value>, -<value>hex</value>, -<value>base64</value>, -<value>base64url</value>; -by default is <value>utf8</value>. -</tag-desc> - -<tag-name id="buffer_compare"><literal>Buffer.compare(<value>buffer1</value>, -<value>buffer2</value>)</literal></tag-name> -<tag-desc> -Compares <value>buffer1</value> with <value>buffer2</value> -when sorting arrays of Buffer instances. -Returns -<literal>0</literal> if -<value>buffer1</value> is the same as <value>buffer2</value>, -<literal>1</literal> if -<value>buffer2</value> should come before <value>buffer1</value> when sorted, or -<literal>-1</literal> if -<value>buffer2</value> should come after <value>buffer1</value> when sorted. -</tag-desc> - -<tag-name id="buffer_concat"><literal>Buffer.concat(<value>list</value>[, -<value>totalLength</value>])</literal></tag-name> -<tag-desc> -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 <value>totalLength</value> is not specified, -it is calculated from the Buffer instances in list by adding their lengths. -If <value>totalLength</value> is specified, -it is coerced to an unsigned integer. -If the combined length of the Buffers in list exceeds -<value>totalLength</value>, -the result is truncated to <value>totalLength</value>. -</tag-desc> - -<tag-name id="buffer_from_array"><literal>Buffer.from(<value>array</value>)</literal></tag-name> -<tag-desc> -Allocates a new Buffer using an array of bytes -in the range <literal>0</literal> – <literal>255</literal>. -Array entries outside that range will be truncated. -</tag-desc> - -<tag-name id="buffer_from_arraybuffer"><literal>Buffer.from(<value>arrayBuffer</value>, -<value>byteOffset</value>[, -<value>length</value>]])</literal></tag-name> -<tag-desc> -Creates a view of the <value>ArrayBuffer</value> -without copying the underlying memory. -The optional <value>byteOffset</value> and <value>length</value> arguments -specify a memory range within the <value>arrayBuffer</value> -that will be shared by the Buffer. -</tag-desc> - -<tag-name id="buffer_from_buffer"><literal>Buffer.from(<value>buffer</value>)</literal></tag-name> -<tag-desc> -Copies the passed buffer data onto a new Buffer instance. -</tag-desc> - -<tag-name id="buffer_from_object"><literal>Buffer.from(<value>object</value>[, -<value>offsetOrEncoding</value>[, -<value>length</value>]])</literal></tag-name> -<tag-desc> -For objects whose <literal>valueOf()</literal> function -returns a value not strictly equal to object, -returns -<literal>Buffer.from(object.valueOf()</literal>, -<literal>offsetOrEncoding</literal>, -<literal>length</literal>). -</tag-desc> - -<tag-name id="buffer_from_string"><literal>Buffer.from(<value>string</value>[, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -Creates a new Buffer with a <value>string</value>. -The <value>encoding</value> parameter identifies the character encoding -to be used when converting a string into bytes. -The encoding can be -<literal>utf8</literal>, -<literal>hex</literal>, -<literal>base64</literal>, -<literal>base64url</literal>; -by default is <literal>utf8</literal>. -</tag-desc> - -<tag-name id="buffer_is_buffer"><literal>Buffer.isBuffer(<value>object</value>)</literal></tag-name> -<tag-desc> -A boolean value, -returns <literal>true</literal> if <value>object</value> is a Buffer. -</tag-desc> - -<tag-name id="buffer_is_encoding"><literal>Buffer.isEncoding(<value>encoding</value>)</literal></tag-name> -<tag-desc> -A boolean value, -returns <literal>true</literal> -if encoding is the name of a supported character encoding. -</tag-desc> - -<tag-name id="buf_index"><literal>buffer[<value>index</value>]</literal></tag-name> -<tag-desc> -The index operator that can be used to get and set the octet -at position <literal>index</literal> in <literal>buffer</literal>. -The values refer to individual bytes, -so the legal value range is between 0 and 255 (decimal). -</tag-desc> - -<tag-name id="buf_buffer"><literal>buf.buffer</literal></tag-name> -<tag-desc> -The underlying <literal>ArrayBuffer</literal> object -based on which this Buffer object is created. -</tag-desc> - -<tag-name id="buf_byte_offset"><literal>buf.byteOffset</literal></tag-name> -<tag-desc> -An integer, -specifying the <literal>byteOffset</literal> of the Buffers -underlying <literal>ArrayBuffer</literal> object. -</tag-desc> - -<tag-name id="buf_compare"><literal>buf.compare(<value>target</value>[, -<value>targetStart</value>[, -<value>targetEnd</value>[, -<value>sourceStart</value>[, -<value>sourceEnd</value>]]]])</literal></tag-name> -<tag-desc> -Compares buffer with <value>target</value> and returns a number -indicating whether buffer comes before, after, or is the same -as <value>target</value> in sort order. -Comparison is based on the actual sequence of bytes in each Buffer. -The <literal>targetStart</literal> is an integer specifying -the offset within <value>target</value> at which to begin comparison, -by default is 0. -The <literal>targetEnd</literal> is an integer specifying -the offset within <value>target</value> at which to end comparison, -by default is <literal>target.length</literal>. -The <literal>sourceStart</literal> is an integer specifying -the offset within buffer at which to begin comparison, -by default is 0. -The <literal>sourceEnd</literal> is an integer specifying -the offset within buffer at which to end comparison (not inclusive), -by default is <literal>buf.length</literal>. -</tag-desc> - -<tag-name id="buf_copy"><literal>buf.copy(<value>target</value>[, -<value>targetStart</value>[, -<value>sourceStart</value>[, -<value>sourceEnd</value>]]])</literal></tag-name> -<tag-desc> -Copies data from a region of buffer to a region in <value>target</value>, -even if the target memory region overlaps with buffer. -The <literal>target</literal> parameter is a -<value>Buffer</value> or <value>Uint8Array</value> to copy into. - -<para> -The <literal>targetStart</literal> is an integer specifying -the offset within target at which to begin writing, -by default is 0. -The <literal>sourceStart</literal> is an integer specifying -the offset within buffer from which to begin copying, -by default is 0. -The <literal>sourceEnd</literal> is an integer specifying -the offset within buffer at which to stop copying (not inclusive) -by default is <value>buf.length</value>. -</para> -</tag-desc> - -<tag-name id="buf_equals"><literal>buf.equals(<value>otherBuffer</value>)</literal></tag-name> -<tag-desc> -A boolean value, -returns <literal>true</literal> if both Buffer and <value>otherBuffer</value> -have exactly the same bytes. -</tag-desc> - -<tag-name id="buf_fill"><literal>buf.fill(<value>value</value>[, -<value>offset</value>[, -<value>end</value>]][, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -Fills the Buffer with the specified <value>value</value>. -If the <value>offset</value> and <value>end</value> are not specified, -the entire Buffer will be filled. -The <value>value</value> is coerced to <value>uint32</value> if it is not a -<literal>string</literal>, -<literal>Buffer</literal>, or -<literal>integer</literal>. -If the resulting integer is greater than 255, -the Buffer will be filled with <value>value</value> and 255. -</tag-desc> - -<tag-name id="buf_includes"><literal>buf.includes(<value>value</value>[, -<value>byteOffset</value>][, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -Equivalent to -<link id="buf_indexof"><literal>buf.indexOf()</literal></link> -<literal>!== -1</literal>, -returns <literal>true</literal> if the <value>value</value> was found -in Buffer. -</tag-desc> - -<tag-name id="buf_indexof"><literal>buf.indexOf(<value>value</value>[, -<value>byteOffset</value>][, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -Returns an integer which is the index of the first occurrence of -<value>value</value> in Buffer, or <value>-1</value> -if Buffer does not contain value. -The <value>value</value> can be a -<literal>string</literal> with specified <value>encoding</value> -(by default <value>utf8</value>), -<literal>Buffer</literal>, -<literal>Unit8Array</literal>, -or a number between 0 and 255. -</tag-desc> - -<tag-name id="buf_lastindexof"><literal>buf.lastIndexOf(<value>value</value>[, -<value>byteOffset</value>][, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -The same as -<link id="buf_indexof"><literal>buf.indexOf()</literal></link>, -except the last occurrence of the <value>value</value> is found -instead of the first occurrence. -The <value>value</value> can be a string, Buffer, or -integer between 1 and 255. -If the <value>value</value> is an empty string or empty Buffer, -<literal>byteOffset</literal> will be returned. -</tag-desc> - -<tag-name id="buf_length"><literal>buf.length</literal></tag-name> -<tag-desc> -Returns the number of bytes in Buffer. -</tag-desc> - -<tag-name id="buf_readintbe"><literal>buf.readIntBE(<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Reads the <value>byteLength</value> from <literal>buf</literal> -at the specified <value>offset</value> -and interprets the result as a big-endian, -two's complement signed value supporting up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The similar methods are also supported: -<literal>buf.readInt8([offset])</literal>, -<literal>buf.readInt16BE([offset])</literal>, -<literal>buf.readInt32BE([offset])</literal>. -</para> -</tag-desc> - -<tag-name id="buf_readintle"><literal>buf.readIntLE(<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Reads the <value>byteLength</value> from <literal>buf</literal> -at the specified <value>offset</value> -and interprets the result as a little-endian, -two's complement signed value supporting up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The similar methods are also supported: -<literal>buf.readInt8([offset])</literal>, -<literal>buf.readInt16LE([offset])</literal>, -<literal>buf.readInt32LE([offset])</literal>. -</para> -</tag-desc> - -<tag-name id="buf_readuintbe"><literal>buf.readUIntBE(<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Reads the <value>byteLength</value> from <literal>buf</literal> -at the specified <value>offset</value> -and interprets the result as a big-endian -integer supporting up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The similar methods are also supported: -<literal>buf.readUInt8([offset])</literal>, -<literal>buf.readUInt16BE([offset])</literal>, -<literal>buf.readUInt32BE([offset])</literal>. -</para> -</tag-desc> - -<tag-name id="buf_readuintle"><literal>buf.readUIntLE(<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Reads the <value>byteLength</value> from <literal>buf</literal> -at the specified <value>offset</value> -and interprets the result as a little-endian -integer supporting up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The similar methods are also supported: -<literal>buf.readUInt8([offset])</literal>, -<literal>buf.readUInt16LE([offset])</literal>, -<literal>buf.readUInt32LE([offset])</literal>. -</para> -</tag-desc> - -<tag-name id="buf_readdobulebe"><literal>buf.readDoubleBE</literal>([<value>offset</value>])</tag-name> -<tag-desc> -Reads a 64-bit, big-endian double from <literal>buf</literal> -at the specified <value>offset</value>. -</tag-desc> - -<tag-name id="buf_readdobulele"><literal>buf.readDoubleLE</literal>([<value>offset</value>])</tag-name> -<tag-desc> -Reads a 64-bit, little-endian double from <literal>buf</literal> -at the specified <value>offset</value>. -</tag-desc> - -<tag-name id="buf_readfloatbe"><literal>buf.readFloatBE</literal>([<value>offset</value>])</tag-name> -<tag-desc> -Reads a 32-bit, big-endian float from <literal>buf</literal> -at the specified <value>offset</value>. -</tag-desc> - -<tag-name id="buf_readfloatle"><literal>buf.readFloatLE</literal>([<value>offset</value>])</tag-name> -<tag-desc> -Reads a 32-bit, little-endian float from <literal>buf</literal> -at the specified <value>offset</value>. -</tag-desc> - -<tag-name id="buf_subarray"><literal>buf.subarray([<value>start</value>[, -<value>end</value>]])</literal></tag-name> -<tag-desc> -Returns a new <literal>buf</literal> -that references the same memory as the original, -but offset and cropped by -<value>start</value> and <value>end</value>. -If <value>end</value> is greater than -<link id="buf_length"><literal>buf.length</literal></link>, -the same result as that of end equal to -<link id="buf_length"><literal>buf.length</literal></link> -is returned. -</tag-desc> - -<tag-name id="buf_slice"><literal>buf.slice([<value>start</value>[, -<value>end</value>]])</literal></tag-name> -<tag-desc> -Returns a new <literal>buf</literal> -that references the same memory as the original, -but offset and cropped by the -<value>start</value> and <value>end</value> values. -The method is not compatible with the -<literal>Uint8Array.prototype.slice()</literal>, -which is a superclass of Buffer. -To copy the slice, use -<literal>Uint8Array.prototype.slice()</literal>. -</tag-desc> - -<tag-name id="buf_swap16"><literal>buf.swap16</literal>()</tag-name> -<tag-desc> -Interprets <literal>buf</literal> as an array of unsigned 16-bit numbers -and swaps the byte order in-place. -Throws an error if -<link id="buf_length"><literal>buf.length</literal></link> -is not a multiple of 2. -</tag-desc> - -<tag-name id="buf_swap32"><literal>buf.swap32</literal>()</tag-name> -<tag-desc> -Interprets <literal>buf</literal> as an array of unsigned 32-bit numbers -and swaps the byte order in-place. -Throws an error if -<link id="buf_length"><literal>buf.length</literal></link> -is not a multiple of 4. -</tag-desc> - -<tag-name id="buf_swap64"><literal>buf.swap64</literal>()</tag-name> -<tag-desc> -Interprets <literal>buf</literal> as an array of 64-bit numbers -and swaps byte order in-place. -Throws an error if -<link id="buf_length"><literal>buf.length</literal></link> -is not a multiple of 8. -</tag-desc> - -<tag-name id="buf_tojson"><literal>buf.toJSON</literal>()</tag-name> -<tag-desc> -Returns a JSON representation of <literal>buf.</literal> -<literal>JSON.stringify()</literal> -implicitly calls this function when stringifying a Buffer instance. -</tag-desc> - -<tag-name id="buf_tostring"><literal>buf.toString([<value>encoding</value>[, -<value>start</value>[, -<value>end</value>]]])</literal></tag-name> -<tag-desc> -Decodes <literal>buf</literal> to a string -according to the specified character <value>encoding</value> -which can be <value>utf8</value>, -<value>hex</value>, -<value>base64</value>, -<value>base64url</value>. -The <value>start</value> and <value>end</value> parameters -may be passed to decode only a subset of Buffer. -</tag-desc> - -<tag-name id="buf_write"><literal>buf.write(<value>string</value>[, -<value>offset</value>[, -<value>length</value>]][, -<value>encoding</value>])</literal></tag-name> -<tag-desc> -Writes a <value>string</value> to <literal>buf</literal> -at <value>offset</value> -according to the character <value>encoding</value>. -The <value>length</value> 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 <value>encoding</value> can be -<value>utf8</value>, -<value>hex</value>, -<value>base64</value>, -<value>base64url</value>. -</tag-desc> - -<tag-name id="buf_writeintbe"><literal>buf.writeIntBE(<value>value</value>, -<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Writes <value>byteLength</value> bytes of <value>value</value> -to <literal>buf</literal> -at the specified <value>offset</value> as big-endian. -Supports up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The following similar methods are also supported: -<literal>buf.writeInt8</literal>, -<literal>buf.writeInt16BE</literal>, -<literal>buf.writeInt32BE</literal>. -</para> -</tag-desc> - -<tag-name id="buf_writeintle"><literal>buf.writeIntLE(<value>value</value>, -<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Writes <value>byteLength</value> bytes of <value>value</value> -to <literal>buf</literal> -at the specified <value>offset</value> as little-endian. -Supports up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The following similar methods are also supported: -<literal>buf.writeInt8</literal>, -<literal>buf.writeInt16LE</literal>, -<literal>buf.writeInt32LE</literal>. -</para> -</tag-desc> - -<tag-name id="buf_writeuintbe"><literal>buf.writeUIntBE(<value>value</value>, -<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Writes <value>byteLength</value> bytes of <value>value</value> -to <literal>buf</literal> -at the specified <value>offset</value> as big-endian. -Supports up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The following similar methods are also supported: -<literal>buf.writeUInt8</literal>, -<literal>buf.writeUInt16BE</literal>, -<literal>buf.writeUInt32BE</literal>. -</para> -</tag-desc> - -<tag-name id="buf_writeuintle"><literal>buf.writeUIntLE(<value>value</value>, -<value>offset</value>, -<value>byteLength</value>)</literal></tag-name> -<tag-desc> -Writes <value>byteLength</value> bytes of <value>value</value> -to <literal>buf</literal> -at the specified <value>offset</value> as little-endian. -Supports up to 48 bits of accuracy. -The <value>byteLength</value> parameter is an integer between 1 and 6 -specifying the number of bytes to read. -<para> -The following similar methods are also supported: -<literal>buf.writeUInt8</literal>, -<literal>buf.writeUInt16LE</literal>, -<literal>buf.writeUInt32LE</literal>. -</para> -</tag-desc> - -<tag-name id="buf_writedoublebe"><literal>buf.writeDoubleBE(<value>value</value>, -[<value>offset</value>])</literal></tag-name> -<tag-desc> -Writes the <value>value</value> to <literal>buf</literal> -at the specified <value>offset</value> as big-endian. -</tag-desc> - -<tag-name id="buf_writedoublele"><literal>buf.writeDoubleLE(<value>value</value>, -[<value>offset</value>])</literal></tag-name> -<tag-desc> -Writes the <value>value</value> to <literal>buf</literal> -at the specified <value>offset</value> as little-endian. -</tag-desc> - -<tag-name id="buf_writefloatbe"><literal>buf.writeFloatBE(<value>value</value>, -[<value>offset</value>])</literal></tag-name> -<tag-desc> -Writes the <value>value</value> to <literal>buf</literal> -at the specified <value>offset</value> as big-endian. -</tag-desc> - -<tag-name id="buf_writefloatle"><literal>buf.writeFloatLE(<value>value</value>, -[<value>offset</value>])</literal></tag-name> -<tag-desc> -Writes the <value>value</value> to <literal>buf</literal> -at the specified <value>offset</value> as little-endian. -</tag-desc> - -</list> -</para> - -</section> - - -<section id="crypto" name="Crypto"> - -<para> -<table width="100%"> -<tr><td><link id="crypto_createhash"><literal>crypto.createHash()</literal></link></td></tr> -<tr><td><link id="crypto_createhmac"><literal>crypto.createHmac()</literal></link></td></tr> -</table> -</para> - -<para> -<note> -Since <link doc="changes.xml" id="njs0.7.0">0.7.0</link>, -extended crypto API is available as a global -<link id="builtin_crypto">crypto</link> object. -</note> -The Crypto module provides cryptographic functionality support. -The Crypto module object is returned by <literal>require('crypto')</literal>. -</para> - -<para> -<list type="tag"> - -<tag-name id="crypto_createhash"><literal>crypto.createHash(<value>algorithm</value>)</literal></tag-name> -<tag-desc> -Creates and returns a <link id="crypto_hash">Hash</link> object -that can be used to generate hash digests -using the given <value>algorithm</value>. -The algorithm can be -<literal>md5</literal>, -<literal>sha1</literal>, and -<literal>sha256</literal>. -</tag-desc> - -<tag-name id="crypto_createhmac"><literal>crypto.createHmac(<value>algorithm</value>, -<value>secret key</value>)</literal></tag-name> -<tag-desc> -Creates and returns an <link id="crypto_hmac">HMAC</link> object that uses -the given <value>algorithm</value> and <value>secret key</value>. -The algorithm can be -<literal>md5</literal>, -<literal>sha1</literal>, and -<literal>sha256</literal>. -</tag-desc> - -</list> -</para> - - -<section id="crypto_hash" name="Hash"> - -<para> -<table width="100%"> -<tr><td><link id="crypto_hash_update"><literal>hash.update()</literal></link></td></tr> -<tr><td><link id="crypto_hash_digest"><literal>hash.digest()</literal></link></td></tr> -</table> -</para> - -<para> -<list type="tag"> - -<tag-name id="crypto_hash_update"><literal>hash.update(<value>data</value>)</literal></tag-name> -<tag-desc> -Updates the hash content with the given <value>data</value>. -</tag-desc> - -<tag-name id="crypto_hash_digest"><literal>hash.digest([<value>encoding</value>])</literal></tag-name> -<tag-desc> -Calculates the digest of all of the data passed using -<literal>hash.update()</literal>. -The encoding can be -<literal>hex</literal>, -<literal>base64</literal>, and -<literal>base64url</literal>. -If encoding is not provided, a Buffer object -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>) is returned. -<note> -Before version (<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -a byte string was returned instead of a Buffer object. -</note> -</tag-desc> - -<tag-name id="crypto_hash_copy"><literal>hash.copy()</literal></tag-name> -<tag-desc> -Makes a copy of the current state of the hash -(since <link doc="changes.xml" id="njs0.7.12">0.7.12</link>). -</tag-desc> - -</list> -</para> - -<para> -<example> ->> var cr = require('crypto') -undefined - ->> cr.createHash('sha1').update('A').update('B').digest('base64url') -'BtlFlCqiamG-GMPiK_GbvKjdK10' -</example> -</para> - -</section> - - -<section id="crypto_hmac" name="HMAC"> - -<para> -<table width="100%"> -<tr><td><link id="crypto_hmac_update"><literal>hmac.update()</literal></link></td></tr> -<tr><td><link id="crypto_hmac_digest"><literal>hmac.digest()</literal></link></td></tr> -</table> -</para> - -<para> -<list type="tag"> - -<tag-name id="crypto_hmac_update"><literal>hmac.update(<value>data</value>)</literal></tag-name> -<tag-desc> -Updates the HMAC content with the given <value>data</value>. -</tag-desc> - -<tag-name id="crypto_hmac_digest"><literal>hmac.digest([<value>encoding</value>])</literal></tag-name> -<tag-desc> -Calculates the HMAC digest of all of the data passed using -<literal>hmac.update()</literal>. -The encoding can be -<literal>hex</literal>, -<literal>base64</literal>, and -<literal>base64url</literal>. -If encoding is not provided, a Buffer object -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>) is returned. -<note> -Before version <link doc="changes.xml" id="njs0.4.4">0.4.4</link>, -a byte string was returned instead of a Buffer object. -</note> -</tag-desc> -</list> -</para> - -<para> -<example> ->> var cr = require('crypto') -undefined - ->> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url') -'Oglm93xn23_MkiaEq_e9u8zk374' -</example> -</para> - -</section> - -</section> - - -<section id="njs_api_fs" name="File System"> - -<para> -<table width="100%"> -<tr><td><link id="fs_accesssync"><literal>fs.accessSync()</literal></link></td></tr> -<tr><td><link id="fs_appendfilesync"><literal>fs.appendFileSync()</literal></link></td></tr> -<tr><td><link id="fs_closesync"><literal>fs.closeSync()</literal></link></td></tr> -<tr><td><link id="fs_existssync"><literal>fs.existsSync()</literal></link></td></tr> -<tr><td><link id="fs_fstatsync"><literal>fs.fstatSync()</literal></link></td></tr> -<tr><td><link id="fs_lstatsync"><literal>fs.lstatSync()</literal></link></td></tr> -<tr><td><link id="fs_mkdirsync"><literal>fs.mkdirSync()</literal></link></td></tr> -<tr><td><link id="fs_opensync"><literal>fs.openSync()</literal></link></td></tr> -<tr><td><link id="fs_promises_open"><literal>fs.promises.open()</literal></link></td></tr> -<tr><td><link id="fs_readdirsync"><literal>fs.readdirSync()</literal></link></td></tr> -<tr><td><link id="fs_readfilesync"><literal>fs.readFileSync()</literal></link></td></tr> -<tr><td><link id="fs_readsync"><literal>fs.readSync()</literal></link></td></tr> -<tr><td><link id="fs_realpathsync"><literal>fs.realpathSync()</literal></link></td></tr> -<tr><td><link id="fs_renamesync"><literal>fs.renameSync()</literal></link></td></tr> -<tr><td><link id="fs_rmdirsync"><literal>fs.rmdirSync()</literal></link></td></tr> -<tr><td><link id="fs_statsync"><literal>fs.statSync()</literal></link></td></tr> -<tr><td><link id="fs_symlinksync"><literal>fs.symlinkSync()</literal></link></td></tr> -<tr><td><link id="fs_unlinksync"><literal>fs.unlinkSync()</literal></link></td></tr> -<tr><td><link id="fs_writefilesync"><literal>fs.writeFileSync()</literal></link></td></tr> -<tr><td><link id="fs_writesync_buf"><literal>fs.writeSync()</literal></link></td></tr> -<tr><td><link id="fs_writesync_str"><literal>fs.writeSync()</literal></link></td></tr> -</table> -</para> - -<para> -<table width="100%"> -<tr><td><link id="fs_dirent"><literal>fs.Dirent</literal></link></td></tr> -<tr><td><link id="fs_filehandle"><literal>fs.FileHandle</literal></link></td></tr> -<tr><td><link id="fs_stats"><literal>fs.Stats</literal></link></td></tr> -<tr><td><link id="access_const"><literal>File Access Constants</literal></link></td></tr> -<tr><td><link id="njs_api_fs_flags"><literal>File System Flags</literal></link></td></tr> -</table> -</para> - -<para> -The File System module provides operations with files. -</para> - -<para> -The module object is returned by <literal>require('fs')</literal>. -Since <link doc="changes.xml" id="njs0.3.9">0.3.9</link>, -promissified versions of file system methods are available through -<literal>require('fs').promises</literal> object: -<example> -> var fs = require('fs').promises; -undefined -> fs.readFile("/file/path").then((data)=>console.log(data)) -<file data> -</example> -<list type="tag"> - -<tag-name id="fs_accesssync"><literal>accessSync(<value>path</value>[, -<value>mode</value>])</literal></tag-name> -<tag-desc> -Synchronously tests permissions for a file or directory -specified in the <literal>path</literal> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -If the check fails, an error will be returned, -otherwise, the method will return undefined. -<list type="tag"> - -<tag-name><literal>mode</literal></tag-name> -<tag-desc> -an optional integer -that specifies the accessibility checks to be performed, -by default is <link id="access_const"><literal>fs.constants.F_OK</literal></link> -<example> -try { - fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK); - console.log('has access'); -} catch (e) { - console.log('no access');) -} -</example> -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_appendfilesync"><literal>appendFileSync(<value>filename</value>, -<value>data</value>[, <value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously appends specified <literal>data</literal> -to a file with provided <literal>filename</literal>. -The <literal>data</literal> is expected to be a string -or a Buffer object (<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -If the file does not exist, it will be created. -The <literal>options</literal> parameter is expected to be -an object with the following keys: -<list type="tag"> - -<tag-name><literal>mode</literal></tag-name> -<tag-desc> -mode option, by default is <literal>0o666</literal> -</tag-desc> - -<tag-name><literal>flag</literal></tag-name> -<tag-desc> -file system <link id="njs_api_fs_flags">flag</link>, -by default is <literal>a</literal> -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_closesync"><literal>closeSync(<value>fd</value>)</literal></tag-name> -<tag-desc> -Closes the <literal>fd</literal> file descriptor represented by an integer -used by the method. -Returns <literal>undefined</literal>. -</tag-desc> - -<tag-name id="fs_existssync"><literal>existsSync(<value>path</value>)</literal></tag-name> -<tag-desc> -Boolean value, returns -<literal>true</literal> if the specified <value>path</value> exists. -(<link doc="changes.xml" id="njs0.8.2">0.8.2</link>) -</tag-desc> - -<tag-name id="fs_fstatsync"><literal>fstatSync(<value>fd</value>)</literal></tag-name> -<tag-desc> -Retrieves the <link id="fs_stats"><literal>fs.Stats</literal></link> object -for the file descriptor -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). -The <literal>fd</literal> parameter is an integer -representing the file descriptor used by the method. -</tag-desc> - -<tag-name id="fs_lstatsync"><literal>lstatSync(<value>path</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously retrieves -the <link id="fs_stats"><literal>fs.Stats</literal></link> object -for the symbolic link referred to by <literal>path</literal> -(<link doc="changes.xml" id="njs0.7.1">0.7.1</link>). -The <literal>options</literal> parameter is expected to be -an object with the following keys: -<list type="tag"> -<tag-name><literal>throwIfNoEntry</literal></tag-name> -<tag-desc> -a boolean value which indicates -whether an exception is thrown if no file system entry exists, -rather than returning <literal>undefined</literal>, -by default is <literal>false</literal>. -</tag-desc> -</list> -</tag-desc> - -<tag-name id="fs_mkdirsync"><literal>mkdirSync(<value>path</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously creates a directory at the specified <literal>path</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>). -The <literal>options</literal> parameter is expected to be an -<literal>integer</literal> that specifies -the <link id="fs_mkdirsync_mode">mode</link>, -or an object with the following keys: -<list type="tag"> - -<tag-name id="fs_mkdirsync_mode"><literal>mode</literal></tag-name> -<tag-desc> -mode option, by default is <literal>0o777</literal>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_opensync"><literal>openSync(<value>path</value>[, -<value>flags</value>[, <value>mode</value>]])</literal></tag-name> -<tag-desc> -Returns an integer -representing the file descriptor for the opened file <literal>path</literal> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). -<list type="tag"> - -<tag-name><literal>flags</literal></tag-name> -<tag-desc> -file system <link id="njs_api_fs_flags">flag</link>, -by default is <literal>r</literal> -</tag-desc> - -<tag-name><literal>mode</literal></tag-name> -<tag-desc> -mode option, by default is <literal>0o666</literal> -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_promises_open"><literal>promises.open(<value>path</value>[, -<value>flags</value>[, <value>mode</value>]])</literal></tag-name> -<tag-desc> -Returns a <link id="fs_filehandle"><literal>FileHandle</literal></link> object -representing the opened file <literal>path</literal> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). -<list type="tag"> - -<tag-name><literal>flags</literal></tag-name> -<tag-desc> -file system <link id="njs_api_fs_flags">flag</link>, -by default is <literal>r</literal> -</tag-desc> - -<tag-name><literal>mode</literal></tag-name> -<tag-desc> -mode option, by default is <literal>0o666</literal> -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_readdirsync"><literal>readdirSync(<value>path</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously reads the contents of a directory -at the specified <literal>path</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>). -The <literal>options</literal> parameter is expected to be -a string that specifies <link id="fs_readdirsync_encoding">encoding</link> -or an object with the following keys: -<list type="tag"> - -<tag-name id="fs_readdirsync_encoding"><literal>encoding</literal></tag-name> -<tag-desc> -encoding, by default is <literal>utf8</literal>. -The encoding can be <literal>utf8</literal> and <literal>buffer</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -</tag-desc> - -<tag-name id="fs_readdirsync_withfiletypes"><literal>withFileTypes</literal></tag-name> -<tag-desc> -if set to <literal>true</literal>, the files array will contain -<link id="fs_dirent"><literal>fs.Dirent</literal></link> objects, -by default is <literal>false</literal>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_readfilesync"><literal>readFileSync(<value>filename</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously returns the contents of the file -with provided <literal>filename</literal>. -The <literal>options</literal> parameter holds -<literal>string</literal> that specifies encoding. -If an encoding is specified, a string is returned, -otherwise, a Buffer object -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>) is returned. -<note> -Before version <link doc="changes.xml" id="njs0.4.4">0.4.4</link>, -a <link id="string_tobytes">byte string</link> was returned -if encoding was not specified. -</note> -Otherwise, <literal>options</literal> is expected to be -an object with the following keys: -<list type="tag"> - -<tag-name><literal>encoding</literal></tag-name> -<tag-desc> -encoding, by default is not specified. -The encoding can be <literal>utf8</literal>, -<literal>hex</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>base64</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>base64url</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -</tag-desc> - -<tag-name><literal>flag</literal></tag-name> -<tag-desc> -file system <link id="njs_api_fs_flags">flag</link>, -by default is <literal>r</literal> -</tag-desc> - -</list> -<example> ->> 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 -</example> -</tag-desc> - -<tag-name id="fs_readsync"><literal>readSync(<value>fd</value>, -<value>buffer</value>, <value>offset</value>[, -<value>length</value>[, <value>position</value>]])</literal></tag-name> -<tag-desc> -Reads the content of a file path using file descriptor <literal>fd</literal>, -returns the number of bytes read -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). - -<list type="tag"> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -the <literal>buffer</literal> value can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> - -<tag-name><literal>offset</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing -the position in buffer to write the data to -</tag-desc> - -<tag-name><literal>length</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing -the number of bytes to read -</tag-desc> - -<tag-name><literal>position</literal></tag-name> -<tag-desc> -specifies where to begin reading from in the file, -the value can be -<literal>integer</literal> or -<literal>null</literal>, -by default is <literal>null</literal>. -If <literal>position</literal> is <literal>null</literal>, -data will be read from the current file position, -and the file position will be updated. -If position is an <literal>integer</literal>, -the file position will be unchanged -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="fs_realpathsync"><literal>realpathSync(<value>path</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously computes the canonical pathname by resolving -<literal>.</literal>, <literal>..</literal> and symbolic links using -<link url="http://man7.org/linux/man-pages/man3/realpath.3.html">realpath(3)</link>. -The <literal>options</literal> 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 -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -</tag-desc> - -<tag-name id="fs_renamesync"><literal>renameSync(<value>oldPath</value>, -<value>newPath</value>)</literal></tag-name> -<tag-desc> -Synchronously changes the name or location of a file from -<literal>oldPath</literal> to <literal>newPath</literal> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>). -<example> ->> var fs = require('fs') -undefined ->> var file = fs.renameSync('hello.txt', 'HelloWorld.txt') -undefined -</example> -</tag-desc> - -<tag-name id="fs_rmdirsync"><literal>rmdirSync(<value>path</value>)</literal></tag-name> -<tag-desc> -Synchronously removes a directory at the specified <literal>path</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>). -</tag-desc> - -<tag-name id="fs_statsync"><literal>statSync(<value>path</value>,[ -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously retrieves -the <link id="fs_stats"><literal>fs.Stats</literal></link> object -for the specified <literal>path</literal> -(<link doc="changes.xml" id="njs0.7.1">0.7.1</link>). -The <literal>path</literal> can be a -<literal>string</literal> or -<literal>buffer</literal>. -The <literal>options</literal> parameter is expected to be -an object with the following keys: -<list type="tag"> -<tag-name><literal>throwIfNoEntry</literal></tag-name> -<tag-desc> -a boolean value which indicates whether -an exception is thrown if no file system entry exists -rather than returning <literal>undefined</literal>, -by default is <literal>true</literal>. -</tag-desc> -</list> -</tag-desc> - -<tag-name id="fs_symlinksync"><literal>symlinkSync(<value>target</value>, -<value>path</value>)</literal></tag-name> -<tag-desc> -Synchronously creates the link called <literal>path</literal> -pointing to <literal>target</literal> using -<link url="http://man7.org/linux/man-pages/man2/symlink.2.html">symlink(2)</link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -Relative targets are relative to the link’s parent directory. -</tag-desc> - -<tag-name id="fs_unlinksync"><literal>unlinkSync(<value>path</value>)</literal></tag-name> -<tag-desc> -Synchronously unlinks a file by <literal>path</literal> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -</tag-desc> - -<tag-name id="fs_writefilesync"><literal>writeFileSync(<value>filename</value>, -<value>data</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Synchronously writes <literal>data</literal> to a file -with provided <literal>filename</literal>. -The <literal>data</literal> is expected to be a string -or a Buffer object (<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -If the file does not exist, it will be created, -if the file exists, it will be replaced. -The <literal>options</literal> parameter is expected to be -an object with the following keys: -<list type="tag"> -<tag-name><literal>mode</literal></tag-name> -<tag-desc> -mode option, by default is <literal>0o666</literal> -</tag-desc> - -<tag-name><literal>flag</literal></tag-name> -<tag-desc> -file system <link id="njs_api_fs_flags">flag</link>, -by default is <literal>w</literal> -</tag-desc> - -</list> -<example> ->> var fs = require('fs') -undefined ->> var file = fs.writeFileSync('hello.txt', 'Hello world') -undefined -</example> -</tag-desc> - -<tag-name id="fs_writesync_buf"><literal>writeSync(<value>fd</value>, -<value>buffer</value>, <value>offset</value>[, -<value>length</value>[, <value>position</value>]])</literal></tag-name> -<tag-desc> -Writes a buffer to a file using file descriptor, -returns the <literal>number</literal> of bytes written -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). - -<list type="tag"> - -<tag-name><literal>fd</literal></tag-name> -<tag-desc> -an <literal>integer</literal> representing the file descriptor -</tag-desc> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -the <literal>buffer</literal> value can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> - -<tag-name><literal>offset</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> that determines -the part of the buffer to be written, -by default <literal>0</literal> -</tag-desc> - -<tag-name><literal>length</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> specifying the number of bytes to write, -by default is an offset of -<link id="buffer_bytelength">Buffer.byteLength</link> -</tag-desc> - -<tag-name><literal>position</literal></tag-name> -<tag-desc> -refers to the offset from the beginning of the file -where this data should be written, -can be an -<literal>integer</literal> or -<literal>null</literal>, -by default is <literal>null</literal>. -See also -<link url="https://man7.org/linux/man-pages/man2/write.2.html">pwrite(2)</link>. -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="fs_writesync_str"><literal>writeSync(<value>fd</value>, -<value>string</value>[, -<value>position</value>[, -<value>encoding</value>]])</literal></tag-name> -<tag-desc> -Writes a <literal>string</literal> to a file -using file descriptor <literal>fd</literal>, -returns the <literal>number</literal> of bytes written -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). - -<list type="tag"> - -<tag-name><literal>fd</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing a file descriptor -</tag-desc> - -<tag-name><literal>position</literal></tag-name> -<tag-desc> -refers to the offset from the beginning of the file -where this data should be written, -can be an -<literal>integer</literal> or -<literal>null</literal>, by default is <literal>null</literal>. -See also -<link url="https://man7.org/linux/man-pages/man2/write.2.html">pwrite(2)</link> -</tag-desc> - -<tag-name><literal>encoding</literal></tag-name> -<tag-desc> -is a <literal>string</literal>, -by default is <literal>utf8</literal> -</tag-desc> -</list> - -</tag-desc> - -</list> -</para> - - -<section id="fs_dirent" name="fs.Dirent"> - -<para> -<literal>fs.Dirent</literal> is a representation of a directory entry— -a file or a subdirectory. -When -<link id="fs_readdirsync"><literal>readdirSync()</literal></link> -is called with the -<link id="fs_readdirsync_withfiletypes"><literal>withFileTypes</literal></link> -option, -the resulting array contains <literal>fs.Dirent</literal> objects. - -<list type= "bullet" compact="no"> - -<listitem> -<literal>dirent.isBlockDevice()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a block device. -</listitem> - -<listitem> -<literal>dirent.isCharacterDevice()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a character device. -</listitem> - -<listitem> -<literal>dirent.isDirectory()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a file system directory. -</listitem> - -<listitem> -<literal>dirent.isFIFO()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a first-in-first-out (FIFO) pipe. -</listitem> - -<listitem> -<literal>dirent.isFile()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a regular file. -</listitem> - -<listitem> -<literal>dirent.isSocket()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a socket. -</listitem> - -<listitem> -<literal>dirent.isSymbolicLink()</literal>—returns -<literal>true</literal> if the <literal>fs.Dirent</literal> object describes -a symbolic link. -</listitem> - -<listitem> -<literal>dirent.name</literal>— -the name of the file <literal>fs.Dirent</literal> object refers to. -</listitem> - -</list> -</para> - -</section> - - -<section id="fs_filehandle" name="fs.FileHandle"> - -<para> -<table width="100%"> -<tr><td><link id="filehandle_close"><literal>filehandle.close()</literal></link></td></tr> -<tr><td><link id="filehandle_fd"><literal>filehandle.fd</literal></link></td></tr> -<tr><td><link id="filehandle_read"><literal>filehandle.read()</literal></link></td></tr> -<tr><td><link id="filehandle_stat"><literal>filehandle.stat()</literal></link></td></tr> -<tr><td><link id="filehandle_write_buf"><literal>filehandle.write(<value>buf</value>)</literal></link></td></tr> -<tr><td><link id="filehandle_write_str"><literal>filehandle.write(<value>str</value>)</literal></link></td></tr> -</table> -</para> - -<para> -The <literal>FileHandle</literal> object is an object wrapper -for a numeric file descriptor -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>). -Instances of the <literal>FileHandle</literal> object are created by the -<link id="fs_promises_open"><literal>fs.promises.open()</literal></link> method. -If a <literal>FileHandle</literal> is not closed using the -<link id="filehandle_close"><literal>filehandle.close()</literal></link> 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 <literal>FileHandle</literal>. -</para> - -<para> -<list type="tag"> - -<tag-name id="filehandle_close"><literal>filehandle.close()</literal></tag-name> -<tag-desc> -Closes the file handle after waiting for any pending operation on the handle -to complete. -Returns a <literal>promise</literal>, fulfills with undefined upon success. -</tag-desc> - -<tag-name id="filehandle_fd"><literal>filehandle.fd</literal></tag-name> -<tag-desc> -The numeric file descriptor -managed by the <literal>FileHandle</literal> object. -</tag-desc> - -<tag-name id="filehandle_read"><literal>filehandle.read(<value>buffer</value>, -<value>offset</value>[, -<value>length</value>[, -<value>position</value>]])</literal></tag-name> -<tag-desc> -Reads data from the file and stores that in the given buffer. - -<list type="tag"> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -a buffer that will be filled with the file data read, -the value can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> - -<tag-name><literal>offset</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> -representing the location in the buffer at which to start filling -</tag-desc> - -<tag-name><literal>length</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> -representing the number of bytes to read -</tag-desc> - -<tag-name><literal>position</literal></tag-name> -<tag-desc> -the location where to begin reading data from the file, -the value can be -<literal>integer</literal>, -<literal>null</literal>. -If <literal>null</literal>, data will be read from the current file position -and the position will be updated. -If position is an <literal>integer</literal>, -the current file position will remain unchanged. -</tag-desc> -</list> - -Returns a <literal>Promise</literal> which fulfills upon success -with an object with two properties: -<list type="tag"> - -<tag-name><literal>bytesRead</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing the number of bytes read -</tag-desc> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -is a reference to the passed argument in buffer, can be -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> -</list> - -</tag-desc> - -<tag-name id="filehandle_stat"><literal>filehandle.stat()</literal></tag-name> -<tag-desc> -Fulfills with an -<link id="fs_stats">fs.Stats</link> for the file, -returns a <literal>promise</literal>. -</tag-desc> - -<tag-name id="filehandle_write_buf"><literal>filehandle.write(<value>buffer</value>, -<value>offset</value>[, -<value>length</value>[, -<value>position</value>]])</literal></tag-name> -<tag-desc> -Writes a buffer to the file. - -<list type="tag"> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -the <literal>buffer</literal> value can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> - -<tag-name><literal>offset</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing -the start position from within buffer where the data to write begins -</tag-desc> - -<tag-name><literal>length</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing -the number of bytes from buffer to write, by default -is an offset of -<link id="buffer_bytelength">Buffer.byteLength</link> -</tag-desc> - -<tag-name><literal>position</literal></tag-name> -<tag-desc> -the offset from the beginning of the file -where the data from buffer should be written, -can be an -<literal>integer</literal> or -<literal>null</literal>, -by default is <literal>null</literal>. -If <literal>position</literal> is not a <literal>number</literal>, -the data will be written at the current position. -See the POSIX -<link url="https://man7.org/linux/man-pages/man2/write.2.html">pwrite(2)</link> -documentation for details. -</tag-desc> -</list> -Returns a <literal>Promise</literal> which is resolved with an object -containing two properties: -<list type="tag"> - -<tag-name><literal>bytesWritten</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing the number of bytes written -</tag-desc> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -a reference to the buffer written, can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> -</list> -<para> -<note> -It is unsafe to use <literal>filehandle.write()</literal> multiple times -on the same file without waiting for the promise to be resolved or rejected. -</note> -</para> - -</tag-desc> - -<tag-name id="filehandle_write_str"><literal>filehandle.write(<value>string</value>[, -<value>position</value>[, -<value>encoding</value>]])</literal></tag-name> -<tag-desc> -Writes a <literal>string</literal> to the file. - -<list type="tag"> - -<tag-name><literal>position</literal></tag-name> -<tag-desc> -the offset from the beginning of the file -where the data from buffer should be written, -can be an -<literal>integer</literal> or -<literal>null</literal>, -by default is <literal>null</literal>. -If <literal>position</literal> is not a <literal>number</literal>, -the data will be written at the current position. -See the POSIX -<link url="https://man7.org/linux/man-pages/man2/write.2.html">pwrite(2)</link> -documentation for details. -</tag-desc> - -<tag-name><literal>encoding</literal></tag-name> -<tag-desc> -the expected encoding of the string, by default <literal>utf8</literal> -</tag-desc> - -</list> -Returns a <literal>Promise</literal> which is resolved with an object -containing two properties: -<list type="tag"> - -<tag-name><literal>bytesWritten</literal></tag-name> -<tag-desc> -is an <literal>integer</literal> representing the number of bytes written -</tag-desc> - -<tag-name><literal>buffer</literal></tag-name> -<tag-desc> -a reference to the buffer written, can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal> -</tag-desc> -</list> -<para> -<note> -It is unsafe to use <literal>filehandle.write()</literal> multiple times -on the same file without waiting for the promise to be resolved or rejected. -</note> -</para> - -</tag-desc> - -</list> -</para> - -</section> - - -<section id="fs_stats" name="fs.Stats"> - -<para> -The <literal>fs.Stats</literal> object provides information about a file. -The object is returned from -<link id="fs_statsync">fs.statSync()</link> and -<link id="fs_lstatsync">fs.lstatSync()</link>. - -<list type= "bullet" compact="no"> - -<listitem> -<literal>stats.isBlockDevice()</literal>—returns -<literal>true</literal> if the <literal>fs.Stats</literal> object describes -a block device. -</listitem> - -<listitem> -<literal>stats.isDirectory()</literal>—returns -<literal>true</literal> if the <literal>fs.Stats</literal> object describes -a file system directory. -</listitem> - -<listitem> -<literal>stats.isFIFO()</literal>—returns -<literal>true</literal> if the <literal>fs.Stats</literal> object describes -a first-in-first-out (FIFO) pipe. -</listitem> - -<listitem> -<literal>stats.isFile()</literal>—returns -<literal>true</literal> if the <literal>fs.Stats</literal> object describes -a regular file. -</listitem> - -<listitem> -<literal>stats.isSocket()</literal>—returns -<literal>true</literal> if the <literal>fs.Stats</literal> object describes -a socket. -</listitem> - -<listitem> -<literal>stats.isSymbolicLink()</literal>—returns -<literal>true</literal> if the <literal>fs.Stats</literal> object describes -a symbolic link. -</listitem> - -<listitem> -<literal>stats.dev</literal>— -the numeric identifier of the device containing the file. -</listitem> - -<listitem> -<literal>stats.ino</literal>— -the file system specific <literal>Inode</literal> number for the file. -</listitem> - -<listitem> -<literal>stats.mode</literal>— -a bit-field describing the file type and mode. -</listitem> - -<listitem> -<literal>stats.nlink</literal>— -the number of hard-links that exist for the file. -</listitem> - -<listitem> -<literal>stats.uid</literal>— -the numeric user identifier of the user that owns the file (POSIX). -</listitem> - -<listitem> -<literal>stats.gid</literal>— -the numeric group identifier of the group that owns the file (POSIX). -</listitem> - -<listitem> -<literal>stats.rdev</literal>— -the numeric device identifier if the file represents a device. -</listitem> - -<listitem> -<literal>stats.size</literal>— -the size of the file in bytes. -</listitem> - -<listitem> -<literal>stats.blksize</literal>— -the file system block size for i/o operations. -</listitem> - -<listitem> -<literal>stats.blocks</literal>— -the number of blocks allocated for this file. -</listitem> - -<listitem> -<literal>stats.atimeMs</literal>— -the timestamp indicating the last time this file was accessed expressed -in milliseconds since the POSIX Epoch. -</listitem> - -<listitem> -<literal>stats.mtimeMs</literal>— -the timestamp indicating the last time this file was modified expressed -in milliseconds since the POSIX Epoch. -</listitem> - -<listitem> -<literal>stats.ctimeMs</literal>— -the timestamp indicating the last time this file was changed expressed -in milliseconds since the POSIX Epoch. -</listitem> - -<listitem> -<literal>stats.birthtimeMs</literal>— -the timestamp indicating the creation time of this file expressed -in milliseconds since the POSIX Epoch. -</listitem> - -<listitem> -<literal>stats.atime</literal>— -the timestamp indicating the last time this file was accessed. -</listitem> - -<listitem> -<literal>stats.mtime</literal>— -the timestamp indicating the last time this file was modified. -</listitem> - -<listitem> -<literal>stats.ctime</literal>— -the timestamp indicating the last time this file was changed. -</listitem> - -<listitem> -<literal>stats.birthtime</literal>— -the timestamp indicating the creation time of this file. -</listitem> - -</list> -</para> - -</section> - - -<section id="access_const" name="File Access Constants"> - -<para> -The <link id="fs_accesssync"><literal>access()</literal></link> method -can accept the following flags. -These flags are exported by <literal>fs.constants</literal>: - -<list type= "bullet" compact="no"> - -<listitem> -<literal>F_OK</literal>—indicates that the file -is visible to the calling process, -used by default if no mode is specified -</listitem> - -<listitem> -<literal>R_OK</literal>—indicates that the file can be -read by the calling process -</listitem> - -<listitem> -<literal>W_OK</literal>—indicates that the file can be -written by the calling process -</listitem> - -<listitem> -<literal>X_OK</literal>—indicates that the file can be -executed by the calling process -</listitem> - -</list> -</para> - -</section> - - -<section id="njs_api_fs_flags" name="File System Flags"> - -<para> -The <literal>flag</literal> option can accept the following values: - -<list type= "bullet" compact="no"> - -<listitem> -<literal>a</literal>—open a file for appending. -The file is created if it does not exist -</listitem> - -<listitem> -<literal>ax</literal>—the same as <literal>a</literal> -but fails if the file already exists -</listitem> - -<listitem> -<literal>a+</literal>—open a file for reading and appending. -If the file does not exist, it will be created -</listitem> - -<listitem> -<literal>ax+</literal>—the same as <literal>a+</literal> -but fails if the file already exists -</listitem> - -<listitem> -<literal>as</literal>—open a file for appending -in synchronous mode. -If the file does not exist, it will be created -</listitem> - -<listitem> -<literal>as+</literal>—open a file for reading and appending -in synchronous mode. -If the file does not exist, it will be created -</listitem> - -<listitem> -<literal>r</literal>—open a file for reading. -An exception occurs if the file does not exist -</listitem> - -<listitem> -<literal>r+</literal>—open a file for reading and writing. -An exception occurs if the file does not exist -</listitem> - -<listitem> -<literal>rs+</literal>—open a file for reading and writing -in synchronous mode. -Instructs the operating system to bypass the local file system cache -</listitem> - -<listitem> -<literal>w</literal>—open a file for writing. -If the file does not exist, it will be created. -If the file exists, it will be replaced -</listitem> - -<listitem> -<literal>wx</literal>—the same as <literal>w</literal> -but fails if the file already exists -</listitem> - -<listitem> -<literal>w+</literal>—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 -</listitem> - -<listitem> -<literal>wx+</literal>—the same as <literal>w+</literal> -but fails if the file already exists -</listitem> - -</list> -</para> - -</section> - -</section> - - -<section id="querystring" name="Query String"> - -<para> -<table width="100%"> -<tr><td><link id="querystring_decode"><literal>querystring.decode()</literal></link></td></tr> -<tr><td><link id="querystring_encode"><literal>querystring.encode()</literal></link></td></tr> -<tr><td><link id="querystring_escape"><literal>querystring.escape()</literal></link></td></tr> -<tr><td><link id="querystring_parse"><literal>querystring.parse()</literal></link></td></tr> -<tr><td><link id="querystring_stringify"><literal>querystring.stringify()</literal></link></td></tr> -<tr><td><link id="querystring_unescape"><literal>querystring.unescape()</literal></link></td></tr> -</table> -</para> - -<para> -The Query String module provides support -for parsing and formatting URL query strings -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>). -The Query String module object is returned by -<literal>require('querystring')</literal>. -</para> - -<para> -<list type="tag"> - -<tag-name id="querystring_decode"><literal>querystring.decode()</literal></tag-name> -<tag-desc> -is an alias for -<link id="querystring_parse"><literal>querystring.parse()</literal></link>. -</tag-desc> - -<tag-name id="querystring_encode"><literal>querystring.encode()</literal></tag-name> -<tag-desc> -is an alias for -<link id="querystring_stringify"><literal>querystring.stringify()</literal></link>. -</tag-desc> - -<tag-name id="querystring_escape"><literal>querystring.escape(<value>string</value>)</literal></tag-name> -<tag-desc> -<para> -Performs URL encoding of the given <literal>string</literal>, -returns an escaped query string. -The method is used by -<link id="querystring_stringify"><literal>querystring.stringify()</literal></link> -and should not be used directly. -</para> -</tag-desc> - -<tag-name id="querystring_parse"><literal>querystring.parse(<value>string</value>[, -<value>separator</value>[, -<value>equal</value>[, -<value>options</value>]]])</literal></tag-name> -<tag-desc> -<para> -Parses the query string URL and returns an object. -</para> - -<para> -The <literal>separator</literal> parameter is a substring -for delimiting key and value pairs in the query string, -by default is “<literal>&</literal>”. -</para> - -<para> -The <literal>equal</literal> parameter is a substring -for delimiting keys and values in the query string, -by default is “<literal>=</literal>”. -</para> - -<para> -The <literal>options</literal> parameter is expected to be -an object with the following keys: -<list type="tag"> -<tag-name><literal>decodeURIComponent</literal> -<value>function</value></tag-name> -<tag-desc> -Function used -to decode percent-encoded characters in the query string, -by default is -<link id="querystring_unescape"><literal>querystring.unescape()</literal></link> -</tag-desc> - -<tag-name><literal>maxKeys</literal> -<value>number</value></tag-name> -<tag-desc> -the maximum number of keys to parse, -by default is <literal>1000</literal>. -The <literal>0</literal> value removes limitations for counting keys. -</tag-desc> - -</list> -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 <literal>U+FFFD</literal> replacement character. -</para> - -<para> -For example, for the following query string -<example> -'foo=bar&abc=xyz&abc=123' -</example> -the output will be: -<example> -{ - foo: 'bar', - abc: ['xyz', '123'] -} -</example> -</para> - -</tag-desc> - -<tag-name id="querystring_stringify"><literal>querystring.stringify(<value>object</value>[, -<value>separator</value>[, -<value>equal</value>[, -<value>options</value>]]])</literal></tag-name> -<tag-desc> -<para> -Serializes an object and returns a URL query string. -</para> - -<para> -The <literal>separator</literal> parameter is a substring -for delimiting key and value pairs in the query string, -by default is “<literal>&</literal>”. -</para> - -<para> -The <literal>equal</literal> parameter is a substring -for delimiting keys and values in the query string, -by default is “<literal>=</literal>”. -</para> - -<para> -The <literal>options</literal> parameter is expected to be -an object with the following keys: -<list type="tag"> -<tag-name><literal>encodeURIComponent</literal> -<value>function</value></tag-name> -<tag-desc> -The function to use when converting -URL-unsafe characters to percent-encoding in the query string, -by default is -<link id="querystring_escape"><literal>querystring.escape()</literal></link>. -</tag-desc> - -</list> -</para> - -<para> -By default, characters that require percent-encoding within the query string -are encoded as UTF-8. -If other encoding is required, then -<literal>encodeURIComponent</literal> option should be specified. -</para> - -<para> -For example, for the following command -<example> -querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], 123: '' }); -</example> -the query string will be: -<example> -'foo=bar&baz=qux&baz=quux&123=' -</example> -</para> - -</tag-desc> - -<tag-name id="querystring_unescape"><literal>querystring.unescape(<value>string</value>)</literal></tag-name> -<tag-desc> -<para> -Performs decoding of URL percent-encoded characters -of the <literal>string</literal>, -returns an unescaped query string. -The method is used by -<link id="querystring_parse"><literal>querystring.parse()</literal></link> -and should not be used directly. -</para> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="xml" name="XML"> - -<para> -<table width="100%"> -<tr><td><link id="xml_parse"><literal>xml.parse()</literal></link></td></tr> -<tr><td><link id="xml_c14n"><literal>xml.c14n()</literal></link></td></tr> -<tr><td><link id="xml_exclusivec14n"><literal>xml.exclusiveC14n()</literal></link></td></tr> -<tr><td><link id="xml_serialize"><literal>xml.serialize()</literal></link></td></tr> -<tr><td><link id="xml_serialize_tostring"><literal>xml.serializeToString()</literal></link></td></tr> -<tr><td><link id="xml_doc"><literal>XMLDoc</literal></link></td></tr> -<tr><td><link id="xml_node"><literal>XMLNode</literal></link></td></tr> -<tr><td><link id="xml_xmlattr"><literal>XMLAttr</literal></link></td></tr> -</table> -</para> - -<para> -The XML module allows working with XML documents -(since <link doc="changes.xml" id="njs0.7.10">0.7.10</link>). -The XML module object is returned by -<literal>require('xml')</literal>. -</para> - -<para> -Example: -<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>' */ -</example> -</para> - -<para> -<list type="tag"> - -<tag-name id="xml_parse"><literal>parse(<value>string</value> | -<value>Buffer</value>)</literal></tag-name> -<tag-desc> -Parses a string or Buffer for an XML document, -returns an -<link id="xml_doc"><literal>XMLDoc</literal></link> wrapper object -representing the parsed XML document. -</tag-desc> - -<tag-name id="xml_c14n"><literal>c14n(<value>root_node</value>[, -<value>excluding_node</value>])</literal></tag-name> -<tag-desc> -Canonicalizes <literal>root_node</literal> and its children according to -<link url="https://www.w3.org/TR/xml-c14n">Canonical XML Version 1.1</link>. -The <literal>root_node</literal> can be -<link id="xml_node"><literal>XMLNode</literal></link> or -<link id="xml_doc"><literal>XMLDoc</literal></link> wrapper object -around XML structure. -Returns Buffer object that contains canonicalized output. - -<para> -<list type="tag"> - -<tag-name><literal>excluding_node</literal></tag-name> -<tag-desc> -allows omitting from the output a part of the document -</tag-desc> - -</list> -</para> - -</tag-desc> - -<tag-name id="xml_exclusivec14n"><literal>exclusiveC14n(<value>root_node</value>[, -<value>excluding_node</value>[, -<value>withComments</value> -[,<value>prefix_list</value>]]])</literal></tag-name> -<tag-desc> -Canonicalizes <literal>root_node</literal> and its children according to -<link url="https://www.w3.org/TR/xml-exc-c14n/">Exclusive XML -Canonicalization Version 1.0</link>. - -<para> -<list type="tag"> - -<tag-name><literal>root_node</literal></tag-name> -<tag-desc> -is -<link id="xml_node"><literal>XMLNode</literal></link> or -<link id="xml_doc"><literal>XMLDoc</literal></link> wrapper object -around XML structure -</tag-desc> - -<tag-name><literal>excluding_node</literal></tag-name> -<tag-desc> -allows omitting from the output a part of the document -corresponding to the node and its children -</tag-desc> - -<tag-name><literal>withComments</literal></tag-name> -<tag-desc> -a boolean value, <literal>false</literal> by default. -If <literal>true</literal>, canonicalization corresponds to -<link url="http://www.w3.org/2001/10/xml-exc-c14n#WithComments">Exclusive XML -Canonicalization Version 1.0</link>. -Returns Buffer object that contains canonicalized output. -</tag-desc> - -<tag-name><literal>prefix_list</literal></tag-name> -<tag-desc> -an optional string with a space separated namespace prefixes -for namespaces that should also be included into the output -</tag-desc> - -</list> -</para> - -</tag-desc> - -<tag-name id="xml_serialize"><literal>serialize()</literal></tag-name> -<tag-desc> -The same as -<link id="xml_c14n"><literal>xml.c14n()</literal></link> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -</tag-desc> - -<tag-name id="xml_serialize_tostring"><literal>serializeToString()</literal></tag-name> -<tag-desc> -The same as -<link id="xml_c14n"><literal>xml.c14n()</literal></link> -except it returns the result as a <literal>string</literal> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -</tag-desc> - -<tag-name id="xml_doc"><literal>XMLDoc</literal></tag-name> -<tag-desc> -An XMLDoc wrapper object around XML structure, -the root node of the document. - -<para> -<list type="tag"> - -<tag-name id="xml_doc_root"><literal>doc.$root</literal></tag-name> -<tag-desc> -the document's root by its name or undefined -</tag-desc> - -<tag-name id="xml_doc_xxx"><literal>doc.<value>abc</value></literal></tag-name> -<tag-desc> -the first root tag named <value>abc</value> as -<link id="xml_node"><literal>XMLNode</literal></link> wrapper object -</tag-desc> - -</list> -</para> - -</tag-desc> - -<tag-name id="xml_node"><literal>XMLNode</literal></tag-name> -<tag-desc> -An XMLNode wrapper object around XML tag node. -<para> -<list type="tag"> - -<tag-name id="node_abc"><literal>node.<value>abc</value></literal></tag-name> -<tag-desc> -the same as -<link id="node_tag"><literal>node.$tag$<value>abc</value></literal></link> -</tag-desc> - -<tag-name id="node_attr"><literal>node.$attr$<value>abc</value></literal></tag-name> -<tag-desc> -the node's attribute value of <value>abc</value>, -writable -since <link doc="changes.xml" id="njs0.7.11">0.7.11</link> -</tag-desc> - -<tag-name id="node_attr_value"><literal>node.$attr$<value>abc</value></literal>=<value>xyz</value></tag-name> -<tag-desc> -the same as -<link id="node_setattribute"><literal>node.setAttribute('<value>abc</value>', -<value>xyz</value>)</literal></link> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>) -</tag-desc> - -<tag-name id="node_attrs"><literal>node.$attrs</literal></tag-name> -<tag-desc> -an <link id="xml_xmlattr"><literal>XMLAttr</literal></link> wrapper object -for all attributes of the node -</tag-desc> - -<tag-name id="node_name"><literal>node.$name</literal></tag-name> -<tag-desc> -the name of the node -</tag-desc> - -<tag-name id="node_ns"><literal>node.$ns</literal></tag-name> -<tag-desc> -the namespace of the node -</tag-desc> - -<tag-name id="node_parent"><literal>node.$parent</literal></tag-name> -<tag-desc> -the parent node of the current node -</tag-desc> - -<tag-name id="node_tag"><literal>node.$tag$<value>abc</value></literal></tag-name> -<tag-desc> -the first child tag of the node named <value>abc</value>, -writable -since <link doc="changes.xml" id="njs0.7.11">0.7.11</link> -</tag-desc> - -<tag-name id="node_tags"><literal>node.$tags</literal></tag-name> -<tag-desc> -an array of all children tags -</tag-desc> - -<tag-name id="node_tags_"><literal>node.$tags = [node1, node2, ...]</literal></tag-name> -<tag-desc> -the same as -<link id="node_removechildren"><literal>node.removeChildren</literal>()</link>; -<link id="node_addchild"><literal>node.addChild(<value>node1</value>)</literal></link>; -<link id="node_addchild"><literal>node.addChild(<value>node2</value>)</literal></link> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -</tag-desc> - -<tag-name id="node_tags_abc"><literal>node.$tags$<value>abc</value></literal></tag-name> -<tag-desc> -all children tags named <value>abc</value> of the node, -writable -since <link doc="changes.xml" id="njs0.7.11">0.7.11</link> -</tag-desc> - -<tag-name id="node_text"><literal>node.$text</literal></tag-name> -<tag-desc> -the content of the node, -writable -since <link doc="changes.xml" id="njs0.7.11">0.7.11</link> -</tag-desc> - -<tag-name id="node_text_abc"><literal>node.$text = 'abc' </literal></tag-name> -<tag-desc> -the same as -<link id="node_settext"><literal>node.setText('abc')</literal></link> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>) -</tag-desc> - -<tag-name id="node_addchild"><literal>node.addChild(<value>nd</value>)</literal></tag-name> -<tag-desc> -adds XMLNode as a child to node -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -<literal>nd</literal> is recursively copied before adding to the node -</tag-desc> - -<tag-name id="node_removeallattr"><literal>node.removeAllAttributes()</literal></tag-name> -<tag-desc> -removes all attributes of the node -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>) -</tag-desc> - -<tag-name id="node_removeattr"><literal>node.removeAttribute(<value>attr_name</value>)</literal></tag-name> -<tag-desc> -removes the attribute named <literal>attr_name</literal> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>) -</tag-desc> - -<tag-name id="node_removechildren"><literal>node.removeChildren(<value>tag_name</value>)</literal></tag-name> -<tag-desc> -removes all the children tags named <literal>tag_name</literal> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -If <literal>tag_name</literal> is absent, all children tags are removed -</tag-desc> - -<tag-name id="node_removetext"><literal>node.removeText()</literal></tag-name> -<tag-desc> -removes the node's text value -(<link doc="changes.xml" id="njs0.7.11">0.7.11</link>) -</tag-desc> - -<tag-name id="node_setattr"><literal>node.setAttribute(<value>attr_name</value>, -<value>value</value>)</literal></tag-name> -<tag-desc> -sets a value for an <literal>attr_name</literal> -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -When the value is <literal>null</literal>, -the attribute named <literal>attr_name</literal> is deleted -</tag-desc> - -<tag-name id="node_settext"><literal>node.setText(<value>value</value>)</literal></tag-name> -<tag-desc> -sets a text value for the node -(since <link doc="changes.xml" id="njs0.7.11">0.7.11</link>). -When the value is <literal>null</literal>, the text of the node is deleted. -</tag-desc> - -</list> -</para> - -</tag-desc> - -<tag-name id="xml_xmlattr"><literal>XMLAttr</literal></tag-name> -<tag-desc> -An XMLAttrs wrapper object around XML node attributes. - -<para> -<list type="tag"> - -<tag-name id="xmlattr_x"><literal>attr.<value>abc</value></literal></tag-name> -<tag-desc> -the attribute value of <value>abc</value> -</tag-desc> - -</list> -</para> - -</tag-desc> - -</list> -</para> - -</section> - - -<section id="zlib" name="zlib"> - -<para> -<table width="100%"> -<tr><td><link id="zlib_deflaterawsync"><literal>zlib.deflateRawSync()</literal></link></td></tr> -<tr><td><link id="zlib_deflatesync"><literal>zlib.deflateSync()</literal></link></td></tr> -<tr><td><link id="zlib_inflaterawsync"><literal>zlib.inflateRawSync()</literal></link></td></tr> -<tr><td><link id="zlib_inflatesync"><literal>zlib.inflateSync()</literal></link></td></tr> -</table> -</para> - -<para> -The zlib module provides compression functionality using the -“deflate” and “inflate” algorithms -(since <link doc="changes.xml" id="njs0.7.12">0.7.12</link>). -The zlib module object is returned by -<literal>require('zlib')</literal>. -</para> - -<para> -<list type="tag"> - -<tag-name id="zlib_deflaterawsync"><literal>deflateRawSync(<value>string</value> | -<value>Buffer</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -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 -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>. -<literal>Options</literal> is an optional object that contains -<link id="zlib_options"/>. -Returns Buffer instance that contains the compressed data. -</tag-desc> - -<tag-name id="zlib_deflatesync"><literal>deflateSync(<value>string</value> | -<value>Buffer</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Compresses data using the “deflate” algorithm provided as a string or Buffer. -The Buffer value can be a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>. -<literal>Options</literal> is an optional object that contains -<link id="zlib_options"/>. -Returns Buffer instance that contains the compressed data. -</tag-desc> - -<tag-name id="zlib_inflaterawsync"><literal>inflateRawSync(<value>string</value> | -<value>Buffer</value>)</literal></tag-name> -<tag-desc> -Decompresses a raw stream by using the “deflate” algorithm. -Returns Buffer instance that contains the decompressed data. -</tag-desc> - -<tag-name id="zlib_inflatesync"><literal>inflateSync(<value>string</value> | -<value>Buffer</value>)</literal></tag-name> -<tag-desc> -Decompresses a stream by using the “deflate” algorithm. -Returns Buffer instance that contains the decompressed data. -</tag-desc> - -</list> -</para> - - -<section id="zlib_options" name="zlib options"> - -<para> -<list type= "bullet" compact="no"> - -<listitem> -<literal>chunkSize</literal>—is an integer, -by default is <literal>1024</literal> -</listitem> - -<listitem> -<literal>dictionary</literal>—is a -<literal>Buffer</literal>, -<literal>TypedArray</literal>, or -<literal>DataView</literal>. -by default is empty -</listitem> - -<listitem> -<literal>level</literal>—is an integer, compression only, -see <link id="zlib_compression_levels"/> -</listitem> - -<listitem> -<literal>memLevel</literal>—is an integer -from <literal>1</literal> to <literal>9</literal>, compression only -</listitem> - -<listitem> -<literal>strategy</literal>—is an integer, compression only, -see <link id="zlib_compression_strategy"/> -</listitem> - -<listitem> -<literal>windowBits</literal>—is an integer -from <literal>-15</literal> to <literal>-9</literal> -for raw data, -from <literal>9</literal> to <literal>15</literal> -for an ordinary stream -</listitem> - -</list> -</para> - -</section> - -<section id="zlib_compression_levels" name="zlib compression levels"> - -<para> -<table> -<tr><td>Name</td><td>Description</td></tr> -<tr><td><literal>zlib.constants.Z_NO_COMPRESSION</literal></td><td>no compression</td></tr> -<tr><td><literal>zlib.constants.Z_BEST_SPEED</literal></td><td>fastest, produces the least compression</td></tr> -<tr><td><literal>zlib.constants.Z_DEFAULT_COMPRESSION</literal></td><td>trade-off between speed and compression</td></tr> -<tr><td><literal>zlib.constants.Z_BEST_COMPRESSION</literal></td><td>slowest, produces the most compression</td></tr> -</table> -</para> - -</section> - -<section id="zlib_compression_strategy" name="zlib compression strategy"> - -<para> -<table> -<tr><td>Name</td><td>Description</td></tr> -<tr><td><literal>zlib.constants.Z_FILTERED</literal></td><td>Filtered strategy: for the data produced by a filter or predictor</td></tr> -<tr><td><literal>zlib.constants.Z_HUFFMAN_ONLY</literal></td><td>Huffman-only strategy: only Huffman encoding, no string matching</td></tr> -<tr><td><literal>zlib.constants.Z_RLE</literal></td><td>Run Length Encoding strategy: limit match distances to one, better compression of PNG image data</td></tr> -<tr><td><literal>zlib.constants.Z_FIXED</literal></td><td>Fixed table strategy: prevents the use of dynamic Huffman codes, a simpler decoder for special applications</td></tr> -<tr><td><literal>zlib.constants.Z_DEFAULT_STRATEGY</literal></td><td>Default strategy, suitable for general purpose compression</td></tr> -</table> -</para> - -</section> - -</section> - -</section> - -</article>
--- a/xml/en/docs/njs/security.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,71 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Security" - link="/en/docs/njs/security.html" - lang="en" - rev="1" - toc="no"> - -<section> - -<para> -All njs security issues should be reported to -<literal>security-alert@nginx.org</literal>. -</para> - -<para> -Patches are signed using one of the -<link doc="../../pgp_keys.xml">PGP public keys</link>. -</para> - -</section> - - -<section id="considerations" name="Special considerations"> - -<para> -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 -<link doc="../http/ngx_http_js_module.xml" id="js_import">js_import</link> -directive in nginx. -JavaScript code is loaded once during nginx start. -</para> - -<para> -In nginx/njs threat model, JavaScript code is considered a trusted source -in the same way as <literal>nginx.conf</literal> and sites certificates. -What this means in practice: - -<list type="bullet"> - -<listitem> -memory disclosure and other security issues -triggered by JavaScript code modification -are not considered security issues, but as ordinary bugs -</listitem> - -<listitem> -measures should be taking for protecting JavaScript code used by njs -</listitem> - -<listitem> -if no <link doc="../http/ngx_http_js_module.xml" id="js_import">js_import</link> -directives are present in <literal>nginx.conf</literal>, -nginx is safe from JavaScript-related vulnerabilities -</listitem> - -</list> -</para> - -</section> - - -</article>
--- a/xml/en/docs/njs/typescript.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,114 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Writing njs code using TypeScript definition files" - link="/en/docs/njs/typescript.html" - lang="en" - rev="1"> - -<section> - -<para> -<link url="https://www.typescriptlang.org">TypeScript</link> is -a typed superset of JavaScript -that compiles to plain JavaScript. -</para> - -<para> -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. -</para> - -<para> -njs provides TypeScript definition files for its -<link doc="reference.xml">API</link> which can be used to: -<list type="bullet"> - -<listitem> -Get autocompletion and API check in an editor -</listitem> - -<listitem> -Write njs type-safe code -</listitem> - -</list> -</para> - -</section> - - -<section id="get" name="Compiling TypeScript definition files"> - -<para> -<example> -$ 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 -</example> -</para> - -</section> - - -<section id="autocomplete" name="API checks and autocompletions"> - -<para> -Put <literal>*.d.ts</literal> files to a place where you editor can find it. -</para> - -<para> -<literal>test.js</literal>: -<example> -/// <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"); -} -</example> -</para> - -</section> - - -<section id="write" name="Writing njs type-safe code"> - -<para> -<literal>test.ts</literal>: -<example> -/// <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"); -} -</example> -TypeScript installation: -<example> -# npm install -g typescript -</example> -TypeScript compilation: -<example> -$ tsc test.ts -$ cat test.js -</example> -The resulting <literal>test.js</literal> file can be used directly with njs. -</para> - -</section> - - -</article>
--- a/xml/en/docs/stream/ngx_stream_js_module.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,793 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE module SYSTEM "../../../../dtd/module.dtd"> - -<module name="Module ngx_stream_js_module" - link="/en/docs/stream/ngx_stream_js_module.html" - lang="en" - rev="44"> - -<section id="summary"> - -<para> -The <literal>ngx_stream_js_module</literal> module is used to implement -handlers in <link doc="../njs/index.xml">njs</link> — -a subset of the JavaScript language. -</para> - -<para> -Download and install instructions are available -<link doc="../njs/install.xml">here</link>. -</para> - -</section> - - -<section id="example" name="Example Configuration"> - -<para> -The example works since -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>. -<example> -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; - } - } -} -</example> -</para> - -<para> -The <path>stream.js</path> file: -<example> -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}; -</example> -</para> - -</section> - - -<section id="directives" name="Directives"> - -<directive name="js_access"> -<syntax><value>function</value> | <value>module.function</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Sets an njs function which will be called at the -<link doc="stream_processing.xml" id="access_phase">access</link> phase. -Since <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>, -a module function can be referenced. -</para> - -<para> -The function is called once at the moment when the stream session reaches -the <link doc="stream_processing.xml" id="access_phase">access</link> phase -for the first time. -The function is called with the following arguments: - -<list type="tag"> -<tag-name><literal>s</literal></tag-name> -<tag-desc> -the <link doc="../njs/reference.xml" id="stream">Stream Session</link> object -</tag-desc> - -</list> -</para> - -<para> -At this phase, it is possible to perform initialization -or register a callback with -the <link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -method -for each incoming data chunk until one of the following methods are called: -<link doc="../njs/reference.xml" id="s_allow"><literal>s.allow()</literal></link>, -<link doc="../njs/reference.xml" id="s_decline"><literal>s.decline()</literal></link>, -<link doc="../njs/reference.xml" id="s_done"><literal>s.done()</literal></link>. -As soon as one of these methods is called, the stream session processing -switches to the <link doc="stream_processing.xml">next phase</link> -and all current -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -callbacks are dropped. -</para> - -</directive> - - -<directive name="js_fetch_buffer_size"> -<syntax><value>size</value></syntax> -<default>16k</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Sets the <value>size</value> of the buffer used for reading and writing -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_ciphers"> -<syntax><value>ciphers</value></syntax> -<default>HIGH:!aNULL:!MD5</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Specifies the enabled ciphers for HTTPS connections -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -The ciphers are specified in the format understood by the OpenSSL library. -</para> - -<para> -The full list can be viewed using the -“<command>openssl ciphers</command>” command. -</para> - -</directive> - - -<directive name="js_fetch_max_response_buffer_size"> -<syntax><value>size</value></syntax> -<default>1m</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Sets the maximum <value>size</value> of the response received -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_protocols"> -<syntax> - [<literal>TLSv1</literal>] - [<literal>TLSv1.1</literal>] - [<literal>TLSv1.2</literal>] - [<literal>TLSv1.3</literal>]</syntax> -<default>TLSv1 TLSv1.1 TLSv1.2</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Enables the specified protocols for HTTPS connections -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_timeout"> -<syntax><value>time</value></syntax> -<default>60s</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Defines a timeout for reading and writing -for <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -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. -</para> - -</directive> - - -<directive name="js_fetch_trusted_certificate"> -<syntax><value>file</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Specifies a <value>file</value> with trusted CA certificates in the PEM format -used to -<link doc="../njs/reference.xml" id="fetch_verify">verify</link> -the HTTPS certificate -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify"> -<syntax><literal>on</literal> | <literal>off</literal></syntax> -<default>on</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Enables or disables verification of the HTTPS server certificate -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify_depth"> -<syntax><value>number</value></syntax> -<default>100</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Sets the verification depth in the HTTPS server certificates chain -with <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_filter"> -<syntax><value>function</value> | <value>module.function</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Sets a data filter. -Since <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>, -a module function can be referenced. -The filter function is called once at the moment when the stream session reaches -the <link doc="stream_processing.xml" id="content_phase">content</link> phase. -</para> - -<para> -The filter function is called with the following arguments: -<list type="tag"> -<tag-name><literal>s</literal></tag-name> -<tag-desc> -the <link doc="../njs/reference.xml" id="stream">Stream Session</link> object -</tag-desc> - -</list> -</para> - -<para> -At this phase, it is possible to perform initialization -or register a callback with -the <link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -method for each incoming data chunk. -The -<link doc="../njs/reference.xml" id="s_off"><literal>s.off()</literal></link> -method may be used to unregister a callback and stop filtering. -</para> - -<para> -<note> -As the <literal>js_filter</literal> handler -returns its result immediately, it supports -only synchronous operations. -Thus, asynchronous operations such as -<link doc="../njs/reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -or -<link doc="../njs/reference.xml" id="settimeout"><literal>setTimeout()</literal></link> -are not supported. -</note> -</para> - -</directive> - - -<directive name="js_import"> -<syntax><value>module.js</value> | -<value>export_name from module.js</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.4.0</appeared-in> - -<para> -Imports a module that implements location and variable handlers in njs. -The <literal>export_name</literal> is used as a namespace -to access module functions. -If the <literal>export_name</literal> is not specified, -the module name will be used as a namespace. -<example> -js_import stream.js; -</example> -Here, the module name <literal>stream</literal> is used as a namespace -while accessing exports. -If the imported module exports <literal>foo()</literal>, -<literal>stream.foo</literal> is used to refer to it. -</para> - -<para> -Several <literal>js_import</literal> directives can be specified. -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_include"> -<syntax><value>file</value></syntax> -<default/> -<context>stream</context> - -<para> -Specifies a file that implements server and variable handlers in njs: -<example> -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; -} -</example> -</para> - -<para> -The directive was made obsolete in version -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -and was removed in version -<link doc="../njs/changes.xml" id="njs0.7.1">0.7.1</link>. -The <link id="js_import"/> directive should be used instead. -</para> - -</directive> - - -<directive name="js_path"> -<syntax> -<value>path</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.3.0</appeared-in> - -<para> -Sets an additional path for njs modules. -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_periodic"> -<syntax><value>function</value> | - <value>module.function</value> - [<literal>interval</literal>=<value>time</value>] - [<literal>jitter</literal>=<value>number</value>] - [<literal>worker_affinity</literal>=<value>mask</value>]</syntax> -<default/> -<context>server</context> -<appeared-in>0.8.1</appeared-in> - -<para> -Specifies a content handler to run at regular interval. -The handler receives a -<link doc="../njs/reference.xml" id="periodic_session">session object</link> -as its first argument, -it also has access to global objects such as -<link doc="../njs/reference.xml" id="ngx">ngx</link>. -</para> - -<para> -The optional <literal>interval</literal> parameter -sets the interval between two consecutive runs, -by default, 5 seconds. -</para> - -<para> -The optional <literal>jitter</literal> parameter sets the time within which -the location content handler will be randomly delayed, -by default, there is no delay. -</para> - -<para> -By default, the <literal>js_handler</literal> is executed on worker process 0. -The optional <literal>worker_affinity</literal> 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 <literal>all</literal> mask allows the handler to be executed -in all worker processes. -</para> - -<para> -Example: -<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); -} -</example> -</para> - -</directive> - - -<directive name="js_preload_object"> -<syntax><value>name.json</value> | -<value>name</value> from <value>file.json</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.8</appeared-in> - -<para> -Preloads an -<link doc="../njs/preload_objects.xml">immutable object</link> -at configure time. -The <literal>name</literal> is used as a name of the global variable -though which the object is available in njs code. -If the <literal>name</literal> is not specified, -the file name will be used instead. -<example> -js_preload_object map.json; -</example> -Here, the <literal>map</literal> is used as a name -while accessing the preloaded object. -</para> - -<para> -Several <literal>js_preload_object</literal> directives can be specified. -</para> - -</directive> - - -<directive name="js_preread"> -<syntax><value>function</value> | <value>module.function</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Sets an njs function which will be called at the -<link doc="stream_processing.xml" id="preread_phase">preread</link> phase. -Since <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>, -a module function can be referenced. -</para> - -<para> -The function is called once -at the moment when the stream session reaches the -<link doc="stream_processing.xml" id="preread_phase">preread</link> phase -for the first time. -The function is called with the following arguments: - -<list type="tag"> -<tag-name><literal>s</literal></tag-name> -<tag-desc> -the <link doc="../njs/reference.xml" id="stream">Stream Session</link> object -</tag-desc> - -</list> -</para> - -<para> -At this phase, it is possible to perform initialization -or register a callback with -the <link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -method -for each incoming data chunk until one of the following methods are called: -<link doc="../njs/reference.xml" id="s_allow"><literal>s.allow()</literal></link>, -<link doc="../njs/reference.xml" id="s_decline"><literal>s.decline()</literal></link>, -<link doc="../njs/reference.xml" id="s_done"><literal>s.done()</literal></link>. -When one of these methods is called, -the stream session switches to the -<link doc="stream_processing.xml">next phase</link> -and all current -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -callbacks are dropped. -</para> - -<para> -<note> -As the <literal>js_preread</literal> handler -returns its result immediately, it supports -only synchronous callbacks. -Thus, asynchronous callbacks such as -<link doc="../njs/reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -or -<link doc="../njs/reference.xml" id="settimeout"><literal>setTimeout()</literal></link> -are not supported. -Nevertheless, asynchronous operations are supported in -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -callbacks in the -<link doc="stream_processing.xml" id="preread_phase">preread</link> phase. -See -<link url="https://github.com/nginx/njs-examples#authorizing-connections-using-ngx-fetch-as-auth-request-stream-auth-request">this example</link> for more information. -</note> -</para> - -</directive> - - -<directive name="js_set"> -<syntax> -<value>$variable</value> <value>function</value> | -<value>module.function</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Sets an njs <literal>function</literal> -for the specified <literal>variable</literal>. -Since <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>, -a module function can be referenced. -</para> - -<para> -The function is called when -the variable is referenced for the first time for a given request. -The exact moment depends on a -<link doc="stream_processing.xml">phase</link> -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 -<link doc="ngx_stream_log_module.xml" id="log_format"/> 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. -</para> - -<para> -<note> -As the <literal>js_set</literal> handler -returns its result immediately, it supports -only synchronous callbacks. -Thus, asynchronous callbacks such as -<link doc="../njs/reference.xml" id="ngx_fetch">ngx.fetch()</link> -or -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link> -are not supported. -</note> -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_shared_dict_zone"> -<syntax> - <literal>zone</literal>=<value>name</value>:<value>size</value> - [<literal>timeout</literal>=<value>time</value>] - [<literal>type</literal>=<literal>string</literal>|<literal>number</literal>] - [<literal>evict</literal>]</syntax> -<default/> -<context>stream</context> -<appeared-in>0.8.0</appeared-in> - -<para> -Sets the <value>name</value> and <value>size</value> of the shared memory zone -that keeps the -key-value <link doc="../njs/reference.xml" id="dict">dictionary</link> -shared between worker processes. -</para> - -<para> -By default the shared dictionary uses a string as a key and a value. -The optional <literal>type</literal> parameter -allows redefining the value type to number. -</para> - -<para> -The optional <literal>timeout</literal> parameter sets -the time after which all shared dictionary entries are removed from the zone. -</para> - -<para> -The optional <literal>evict</literal> parameter removes the oldest -key-value pair when the zone storage is exhausted. -</para> - -<para> -Example: -<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)); - } -</example> -</para> - -</directive> - - -<directive name="js_var"> -<syntax><value>$variable</value> [<value>value</value>]</syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.5.3</appeared-in> - -<para> -Declares -a <link doc="../njs/reference.xml" id="r_variables">writable</link> -variable. -The value can contain text, variables, and their combination. -</para> - -<para> -<note> -The directive can be specified on the -<literal>server</literal> level -since <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - -</section> - - -<section id="properties" name="Session Object Properties"> - -<para> -Each stream njs handler receives one argument, a stream session -<link doc="../njs/reference.xml" id="stream">object</link>. -</para> - -</section> - -</module>
--- a/xml/en/index.xml Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/en/index.xml Wed Feb 14 20:06:00 2024 +0300 @@ -8,7 +8,7 @@ <article name="nginx" link="/en/" lang="en" - rev="162"> + rev="163"> <section> @@ -204,11 +204,7 @@ </listitem> <listitem> -Embedded <link doc="docs/http/ngx_http_perl_module.xml">Perl</link>; -</listitem> - -<listitem> -<link doc="docs/njs/index.xml">njs</link> scripting language. +Embedded <link doc="docs/http/ngx_http_perl_module.xml">Perl</link>. </listitem> </list> @@ -330,11 +326,7 @@ </listitem> <listitem> -<link doc="docs/stream/ngx_stream_split_clients_module.xml">A/B testing</link>; -</listitem> - -<listitem> -<link doc="docs/njs/index.xml">njs</link> scripting language. +<link doc="docs/stream/ngx_stream_split_clients_module.xml">A/B testing</link>. </listitem> </list>
--- a/xml/ru/GNUmakefile Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/ru/GNUmakefile Wed Feb 14 20:06:00 2024 +0300 @@ -47,7 +47,6 @@ 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 @@ 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 @@ 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 \
--- a/xml/ru/docs/http/ngx_http_js_module.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,814 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE module SYSTEM "../../../../dtd/module.dtd"> - -<module name="Модуль ngx_http_js_module" - link="/ru/docs/http/ngx_http_js_module.html" - lang="ru" - rev="46"> - -<section id="summary"> - -<para> -Модуль <literal>ngx_http_js_module</literal> позволяет задавать -обработчики location и переменных -на <link doc="../njs/index.xml">njs</link> — -подмножестве языка JavaScript. -</para> - -<para> -Инструкция по сборке и установке доступны -<link doc="../njs/install.xml">здесь</link>. -</para> - -</section> - - -<section id="example" name="Пример конфигурации"> - -<para> -Пример работает начиная с версии -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>. -<example> -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; - } - } -} -</example> -</para> - -<para> -Файл <path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - - -<section id="directives" name="Директивы"> - -<directive name="js_body_filter"> -<syntax><value>функция</value> | <value>модуль.функция</value> -[<value>buffer_type</value>=<value>строка</value> | <value>буфер</value>]</syntax> -<default/> -<context>location</context> -<context>if in location</context> -<context>limit_except</context> -<appeared-in>0.5.2</appeared-in> - -<para> -Задаёт функцию njs в качестве фильтра тела ответа. -Функция фильтра вызывается для каждого блока данных тела ответа -со следующими аргументами: - -<list type="tag"> -<tag-name><literal>r</literal></tag-name> -<tag-desc> -объект <link doc="../njs/reference.xml" id="http">HTTP request</link> -</tag-desc> - -<tag-name><literal>data</literal></tag-name> -<tag-desc> -входящий блок данных -может быть строкой или буфером -в зависимости от значения <literal>buffer_type</literal>, -по умолчанию является строкой. -</tag-desc> - -<tag-name><literal>flags</literal></tag-name> -<tag-desc> -объект со следующими свойствами: -<list type="tag"> -<tag-name><literal>last</literal></tag-name> -<tag-desc> -логическое значение, true, если данные являются последним буфером. -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -<para> -Функция фильтра может передавать свою модифицированную версию -входящего блока данных следующему фильтру тела ответа при помощи вызова -<link doc="../njs/reference.xml" id="r_sendbuffer"><literal>r.sendBuffer()</literal></link>. -Пример преобразования букв в нижний регистр в теле ответа: -<example> -function filter(r, data, flags) { - r.sendBuffer(data.toLowerCase(), flags); -} -</example> -Для отмены фильтра (блоки данных будут передаваться клиенту -без вызова <literal>js_body_filter</literal>), -можно использовать -<link doc="../njs/reference.xml" id="r_done"><literal>r.done()</literal></link>. -</para> - -<para> -Если функция фильтра изменяет длину тела ответа, то -необходимо очистить заголовок ответа <header>Content-Length</header> -(если присутствует) в -<link id="js_header_filter"><literal>js_header_filter</literal></link>, -чтобы применить поблочное кодирование. -</para> - -<para> -<note> -Так как обработчик <literal>js_body_filter</literal> -должен сразу возвращать результат, -то поддерживаются только синхронные операции, -Таким образом, асинхронные операции, например -<link doc="../njs/reference.xml" id="r_subrequest">r.subrequest()</link> -или -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link>, -не поддерживаются. -</note> -</para> - -<para> -<note> -Директива может быть указана внутри -блока <link doc="../http/ngx_http_rewrite_module.xml" id="if">if</link> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_content"> -<syntax><value>функция</value> | <value>модуль.функция</value></syntax> -<default/> -<context>location</context> -<context>if in location</context> -<context>limit_except</context> - -<para> -Задаёт функцию njs в качестве обработчика содержимого location. -Начиная с версии <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -можно ссылаться на функцию модуля. -</para> - -<para> -<note> -Директива может быть указана внутри -блока <link doc="../http/ngx_http_rewrite_module.xml" id="if">if</link> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_fetch_buffer_size"> -<syntax><value>размер</value></syntax> -<default>16k</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Задаёт <value>размер</value> буфера, который будет использоваться -для чтения и записи для -<link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_ciphers"> -<syntax><value>шифры</value></syntax> -<default>HIGH:!aNULL:!MD5</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Описывает разрешённые шифры для HTTPS-запросов -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -Шифры задаются в формате, поддерживаемом библиотекой OpenSSL. -</para> - -<para> -Полный список можно посмотреть с помощью команды -“<command>openssl ciphers</command>”. -</para> - -</directive> - - -<directive name="js_fetch_max_response_buffer_size"> -<syntax><value>размер</value></syntax> -<default>1m</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Задаёт максимальный <value>размер</value> ответа, полученного -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_protocols"> -<syntax> - [<literal>TLSv1</literal>] - [<literal>TLSv1.1</literal>] - [<literal>TLSv1.2</literal>] - [<literal>TLSv1.3</literal>]</syntax> -<default>TLSv1 TLSv1.1 TLSv1.2</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Разрешает указанные протоколы для HTTPS-запросов -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_timeout"> -<syntax><value>время</value></syntax> -<default>60s</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Задаёт таймаут при чтении и записи -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -Таймаут устанавливается не на всю передачу ответа, -а только между двумя операциями чтения. -Если по истечении этого времени данные не передавались, соединение закрывается. -</para> - -</directive> - - -<directive name="js_fetch_trusted_certificate"> -<syntax><value>файл</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Задаёт <value>файл</value> с доверенными сертификатами CA в формате PEM, -используемыми при -<link doc="../njs/reference.xml" id="fetch_verify">проверке</link> -HTTPS-сертификата -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify"> -<syntax><literal>on</literal> | <literal>off</literal></syntax> -<default>on</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Разрешает или запрещает проверку сертификата HTTPS-сервера -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify_depth"> -<syntax><value>число</value></syntax> -<default>100</default> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Устанавливает глубину проверки в цепочке HTTPS-сертификатов -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_header_filter"> -<syntax><value>функция</value> | <value>модуль.функция</value></syntax> -<default/> -<context>location</context> -<context>if in location</context> -<context>limit_except</context> -<appeared-in>0.5.1</appeared-in> - -<para> -Задаёт функцию njs в качестве фильтра заголовка ответа. -Директива позволяет менять произвольные поля заголовка ответа. -</para> - -<para> -<note> -Так как обработчик <literal>js_header_filter</literal> -должен сразу возвращать результат, -то поддерживаются только синхронные операции, -Таким образом, асинхронные операции, например -<link doc="../njs/reference.xml" id="r_subrequest">r.subrequest()</link> -или -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link>, -не поддерживаются. -</note> -</para> - -<para> -<note> -Директива может быть указана внутри -блока <link doc="../http/ngx_http_rewrite_module.xml" id="if">if</link> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_import"> -<syntax><value>модуль.js</value> | -<value>имя_экспорта from модуль.js</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.4.0</appeared-in> - -<para> -Импортирует модуль, позволяющий задавать обработчики location и переменных -на njs. -<literal>Имя_экспорта</literal> является пространством имён -при доступе к функциям модуля. -Если <literal>имя_экспорта</literal> не задано, -то пространством имён будет являться имя модуля. -<example> -js_import http.js; -</example> -В примере при доступе к экспорту в качестве -пространства имён используется имя модуля <literal>http</literal>. -Если импортируемый модуль экспортирует <literal>foo()</literal>, -то для доступа используется <literal>http.foo</literal>. -</para> - -<para> -Директив <literal>js_import</literal> может быть несколько. -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> и <literal>location</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_include"> -<syntax><value>файл</value></syntax> -<default/> -<context>http</context> - -<para> -Задаёт файл, позволяющий задавать обработчики location и переменных на njs: -<example> -nginx.conf: -js_include http.js; -location /version { - js_content version; -} - -http.js: -function version(r) { - r.return(200, njs.version); -} -</example> -</para> - -<para> -Директива устарела в версии -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -и была удалена в версии -<link doc="../njs/changes.xml" id="njs0.7.1">0.7.1</link>. -Вместо неё следует использовать директиву <link id="js_import"/>. -</para> - -</directive> - - -<directive name="js_path"> -<syntax> -<value>путь</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.3.0</appeared-in> - -<para> -Задаёт дополнительный путь для модулей njs. -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> и <literal>location</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_periodic"> -<syntax><value>функция</value> | - <value>модуль.функция</value> - [<literal>interval</literal>=<value>время</value>] - [<literal>jitter</literal>=<value>число</value>] - [<literal>worker_affinity</literal>=<value>маска</value>]</syntax> -<default/> -<context>location</context> -<appeared-in>0.8.1</appeared-in> - -<para> -Задаёт периодичность запуска обработчика содержимого. -В качестве первого аргумента обработчик получает -<link doc="../njs/reference.xml" id="periodic_session">объект сессии</link>, -также у обработчика есть доступ к глобальным объектам таким как -<link doc="../njs/reference.xml" id="ngx">ngx</link>. -</para> - -<para> -Необязательный параметр <literal>interval</literal> -задаёт интервал между двумя последовательными запусками, -по умолчанию 5 секунд. -</para> - -<para> -Необязательный параметр <literal>jitter</literal> -задаёт время, в пределах которого -случайным образом задерживается каждый запуск, -по умолчанию задержки нет. -</para> - -<para> -По умолчанию <literal>js_handler</literal> выполняется для рабочего процесса 0. -Необязательный параметр <literal>worker_affinity</literal> -позволяет указать рабочий процесс, -для которого будет выполняться обработчик содержимого location. -Рабочие процессы задаются битовой маской разрешённых к использованию рабочих -процессов. -Маска <literal>all</literal> позволяет обработчику выполняться -для всех рабочих процессов. -</para> - -<para> -Пример: -<example> -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); -} -</example> -</para> - -</directive> - - -<directive name="js_preload_object"> -<syntax><value>имя.json</value> | -<value>имя</value> from <value>файл.json</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.7.8</appeared-in> - -<para> -Предварительно загружает -<link doc="../njs/preload_objects.xml">неизменяемый объект</link> -во время конфигурации. -<literal>Имя</literal> используется в качестве имени глобальной переменной, -через которую объект доступен в коде njs. -Если <literal>имя</literal> не указано, -то будет использоваться имя файла. -<example> -js_preload_object map.json; -</example> -В примере <literal>map</literal> используется в качестве имени -во время доступа к предварительно загруженному объекту. -</para> - -<para> -Директив <literal>js_preload_object</literal> может быть несколько. -</para> - -</directive> - - -<directive name="js_set"> -<syntax> -<value>$переменная</value> <value>функция</value> | -<value>модуль.функция</value></syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> - -<para> -Задаёт <literal>функцию</literal> njs -для указанной <literal>переменной</literal>. -Начиная с <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -можно ссылаться на функцию модуля. -</para> - -<para> -Функция вызывается в момент -первого обращения к переменной для данного запроса. -Точный момент вызова функции зависит от -<link doc="../dev/development_guide.xml" id="http_phases">фазы</link>, -в которой происходит обращение к переменной. -Это можно использовать для реализации дополнительной логики, -не относящейся к вычислению переменной. -Например, если переменная указана -в директиве <link doc="ngx_http_log_module.xml" id="log_format"/>, -то её обработчик не будет выполняться до фазы записи в лог. -Этот обработчик также может использоваться для выполнения процедур -непосредственно перед освобождением запроса. -</para> - -<para> -<note> -Так как обработчик <literal>js_set</literal> -должен сразу возвращать результат, -то поддерживаются только синхронные операции, -Таким образом, асинхронные операции, например -<link doc="../njs/reference.xml" id="r_subrequest">r.subrequest()</link> -или -<link doc="../njs/reference.xml" id="settimeout">setTimeout()</link>, -не поддерживаются. -</note> -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> и <literal>location</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_shared_dict_zone"> -<syntax> - <literal>zone</literal>=<value>имя</value>:<value>размер</value> - [<literal>timeout</literal>=<value>время</value>] - [<literal>type</literal>=<literal>строка</literal>|<literal>число</literal>] - [<literal>evict</literal>]</syntax> -<default/> -<context>http</context> -<appeared-in>0.8.0</appeared-in> - -<para> -Задаёт <value>имя</value> и <value>размер</value> зоны разделяемой памяти, -в которой хранится -<link doc="../njs/reference.xml" id="dict">словарь</link> ключей и значений, -разделяемый между рабочими процессами. -</para> - -<para> -По умолчанию в качестве ключа и значения используется строка. -Необязательный параметр <literal>type</literal> -позволяет изменить тип значения на число. -</para> - -<para> -Необязательный параметр <literal>timeout</literal> задаёт время, -по завершении которого все записи в словаре удаляются из зоны. -</para> - -<para> -Необязательный параметр <literal>evict</literal> удаляет самую старую -пару ключ-значение при переполнении зоны. -</para> - -<para> -Пример: -<example> -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)); - } -</example> -</para> - -</directive> - - -<directive name="js_var"> -<syntax><value>$переменная</value> [<value>значение</value>]</syntax> -<default/> -<context>http</context> -<context>server</context> -<context>location</context> -<appeared-in>0.5.3</appeared-in> - -<para> -Объявляет -<link doc="../njs/reference.xml" id="r_variables">перезаписываемую</link> -переменную. -В качестве значения можно использовать текст, переменные и их комбинации. -Переменная не перезаписывается после перенаправления, -в отличие от переменных, созданных при помощи -директивы <link doc="ngx_http_rewrite_module.xml" id="set"/>. -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> и <literal>location</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - -</section> - - -<section id="arguments" name="Аргумент запроса"> - -<para> -Каждый HTTP-обработчик njs получает один аргумент, -<link doc="../njs/reference.xml" id="http">объект</link> запроса. -</para> - -</section> - -</module>
--- a/xml/ru/docs/index.xml Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/ru/docs/index.xml Wed Feb 14 20:06:00 2024 +0300 @@ -8,7 +8,7 @@ <article name="nginx: документация" link="/ru/docs/" lang="ru" - rev="51" + rev="52" toc="no"> @@ -99,14 +99,6 @@ <list type="bullet"> <listitem> -<link doc="njs/index.xml">Создание сценариев на njs</link> -</listitem> - -</list> - -<list type="bullet"> - -<listitem> <link url="http://www.aosabook.org/en/nginx.html">Глава “nginx” из книги “The Architecture of Open Source Applications”</link> [en] </listitem> @@ -306,11 +298,6 @@ </listitem> <listitem> -<link doc="http/ngx_http_js_module.xml"> -ngx_http_js_module</link> -</listitem> - -<listitem> <link doc="http/ngx_http_limit_conn_module.xml"> ngx_http_limit_conn_module</link> </listitem> @@ -519,11 +506,6 @@ </listitem> <listitem> -<link doc="stream/ngx_stream_js_module.xml"> -ngx_stream_js_module</link> -</listitem> - -<listitem> <link doc="stream/ngx_stream_limit_conn_module.xml"> ngx_stream_limit_conn_module</link> </listitem>
--- a/xml/ru/docs/njs/cli.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Интерфейс командной строки" - link="/ru/docs/njs/cli.html" - lang="ru" - rev="4"> - -<section> -<para> -Создание и отладка njs-скриптов может осуществляться -в командной строке. -Утилита командной строки доступна после установки -<link doc="install.xml" id="install_package">пакета</link> Linux -или после сборки из -<link doc="install.xml" id="install_sources">исходных файлов</link>. -В отличие от njs, запущенном внутри nginx, -в утилите недоступны объекты nginx -(<link doc="reference.xml" id="http">HTTP</link> и -<link doc="reference.xml" id="stream">Stream</link>). -<example> -$ 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] -} ->> -</example> -</para> - -</section> - -</article>
--- a/xml/ru/docs/njs/compatibility.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1265 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Совместимость" - link="/ru/docs/njs/compatibility.html" - lang="ru" - rev="44" - toc="no"> - -<section> - -<para> -njs совместим с -<link url="http://www.ecma-international.org/ecma-262/5.1/">ECMAScript 5.1</link> -(строгий режим) c некоторыми расширениями -<link url="http://www.ecma-international.org/ecma-262/6.0/">ECMAScript 6</link> -и позже. -Совместимость находится в стадии развития. -</para> - -<para> -Описания методов и свойств, доступных только в njs -и не соответствующих стандарту ECMAScript, доступны в -<link doc="reference.xml">справочнике</link>. -Описания методов и свойств njs, -соответствующих стандарту, доступны в -<link url="http://www.ecma-international.org/ecma-262/">спецификации -ECMAScript</link>. -</para> - -</section> - - -<section id="supported" name="Готовая функциональность"> - -<para> -<list type="bullet" compact="no"> - -<listitem> -Логические значения, числа, строки, объекты, массивы, -функции, конструкторы функций -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>) -и регулярные выражения -</listitem> - -<listitem> -ES5.1 операторы, ES7 операторы возведения в степень -</listitem> - -<listitem> -ES5.1 инструкции: -<literal>break</literal>, -<literal>catch</literal>, -<literal>continue</literal>, -<literal>do while</literal>, -<literal>else</literal>, -<literal>finally</literal>, -<literal>for</literal>, -<literal>for in</literal>, -<literal>if</literal>, -<literal>return</literal>, -<literal>switch</literal>, -<literal>throw</literal>, -<literal>try</literal>, -<literal>var</literal>, -<literal>while</literal>, -инструкции меток (labels) (<link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</listitem> - -<listitem> -ES6 инструкции: -<literal>let</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>), -<literal>const</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>), -<literal>async</literal> (<link doc="changes.xml" id="njs0.7.0">0.7.0</link>), -<literal>await</literal> (<link doc="changes.xml" id="njs0.7.0">0.7.0</link>) -</listitem> - -<listitem> -Свойства <literal>Math</literal>: -<list type="bullet"> - -<listitem> -ES6: -<literal>E</literal>, -<literal>LN10</literal>, -<literal>LN2</literal>, -<literal>LOG10E</literal>, -<literal>LOG2E</literal>, -<literal>PI</literal>, -<literal>SQRT1_2</literal>, -<literal>SQRT2</literal> -</listitem> -</list> -</listitem> - -<listitem> -Методы <literal>Math</literal>: -<list type="bullet"> - -<listitem> -ES6: -<literal>abs</literal>, -<literal>acos</literal>, -<literal>acosh</literal>, -<literal>asin</literal>, -<literal>asinh</literal>, -<literal>atan</literal>, -<literal>atan2</literal>, -<literal>atanh</literal>, -<literal>cbrt</literal>, -<literal>ceil</literal>, -<literal>clz32</literal>, -<literal>cos</literal>, -<literal>cosh</literal>, -<literal>exp</literal>, -<literal>expm1</literal>, -<literal>floor</literal>, -<literal>fround</literal>, -<literal>hypot</literal>, -<literal>imul</literal>, -<literal>log</literal>, -<literal>log10</literal>, -<literal>log1p</literal>, -<literal>log2</literal>, -<literal>max</literal>, -<literal>min</literal>, -<literal>pow</literal>, -<literal>random</literal>, -<literal>round</literal>, -<literal>sign</literal>, -<literal>sin</literal>, -<literal>sinh</literal>, -<literal>sqrt</literal>, -<literal>tan</literal>, -<literal>tanh</literal>, -<literal>trunc</literal> -</listitem> -</list> -</listitem> - -<listitem> -Свойства <literal>Number</literal>: -<list type="bullet"> - -<listitem> -ES6: -<literal>EPSILON</literal>, -<literal>MAX_SAFE_INTEGER</literal>, -<literal>MAX_VALUE</literal>, -<literal>MIN_SAFE_INTEGER</literal>, -<literal>MIN_VALUE</literal>, -<literal>NEGATIVE_INFINITY</literal>, -<literal>NaN</literal>, -<literal>POSITIVE_INFINITY</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы <literal>Number</literal>: -<list type="bullet"> - -<listitem> -ES6: -<literal>isFinite</literal>, -<literal>isInteger</literal>, -<literal>isNaN</literal>, -<literal>isSafeInteger</literal>, -<literal>parseFloat</literal>, -<literal>parseInt</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Number</literal>: -<list type="bullet"> - -<listitem> -ES6: -<literal>toExponential</literal> -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>), -<literal>toFixed</literal> -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>), -<literal>toPrecision</literal> -(<link doc="changes.xml" id="njs0.3.6">0.3.6</link>) -</listitem> -</list> - -</listitem> - -<listitem> -Методы <literal>String</literal>: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>fromCharCode</literal> -</listitem> - -<listitem> -ES6: -<literal>fromCodePoint</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>String</literal>: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>charAt</literal>, -<literal>concat</literal>, -<literal>indexOf</literal>, -<literal>lastIndexOf</literal>, -<literal>match</literal>, -<literal>replace</literal>, -<literal>search</literal>, -<literal>slice</literal>, -<literal>split</literal>, -<literal>substr</literal>, -<literal>substring</literal>, -<literal>toLowerCase</literal>, -<literal>trim</literal>, -<literal>toUpperCase</literal> -</listitem> - -<listitem> -ES6: -<literal>codePointAt</literal>, -<literal>endsWith</literal>, -<literal>includes</literal>, -<literal>repeat</literal>, -<literal>startsWith</literal> -</listitem> - -<listitem> -ES8: -<literal>padEnd</literal>, -<literal>padStart</literal> -</listitem> - -<listitem> -ES9: -<literal>trimEnd</literal> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>), -<literal>trimStart</literal> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>) -</listitem> - -<listitem> -ES12: -<literal>replaceAll</literal> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>) -</listitem> - -</list> - -</listitem> - -<listitem> -Методы <literal>Object</literal>: -<list type="bullet"> -<listitem> -ES5.1: -<literal>create</literal> (поддержка без списка свойств), -<literal>defineProperties</literal> (поддержка дескрипторов доступа -начиная с версии <link doc="changes.xml" id="njs0.3.3">0.3.3</link>), -<literal>defineProperty</literal> (поддержка дескрипторов доступа -начиная с версии <link doc="changes.xml" id="njs0.3.3">0.3.3</link>), -<literal>freeze</literal>, -<literal>getOwnPropertyDescriptor</literal>, -<literal>getOwnPropertyDescriptors</literal> -(<link doc="changes.xml" id="njs0.3.1">0.3.1</link>), -<literal>getOwnPropertyNames</literal> -(<link doc="changes.xml" id="njs0.3.1">0.3.1</link>), -<literal>getPrototypeOf</literal>, -<literal>isExtensible</literal>, -<literal>isFrozen</literal>, -<literal>isSealed</literal>, -<literal>keys</literal>, -<literal>preventExtensions</literal>, -<literal>seal</literal> -</listitem> - -<listitem> -ES6: -<literal>assign</literal> -(<link doc="changes.xml" id="njs0.3.7">0.3.7</link>) -</listitem> - -<listitem> -ES8: -<literal>entries</literal> -(<link doc="changes.xml" id="njs0.2.7">0.2.7</link>), -<literal>values</literal> -(<link doc="changes.xml" id="njs0.2.7">0.2.7</link>) -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Object</literal>: -<list type="bullet"> -<listitem> -ES5.1: -<literal>hasOwnProperty</literal>, -<literal>isPrototypeOf</literal>, -(<link doc="changes.xml" id="njs0.3.0">0.3.0</link>), -<literal>propertyIsEnumerable</literal>, -<literal>toString</literal>, -<literal>valueOf</literal> -</listitem> - -<listitem> -ES6: -<literal>is</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>), -<literal>setPrototypeOf</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>) -</listitem> - -</list> -</listitem> - -<listitem> -Методы <literal>Array</literal>: -<list type="bullet"> -<listitem> -ES5.1: -<literal>isArray</literal> -</listitem> - -<listitem> -ES6: -<literal>of</literal> -</listitem> - -<listitem> -ES13: -<literal>from</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Array</literal>: -<list type="bullet"> -<listitem> -ES5.1: -<literal>concat</literal>, -<literal>every</literal>, -<literal>filter</literal>, -<literal>forEach</literal>, -<literal>indexOf</literal>, -<literal>join</literal>, -<literal>lastIndexOf</literal>, -<literal>map</literal>, -<literal>pop</literal>, -<literal>push</literal>, -<literal>reduce</literal>, -<literal>reduceRight</literal>, -<literal>reverse</literal>, -<literal>shift</literal>, -<literal>slice</literal>, -<literal>some</literal>, -<literal>sort</literal>, -<literal>splice</literal>, -<literal>unshift</literal> -</listitem> - -<listitem> -ES6: -<literal>copyWithin</literal> -(<link doc="changes.xml" id="njs0.3.7">0.3.7</link>), -<literal>fill</literal>, -<literal>find</literal>, -<literal>findIndex</literal> -</listitem> - -<listitem> -ES7: <literal>includes</literal> -</listitem> - -<listitem> -ES13: -<literal>toReversed</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<literal>toSorted</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<literal>toSpliced</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</listitem> -</list> - -</listitem> - -<listitem> -Методы <literal>ArrayBuffer</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>isView</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>ArrayBuffer</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>slice</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Конструкторы <literal>Typed-array</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>Int8Array</literal>, -<literal>Uint8Array</literal>, -<literal>Uint8ClampedArray</literal>, -<literal>Int16Array</literal>, -<literal>Uint16Array</literal>, -<literal>Int32Array</literal>, -<literal>Uint32Array</literal>, -<literal>Float32Array</literal>, -<literal>Float64Array</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Typed-array</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>copyWithin</literal>, -<literal>every</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>fill</literal>, -<literal>filter</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>find</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>findIndex</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>forEach</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>includes</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>indexOf</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>join</literal>, -<literal>lastIndexOf</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>map</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>reduce</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>reduceRight</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>reverse</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>set</literal>, -<literal>slice</literal>, -<literal>some</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>sort</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<literal>subarray</literal>, -<literal>toString</literal> -</listitem> - -<listitem> -ES13: -<literal>toReversed</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -<literal>toSorted</literal> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</listitem> - -</list> - -</listitem> - -<listitem> -Методы <literal>Buffer</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>): -<list type="bullet"> -<listitem> -<link doc="reference.xml" id="buffer_alloc"><literal>alloc</literal></link>, -<link doc="reference.xml" id="buffer_alloc_unsafe"><literal>allocUnsafe</literal></link>, -<link doc="reference.xml" id="buffer_bytelength"><literal>byteLength</literal></link>, -<link doc="reference.xml" id="buffer_compare"><literal>compare</literal></link>, -<link doc="reference.xml" id="buffer_concat"><literal>concat</literal></link>, -<link doc="reference.xml" id="buffer_from_array"><literal>from</literal></link>, -<link doc="reference.xml" id="buffer_is_buffer"><literal>isBuffer</literal></link>, -<link doc="reference.xml" id="buffer_is_encoding"><literal>isEncoding</literal></link> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Buffer</literal>: -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>): -<list type="bullet"> -<listitem> -<link doc="reference.xml" id="buf_compare"><literal>compare</literal></link>, -<link doc="reference.xml" id="buf_copy"><literal>copy</literal></link>, -<link doc="reference.xml" id="buf_equals"><literal>equals</literal></link>, -<link doc="reference.xml" id="buf_fill"><literal>fill</literal></link>, -<link doc="reference.xml" id="buf_includes"><literal>includes</literal></link>, -<link doc="reference.xml" id="buf_indexof"><literal>indexOf</literal></link>, -<link doc="reference.xml" id="buf_lastindexof"><literal>lastIndexOf</literal></link>, -<link doc="reference.xml" id="buf_readintbe"><literal>readIntBE</literal></link>, -<literal>readInt8</literal>, -<literal>readInt16BE</literal>, -<literal>readInt32BE</literal>, -<link doc="reference.xml" id="buf_readintle"><literal>readIntLE</literal></link>, -<literal>readInt8</literal>, -<literal>readInt16LE</literal>, -<literal>readInt32LE</literal>, -<link doc="reference.xml" id="buf_readuintbe"><literal>readUIntBE</literal></link>, -<literal>readUInt8</literal>, -<literal>readUInt16BE</literal>, -<literal>readUInt32BE</literal>, -<link doc="reference.xml" id="buf_readuintle"><literal>readUIntLE</literal></link>, -<literal>readUInt8</literal>, -<literal>readUInt16LE</literal>, -<literal>readUInt32LE</literal>, -<link doc="reference.xml" id="buf_readdobulebe"><literal>readDoubleBE</literal></link>, -<link doc="reference.xml" id="buf_readdobulele"><literal>readDoubleLE</literal></link>, -<link doc="reference.xml" id="buf_readfloatbe"><literal>readFloatBE</literal></link>, -<link doc="reference.xml" id="buf_readfloatle"><literal>readFloatLE</literal></link>, -<link doc="reference.xml" id="buf_subarray"><literal>subarray</literal></link>, -<link doc="reference.xml" id="buf_slice"><literal>slice</literal></link>, -<link doc="reference.xml" id="buf_swap16"><literal>swap16</literal></link>, -<link doc="reference.xml" id="buf_swap32"><literal>swap32</literal></link>, -<link doc="reference.xml" id="buf_swap64"><literal>swap64</literal></link>, -<link doc="reference.xml" id="buf_tojson"><literal>toJSON</literal></link>, -<link doc="reference.xml" id="buf_tostring"><literal>toString</literal></link>, -<link doc="reference.xml" id="buf_write"><literal>write</literal></link>, -<link doc="reference.xml" id="buf_writeintbe"><literal>writeIntBE</literal></link>, -<literal>writeInt8</literal>, -<literal>writeInt16BE</literal>, -<literal>writeInt32BE</literal>, -<link doc="reference.xml" id="buf_writeintle"><literal>writeIntLE</literal></link>, -<literal>writeInt8</literal>, -<literal>writeInt16LE</literal>, -<literal>writeInt32LE</literal>, -<link doc="reference.xml" id="buf_writeuintbe"><literal>writeUIntBE</literal></link>, -<literal>writeUInt8</literal>, -<literal>writeUInt16BE</literal>, -<literal>writeUInt32BE</literal>, -<link doc="reference.xml" id="buf_writeuintle"><literal>writeUIntLE</literal></link>, -<literal>writeUInt8</literal>, -<literal>writeUInt16LE</literal>, -<literal>writeUInt32LE</literal>, -<link doc="reference.xml" id="buf_writedoublebe"><literal>writeDoubleBE</literal></link>, -<link doc="reference.xml" id="buf_writedoublele"><literal>writeDoubleLE</literal></link>, -<link doc="reference.xml" id="buf_writefloatbe"><literal>writeFloatBE</literal></link>, -<link doc="reference.xml" id="buf_writefloatle"><literal>writeFloatLE</literal></link> -</listitem> -</list> - -</listitem> - -<listitem> -Методы <literal>Promise</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>any</literal> -(<link doc="changes.xml" id="njs0.6.2">0.6.2</link>), -<literal> all</literal> -(<link doc="changes.xml" id="njs0.6.2">0.6.2</link>), -<literal> allSettled</literal> -(<link doc="changes.xml" id="njs0.6.2">0.6.2</link>), -<literal>reject</literal>, -<literal>resolve</literal>, -<literal>race</literal> (<link doc="changes.xml" id="njs0.6.2">0.6.2</link>) -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Promise</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>): -<list type="bullet"> -<listitem> -ES6: -<literal>catch</literal>, -<literal>finally</literal>, -<literal>then</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Function</literal>: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>apply</literal>, -<literal>bind</literal>, -<literal>call</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Свойства аксессоров прототипа <literal>RegExp</literal>: -<list type="bullet"> - -<listitem> -<literal>flags</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>), -<literal>global</literal>, -<literal>ignoreCase</literal>, -<literal>multiline</literal>, -<literal>source</literal>, -<literal>sticky</literal> (<link doc="changes.xml" id="njs0.6.0">0.6.0</link>) -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>RegExp</literal>: -<list type="bullet"> - -<listitem> -<literal>[@@replace]</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<literal>[@@split]</literal> -(<link doc="changes.xml" id="njs0.6.0">0.6.0</link>) -</listitem> - -<listitem> -ES5.1: -<literal>exec</literal>, -<literal>test</literal>, -<literal>toString</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Свойства экземпляра <literal>RegExp</literal>: -<list type="bullet"> - -<listitem> -<literal>lastIndex</literal> -</listitem> -</list> - -</listitem> - -<listitem> -<literal>RegExp</literal> -ES9 именные группы записи (<link doc="changes.xml" id="njs0.3.2">0.3.2</link>) -</listitem> - -<listitem> -Методы прототипа <literal>DataView</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>): -<list type="bullet"> - -<listitem> -ES6: -<literal>getFloat32</literal>, -<literal>getFloat64</literal>, -<literal>getInt16</literal>, -<literal>getInt32</literal>, -<literal>getInt8</literal>, -<literal>getUint16</literal>, -<literal>getUint32</literal>, -<literal>getUint8</literal>, -<literal>setFloat32</literal>, -<literal>setFloat64</literal>, -<literal>setInt16</literal>, -<literal>setInt32</literal>, -<literal>setInt8</literal>, -<literal>setUint16</literal>, -<literal>setUint32</literal>, -<literal>setUint8</literal> -</listitem> - -</list> -</listitem> - -<listitem> -Методы <literal>Date</literal>: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>now</literal>, -<literal>parse</literal>, -<literal>UTC</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы прототипа <literal>Date</literal>: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>getDate</literal>, -<literal>getDay</literal>, -<literal>getFullYear</literal>, -<literal>getHours</literal>, -<literal>getMilliseconds</literal>, -<literal>getMinutes</literal>, -<literal>getMonth</literal>, -<literal>getSeconds</literal>, -<literal>getTime</literal>, -<literal>getTimezoneOffset</literal>, -<literal>getUTCDate</literal>, -<literal>getUTCDay</literal>, -<literal>getUTCFullYear</literal>, -<literal>getUTCHours</literal>, -<literal>getUTCMilliseconds</literal>, -<literal>getUTCMinutes</literal>, -<literal>getUTCMonth</literal>, -<literal>getUTCSeconds</literal>, -<literal>toDateString</literal>, -<literal>toISOString</literal>, -<literal>toLocaleDateString</literal>, -<literal>toLocaleString</literal>, -<literal>toLocaleTimeString</literal>, -<literal>toTimeString</literal>, -<literal>toUTCString</literal>, -<literal>setDate</literal>, -<literal>setFullYear</literal>, -<literal>setHours</literal>, -<literal>setMinutes</literal>, -<literal>setMilliseconds</literal>, -<literal>setMonth</literal>, -<literal>setSeconds</literal>, -<literal>setTime</literal>, -<literal>setUTCDate</literal>, -<literal>setUTCFullYear</literal>, -<literal>setUTCHours</literal>, -<literal>setUTCMilliseconds</literal>, -<literal>setUTCMinutes</literal>, -<literal>setUTCMonth</literal>, -<literal>setUTCSeconds</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы <literal>JSON</literal>: -<list type="bullet"> - -<listitem> -ES5.1: -<literal>parse</literal>, -<literal>stringify</literal> -</listitem> -</list> - -</listitem> - -<listitem> -Методы <literal>Symbol</literal> -(<link doc="changes.xml" id="njs0.7.6">0.7.6</link>): -<list type="bullet"> - -<listitem> -<literal>for</literal>, -<literal>keyfor</literal> -</listitem> -</list> - -</listitem> - -<listitem> -ES5.1 объект <literal>arguments</literal> -(<link doc="changes.xml" id="njs0.2.5">0.2.5</link>) -</listitem> - -<listitem> -ES6 синтаксис rest параметров (без поддержки деструктуризации) -(<link doc="changes.xml" id="njs0.2.7">0.2.7</link>) -</listitem> - -<listitem> -ES5.1 global functions: -<literal>decodeURI</literal>, -<literal>decodeURIComponent</literal>, -<literal>encodeURI</literal>, -<literal>encodeURIComponent</literal>, -<literal>isFinite</literal>, -<literal>isNaN</literal>, -<literal>parseFloat</literal>, -<literal>parseInt</literal> -</listitem> - -<listitem> -Global functions (<link doc="changes.xml" id="njs0.7.6">0.7.6</link>): -<link doc="reference.xml" id="atob"><literal>atob</literal></link>, -<link doc="reference.xml" id="btoa"><literal>btoa</literal></link> -</listitem> - -<listitem> -Объекты <literal>Error</literal>: -<literal>Error</literal>, -<literal>EvalError</literal>, -<literal>InternalError</literal>, -<literal>RangeError</literal>, -<literal>ReferenceError</literal>, -<literal>SyntaxError</literal>, -<literal>TypeError</literal>, -<literal>URIError</literal> -</listitem> - -<listitem> -Функции -<link doc="reference.xml" id="cleartimeout"><literal>clearTimeout</literal></link> -и -<link doc="reference.xml" id="settimeout"><literal>setTimeout</literal></link> -(<link doc="changes.xml" id="njs0.2.0">0.2.0</link>) -</listitem> - -<listitem> -Методы <literal>File system</literal>: -<link doc="reference.xml" id="fs_accesssync"><literal>fs.accessSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="appendfilesync"><literal>fs.appendFileSync</literal></link>, -<link doc="reference.xml" id="fs_closesync"><literal>fs.closeSync</literal></link>, -<link doc="reference.xml" id="fs_existssync"><literal>fs.existsSync</literal></link> -(<link doc="changes.xml" id="njs0.8.2">0.8.2</link>), -<link doc="reference.xml" id="fs_filehandle"><literal>fs.FileHandle</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_fstatsync"><literal>fs.fstatSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_lstatsync"><literal>fs.lstatSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.1</link>), -<link doc="reference.xml" id="fs_mkdirsync"><literal>fs.mkdirSync</literal></link> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<link doc="reference.xml" id="fs_opensync"><literal>fs.openSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_promises_open"><literal>fs.promises.open</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_readdirsync"><literal>fs.readdirSync</literal></link> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<link doc="reference.xml" id="readfilesync"><literal>fs.readFileSync</literal></link>, -<link doc="reference.xml" id="fs_readsync"><literal>fs.readSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>), -<link doc="reference.xml" id="fs_realpathsync"><literal>fs.realpathSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="fs_renamesync"><literal>fs.renameSync</literal></link> -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>), -<link doc="reference.xml" id="fs_rmdirsync"><literal>fs.rmdirSync</literal></link> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>), -<link doc="reference.xml" id="fs_symlinksync"><literal>fs.symlinkSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="fs_unlinksync"><literal>fs.unlinkSync</literal></link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -<link doc="reference.xml" id="fs_writefilesync"><literal>fs.writeFileSync</literal></link> -<link doc="reference.xml" id="fs_writesync_buf"><literal>fs.writeSync</literal></link> -(<link doc="changes.xml" id="njs0.7.7">0.7.7</link>) -</listitem> - -<listitem> -<literal>fs.promises</literal> API (<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -асинхронная версия файловых методов file system. -</listitem> - -<listitem> -Методы <literal>Crypto</literal> -(<link doc="changes.xml" id="njs0.2.0">0.2.0</link>): -<link doc="reference.xml" id="crypto_createhash"><literal>crypto.createHash</literal></link>, -<link doc="reference.xml" id="crypto_createhmac"><literal>crypto.createHmac</literal></link> -</listitem> - -<listitem id="querysting"> -Методы -<link doc="reference.xml" id="querystring"><literal>Query String</literal></link> -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>): -<link doc="reference.xml" id="querystring_decode"><literal>querystring.decode</literal></link>, -<link doc="reference.xml" id="querystring_encode"><literal>querystring.encode</literal></link>, -<link doc="reference.xml" id="querystring_escape"><literal>querystring.escape</literal></link>, -<link doc="reference.xml" id="querystring_parse"><literal>querystring.parse</literal></link>, -<link doc="reference.xml" id="querystring_stringify"><literal>querystring.stringify</literal></link>, -<link doc="reference.xml" id="querystring_unescape"><literal>querystring.unescape</literal></link> -</listitem> - -<listitem id="textdecoder"> -Методы -<link doc="reference.xml" id="textdecoder"><literal>TextDecoder</literal></link> -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>): -<link doc="reference.xml" id="textdecoder_encoding"><literal>encoding</literal></link>, -<link doc="reference.xml" id="textdecoder_fatal"><literal>fatal</literal></link>, -<link doc="reference.xml" id="textdecoder_ignorebom"><literal>ignoreBOM</literal></link>, -<link doc="reference.xml" id="textdecoder_ignorebom"><literal>decode</literal></link> -</listitem> - -<listitem id="textencoder"> -Методы -<link doc="reference.xml" id="textencoder"><literal>TextEncoder</literal></link> -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>): -<link doc="reference.xml" id="textencoder_encode"><literal>encode</literal></link>, -<link doc="reference.xml" id="textencoder_encodeinto"><literal>encodeInto</literal></link> -</listitem> - -<listitem id="xml"> -Методы -<link doc="reference.xml" id="xml"><literal>XML</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>): -<link doc="reference.xml" id="xml_parse"><literal>parse</literal></link>, -<link doc="reference.xml" id="xml_c14n"><literal>xml.c14n</literal></link>, -<link doc="reference.xml" id="xml_exclusiveC14n"><literal>xml.exclusiveC14n</literal></link> -</listitem> - -<listitem id="zlib"> -Методы -<link doc="reference.xml" id="zlib"><literal>zlib</literal></link> -(<link doc="changes.xml" id="njs0.7.12">0.7.12</link>): -<link doc="reference.xml" id="zlib_deflaterawsync"><literal>deflateRawSync</literal></link>, -<link doc="reference.xml" id="zlib_deflatesync"><literal>deflateSync</literal></link>, -<link doc="reference.xml" id="zlib_inflaterawsync"><literal>inflateRawSync</literal></link> -<link doc="reference.xml" id="zlib_inflatesync"><literal>inflateSync</literal></link> -</listitem> - -<listitem> -ES6 поддержка модулей: -инструкции -<literal>export</literal> по умолчанию и -<literal>import</literal> по умолчанию -(<link doc="changes.xml" id="njs0.3.0">0.3.0</link>) -</listitem> - -<listitem> -ES6 поддержка стрелочных функций -(<link doc="changes.xml" id="njs0.3.1">0.3.1</link>) -</listitem> - -<listitem> -Шаблонные строки: -многострочные литералы, интерполяция выражений, вложенные шаблоны -(<link doc="changes.xml" id="njs0.3.2">0.3.2</link>) -</listitem> - -<listitem> -Глобальные объекты -(<link doc="changes.xml" id="njs0.3.3">0.3.3</link>): -<list type="bullet"> - -<listitem> -<link doc="reference.xml" id="console"><literal>console</literal></link> -(<link doc="changes.xml" id="njs0.8.2">0.8.2</link>): -<link doc="reference.xml" id="console_error"><literal>error</literal></link>, -<link doc="reference.xml" id="console_info"><literal>info</literal></link>, -<link doc="reference.xml" id="console_log"><literal>log</literal></link>, -<link doc="reference.xml" id="console_time"><literal>time</literal></link>, -<link doc="reference.xml" id="console_time_end"><literal>timeEnd</literal></link>, -<link doc="reference.xml" id="console_warn"><literal>warn</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="builtin_crypto"><literal>crypto</literal></link> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>): -<link doc="reference.xml" id="crypto_get_random_values"><literal>getRandomValues</literal></link>, -<link doc="reference.xml" id="crypto_subtle_encrypt"><literal>subtle.encrypt</literal></link>, -<link doc="reference.xml" id="crypto_subtle_decrypt"><literal>subtle.decrypt</literal></link>, -<link doc="reference.xml" id="crypto_subtle_derive_bits"><literal>subtle.deriveBits</literal></link>, -<link doc="reference.xml" id="crypto_subtle_derive_key"><literal>subtle.deriveKey</literal></link>, -<link doc="reference.xml" id="crypto_subtle_digest"><literal>subtle.digest</literal></link> -<link doc="reference.xml" id="crypto_subtle_export_key"><literal>subtle.exportKey</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>), -<link doc="reference.xml" id="crypto_subtle_generate_key"><literal>subtle.generateKey</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>), -<link doc="reference.xml" id="crypto_subtle_import_key"><literal>subtle.importKey</literal></link>, -<link doc="reference.xml" id="crypto_subtle_sign"><literal>subtle.sign</literal></link>, -<link doc="reference.xml" id="crypto_subtle_verify"><literal>subtle.verify</literal></link> -</listitem> - -<listitem> -псевдоним <literal>globalThis</literal> -(<link doc="changes.xml" id="njs0.3.8">0.3.8</link>), -</listitem> - -<listitem> -<link doc="reference.xml" id="njs"><literal>njs</literal></link>: -<link doc="reference.xml" id="njs_version"><literal>version</literal></link>, -<link doc="reference.xml" id="njs_version_number"><literal>version_number</literal></link> -(<link doc="changes.xml" id="njs0.7.4">0.7.4</link>), -<link doc="reference.xml" id="njs_dump"><literal>dump</literal></link>, -<link doc="reference.xml" id="njs_memory_stats"><literal>memoryStats</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="njs_on"><literal>on</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="process"><literal>process</literal></link>: -<link doc="reference.xml" id="process_argv"><literal>argv</literal></link>, -<link doc="reference.xml" id="process_env"><literal>env</literal></link>, -<link doc="reference.xml" id="process_pid"><literal>pid</literal></link>, -<link doc="reference.xml" id="process_ppid"><literal>ppid</literal></link> -</listitem> - -</list> -</listitem> - -<listitem> -Методы объекта nginx: -<list type="bullet"> - -<listitem> -<link doc="reference.xml" id="http"><literal>HTTP Request</literal></link>: -<link doc="reference.xml" id="r_done"><literal>r.done</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>), -<link doc="reference.xml" id="r_error"><literal>r.error</literal></link>, -<link doc="reference.xml" id="r_finish"><literal>r.finish</literal></link>, -<link doc="reference.xml" id="r_internal_redirect"><literal>r.internalRedirect</literal></link>, -<link doc="reference.xml" id="r_log"><literal>r.log</literal></link>, -<link doc="reference.xml" id="r_return"><literal>r.return</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_send"><literal>r.send</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_sendbuffer"><literal>r.sendBuffer</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>), -<link doc="reference.xml" id="r_send_header"><literal>r.sendHeader</literal></link>, -<link doc="reference.xml" id="r_set_return_value"><literal>r.setReturnValue</literal></link> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>), -<link doc="reference.xml" id="r_subrequest"><literal>r.subrequest</literal></link>, -<link doc="reference.xml" id="r_warn"><literal>r.warn</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="stream"><literal>Stream Session</literal></link>: -<link doc="reference.xml" id="s_allow"><literal>s.allow</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_decline"><literal>s.decline</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_deny"><literal>s.deny</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_done"><literal>s.done</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_error"><literal>s.error</literal></link>, -<link doc="reference.xml" id="s_log"><literal>s.log</literal></link>, -<link doc="reference.xml" id="s_off"><literal>s.off</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_on"><literal>s.on</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_send"><literal>s.send</literal></link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>), -<link doc="reference.xml" id="s_send_downstream"><literal>s.sendDownstream</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="s_send_upstream"><literal>s.sendUpstream</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="s_set_return_value"><literal>s.setReturnValue</literal></link> -(<link doc="changes.xml" id="njs0.7.0">0.7.0</link>), -<link doc="reference.xml" id="s_warn"><literal>s.warn</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="headers"><literal>Headers</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>): -<link doc="reference.xml" id="headers_append"><literal>append</literal></link>, -<link doc="reference.xml" id="headers_delete"><literal>delete</literal></link>, -<link doc="reference.xml" id="headers_get"><literal>get</literal></link>, -<link doc="reference.xml" id="headers_getall"><literal>getAll</literal></link>, -<link doc="reference.xml" id="headers_foreach"><literal>forEach</literal></link>, -<link doc="reference.xml" id="headers_has"><literal>has</literal></link>, -<link doc="reference.xml" id="headers_set"><literal>set</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="request"><literal>Request</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>): -<link doc="reference.xml" id="request_arraybuffer"><literal>arrayBuffer</literal></link>, -<link doc="reference.xml" id="request_headers"><literal>headers</literal></link>, -<link doc="reference.xml" id="request_json"><literal>json</literal></link>, -<link doc="reference.xml" id="request_text"><literal>text</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="response"><literal>Response</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>): -<link doc="reference.xml" id="response_arraybuffer"><literal>arrayBuffer</literal></link>, -<link doc="reference.xml" id="response_headers"><literal>headers</literal></link>, -<link doc="reference.xml" id="response_json"><literal>json</literal></link>, -<link doc="reference.xml" id="response_text"><literal>text</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx"><literal>ngx</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>): -<link doc="reference.xml" id="ngx_fetch"><literal>fetch</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>), -<link doc="reference.xml" id="ngx_log"><literal>log</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx_shared"><literal>ngx.shared</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>): -<link doc="reference.xml" id="dict_add"><literal>add</literal></link>, -<link doc="reference.xml" id="dict_clear"><literal>clear</literal></link>, -<link doc="reference.xml" id="dict_delete"><literal>delete</literal></link>, -<link doc="reference.xml" id="dict_freespace"><literal>freeSpace</literal></link>, -<link doc="reference.xml" id="dict_get"><literal>get</literal></link>, -<link doc="reference.xml" id="dict_has"><literal>has</literal></link>, -<link doc="reference.xml" id="dict_incr"><literal>incr</literal></link>, -<link doc="reference.xml" id="dict_items"><literal>items</literal></link>, -<link doc="reference.xml" id="dict_keys"><literal>keys</literal></link>, -<link doc="reference.xml" id="dict_pop"><literal>pop</literal></link>, -<link doc="reference.xml" id="dict_replace"><literal>replace</literal></link>, -<link doc="reference.xml" id="dict_set"><literal>set</literal></link>, -<link doc="reference.xml" id="dict_size"><literal>size</literal></link> -</listitem> - -</list> -</listitem> - -<listitem> -Свойства объекта nginx: -<list type="bullet"> - -<listitem> -<link doc="reference.xml" id="http"><literal>HTTP Request</literal></link>: -<link doc="reference.xml" id="r_args"><literal>r.args</literal></link>, -<link doc="reference.xml" id="r_headers_in"><literal>r.headersIn</literal></link>, -<link doc="reference.xml" id="r_headers_out"><literal>r.headersOut</literal></link>, -<link doc="reference.xml" id="r_http_version"><literal>r.httpVersion</literal></link>, -<link doc="reference.xml" id="r_internal"><literal>r.internal</literal></link>, -<link doc="reference.xml" id="r_method"><literal>r.method</literal></link>, -<link doc="reference.xml" id="r_parent"><literal>r.parent</literal></link>, -<link doc="reference.xml" id="r_raw_headers_in"><literal>r.rawHeadersIn</literal></link> -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>), -<link doc="reference.xml" id="r_raw_headers_out"><literal>r.rawHeadersOut</literal></link> -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>), -<link doc="reference.xml" id="r_raw_variables"><literal>r.rawVariables</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_remote_address"><literal>r.remoteAddress</literal></link>, -<link doc="reference.xml" id="r_request_buffer"><literal>r.requestBuffer</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_request_text"><literal>r.requestText</literal></link>, -<link doc="reference.xml" id="r_response_buffer"><literal>r.responseBuffer</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_response_text"><literal>r.responseText</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="r_status"><literal>r.status</literal></link>, -<link doc="reference.xml" id="r_uri"><literal>r.uri</literal></link>, -<link doc="reference.xml" id="r_variables"><literal>r.variables</literal></link> -(<link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="stream"><literal>Stream Session</literal></link>: -<link doc="reference.xml" id="s_remote_address"><literal>s.remoteAddress</literal></link>, -<link doc="reference.xml" id="s_raw_variables"><literal>s.rawVariables</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>), -<link doc="reference.xml" id="s_status"><literal>s.status</literal></link> -(<link doc="changes.xml" id="njs0.5.2">0.5.2</link>), -<link doc="reference.xml" id="s_variables"><literal>s.variables</literal></link> -(<link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="periodic_session"><literal>Periodic Session</literal></link> -(<link doc="changes.xml" id="njs0.8.1">0.8.1</link>): -<link doc="reference.xml" id="periodic_session_raw_variables"><literal>PeriodicSession.rawVariables</literal></link>, -<link doc="reference.xml" id="periodic_session_variables"><literal>PeriodicSession.variables</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="request"><literal>Request</literal></link> -(<link doc="changes.xml" id="njs0.7.10">0.7.10</link>): -<link doc="reference.xml" id="request_bodyused"><literal>bodyUsed</literal></link>, -<link doc="reference.xml" id="request_cache"><literal>cache</literal></link>, -<link doc="reference.xml" id="request_credentials"><literal>credentials</literal></link>, -<link doc="reference.xml" id="request_method"><literal>method</literal></link>, -<link doc="reference.xml" id="request_mode"><literal>mode</literal></link>, -<link doc="reference.xml" id="request_url"><literal>url</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="response"><literal>Response</literal></link> -(<link doc="changes.xml" id="njs0.5.1">0.5.1</link>): -<link doc="reference.xml" id="response_bodyused"><literal>bodyUsed</literal></link>, -<link doc="reference.xml" id="response_ok"><literal>ok</literal></link>, -<link doc="reference.xml" id="response_redirect"><literal>redirected</literal></link>, -<link doc="reference.xml" id="response_status"><literal>status</literal></link>, -<link doc="reference.xml" id="response_statustext"><literal>statusText</literal></link>, -<link doc="reference.xml" id="response_type"><literal>type</literal></link>, -<link doc="reference.xml" id="response_url"><literal>url</literal></link> -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx"><literal>ngx</literal></link> -(<link doc="changes.xml" id="njs0.5.0">0.5.0</link>): -<link doc="reference.xml" id="ngx_build"><literal>build</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_conf_file_path"><literal>conf_file_path</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_conf_prefix"><literal>conf_prefix</literal></link> -(<link doc="changes.xml" id="njs0.7.8">0.7.8</link>), -<link doc="reference.xml" id="ngx_error_log_path"><literal>error_log_path</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_prefix"><literal>prefix</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_version"><literal>version</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_version_number"><literal>version_number</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>), -<link doc="reference.xml" id="ngx_worker_id"><literal>worker_id</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>) -</listitem> - -<listitem> -<link doc="reference.xml" id="ngx_shared"><literal>ngx.shared</literal></link> -(<link doc="changes.xml" id="njs0.8.0">0.8.0</link>): -<link doc="reference.xml" id="dict_capacity"><literal>capacity</literal></link>, -<link doc="reference.xml" id="dict_name"><literal>name</literal></link>, -<link doc="reference.xml" id="dict_name"><literal>type</literal></link> -</listitem> - -</list> -</listitem> - -</list> -</para> - -</section> - -</article>
--- a/xml/ru/docs/njs/examples.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,331 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Примеры использования" - link="/ru/docs/njs/examples.html" - lang="ru" - rev="22"> - -<section id="summary"> - -<para> -Примеры работают начиная с версии -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>. -</para> - -</section> - - -<section id="helloword" name="Hello World"> - -<para> -<path>nginx.conf</path>: -<example> -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} -</example> -</para> - -<para> -<literal>http.js</literal>: -<example> -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; -</example> -</para> - -</section> - - -<section id="http_auth" name="HTTP-авторизация"> - - -<section id="jwt" name="Создание HS JWT"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -js_set $jwt http.jwt; -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - - -<section id="secure_link" name="Создание secure_link хэша"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -js_set $new_foo http.create_secure_link; -#... - -location / { - secure_link $cookie_foo; - secure_link_md5 "$uri mykey"; - #... -} - -location @login { - add_header Set-Cookie "foo=$new_foo; Max-Age=60"; - return 302 /; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -function create_secure_link(r) { - return require('crypto').createHash('md5') - .update(r.uri).update(" mykey") - .digest('base64url'); -} - -export default {create_secure_link}; -</example> -</para> - -</section> - - -<section id="jwt_field" name="Получение произвольного поля JWT - как значение переменной nginx"> - -<para> -В данном примере из JWT payload извлекается поле <literal>sub</literal>. -JWT-токен извлекается из заголовка <header>Authorization</header>. -</para> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -js_set $jwt_payload_sub http.jwt_payload_sub; - -server { - #... - - location /jwt { - return 200 $jwt_payload_sub; - } -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - -</section> - - -<section id="http_proxying" name="HTTP-проксирование"> - - -<section id="fast_response" name="Возвращение самого быстрого ответа от прокси"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -location /start { - js_content http.content; -} - -location /foo { - proxy_pass http://backend1; -} - -location /bar { - proxy_pass http://backend2; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - - -<section id="subrequests_chaining" name="Построение цепочки подзапросов"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -location /start { - js_content http.content; -} - -location /auth { - proxy_pass http://auth_backend; -} - -location /backend { - proxy_pass http://backend; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -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}; -</example> -</para> - -</section> - -</section> - - -<section id="misc" name="Разное"> - - -<section id="redirect" name="Внутренняя переадресация"> - -<para> -<path>nginx.conf</path>: -<example> -js_import http.js; - -location /redirect { - js_content http.redirect; -} - -location @named { - return 200 named; -} -</example> -</para> - -<para> -<path>http.js</path>: -<example> -function redirect(r) { - r.internalRedirect('@named'); -} - -export default {redirect}; -</example> -</para> - -</section> - -</section> - -</article>
--- a/xml/ru/docs/njs/index.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,232 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Сценарный язык njs" - link="/ru/docs/njs/index.html" - lang="ru" - rev="34" - toc="no"> - -<section id="summary"> - -<para> -njs - это подмножество языка JavaScript, позволяющее -расширить функциональность nginx. -njs совместим с -<link url="http://www.ecma-international.org/ecma-262/5.1/">ECMAScript 5.1</link> -(строгий режим) c некоторыми расширениями -<link url="http://www.ecma-international.org/ecma-262/6.0/">ECMAScript 6</link> -и позже. -Совместимость находится в стадии <link doc="compatibility.xml">развития</link>. -</para> - -</section> - - -<section id="links"> - -<para> -<list type="bullet"> - -<listitem> -<link doc="install.xml"/> -</listitem> - -<listitem> -<link doc="changes.xml">Изменения в njs</link> -</listitem> - -<listitem> -<link doc="reference.xml"/> -</listitem> - -<listitem> -<link url="https://github.com/nginx/njs-examples/">Примеры использования</link> -</listitem> - -<listitem> -<link doc="security.xml">Безопасность</link> [en] -</listitem> - -<listitem> -<link doc="compatibility.xml"/> -</listitem> - -<listitem> -<link doc="cli.xml"/> -</listitem> - -<listitem> -<link doc="preload_objects.xml"/> -</listitem> - -<listitem> -<link id="tested_os_and_platforms">Протестированные ОС и платформы</link> -</listitem> - -</list> -</para> - -<para> -<list type="bullet"> - -<listitem> -<link doc="../http/ngx_http_js_module.xml"> -ngx_http_js_module</link> -</listitem> - -<listitem> -<link doc="../stream/ngx_stream_js_module.xml"> -ngx_stream_js_module</link> -</listitem> - -</list> -</para> - -<para> -<list type="bullet"> - -<listitem> -<link doc="typescript.xml"/> -</listitem> - -<listitem> -<link doc="node_modules.xml"/> -</listitem> - -</list> -</para> - -</section> - - -<section id="usecases" name="Сценарии использования"> - -<para> -<list type="bullet"> - -<listitem> -Комплексное управление доступом и проверка защиты при помощи njs -до получения запроса сервером группы -</listitem> - -<listitem> -Управление заголовками ответа -</listitem> - -<listitem> -Создание гибких асинхронных обработчиков содержимого и фильтров -</listitem> - -</list> -Подробнее о сценариях использования -см. в <link url="https://github.com/nginx/njs-examples/">примерах</link> -и <link url="https://www.nginx.com/blog/tag/nginx-javascript-module/">блогпостах</link>. -</para> - -</section> - - -<section id="example" name="Базовый пример HTTP"> - -<para> -Чтобы использовать njs в nginx, необходимо: -<list type="bullet"> - -<listitem> -<para> -<link doc="install.xml">установить</link> njs -</para> -</listitem> - -<listitem id="hello_world"> -<para> -создать файл сценария njs, например <path>http.js</path>. -Описание свойств и методов языка njs -см. в <link doc="reference.xml">справочнике</link>. -<example> -function hello(r) { - r.return(200, "Hello world!"); -} - -export default {hello}; -</example> -</para> -</listitem> - -<listitem> - -<para> -в файле <path>nginx.conf</path> включить -модуль <link doc="../http/ngx_http_js_module.xml">ngx_http_js_module</link> -и указать директиву -<link doc="../http/ngx_http_js_module.xml" id="js_import">js_import</link> -с файлом сценария <path>http.js</path>: -<example> -load_module modules/ngx_http_js_module.so; - -events {} - -http { - js_import http.js; - - server { - listen 8000; - - location / { - js_content http.hello; - } - } -} -</example> -</para> -</listitem> - -</list> -Также доступна отдельная утилита <link doc="cli.xml">командной строки</link>, -которая может использоваться независимо от nginx для разработки и отладки njs. -</para> - -</section> - - -<section id="tested_os_and_platforms" - name="Протестированные ОС и платформы"> - -<para> -<list type="bullet"> - -<listitem> -FreeBSD / amd64; -</listitem> - -<listitem> -Linux / x86, amd64, arm64, ppc64el; -</listitem> - -<listitem> -Solaris 11 / amd64; -</listitem> - -<listitem> -macOS / x86_64; -</listitem> - -</list> -</para> - -</section> - - -<section id="presentation" name="Презентация на nginx.conf 2018"> - -<para><video id="Jc_L6UffFOs" /></para> - -</section> - -</article>
--- a/xml/ru/docs/njs/install.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,83 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Загрузка и установка" - link="/ru/docs/njs/install.html" - lang="ru" - rev="3"> - -<section id="install_package" name="Установка пакета Linux"> - -<para> -Для установки модулей njs на Linux могут быть использованы -<link doc="../../linux_packages.xml" id="dynmodules">пакеты</link>: -<list type="bullet"> - -<listitem> -<literal>nginx-module-njs</literal> — -<link doc="../ngx_core_module.xml" id="load_module">динамические</link> модули -njs -</listitem> - -<listitem> -<literal>nginx-module-njs-dbg</literal> — debug-символы для -пакета <literal>nginx-module-njs</literal> -</listitem> - -</list> -</para> - -<para> -После установки пакетов необходимо загрузить динамические модули njs при помощи -директивы -<link doc="../ngx_core_module.xml" id="load_module"><literal>load_module</literal></link>: -<example> -load_module modules/ngx_http_js_module.so; -</example> -или -<example> -load_module modules/ngx_stream_js_module.so; -</example> -</para> - -</section> - - -<section id="install_sources" name="Установка из исходных файлов"> - -<para> -<link url="http://hg.nginx.org/njs">Репозиторий</link> -с исходным кодом njs можно клонировать следующей командой: -(необходим клиент <link url="https://www.mercurial-scm.org">Mercurial</link>): -<example> -hg clone http://hg.nginx.org/njs -</example> -Затем модули необходимо собрать из -корневого каталога <link doc="../configure.xml">nginx</link> с помощью -конфигурационного параметра <literal>--add-module</literal>: -<example> -./configure --add-module=<value>path-to-njs</value>/nginx -</example> -Модули также можно собрать как -<link doc="../ngx_core_module.xml" id="load_module">динамические</link>: -<example> -./configure --add-dynamic-module=<value>path-to-njs</value>/nginx -</example> -</para> - -<para> -Чтобы собрать только <link doc="cli.xml">утилиту</link> командной строки njs -необходимо запустить -команды <literal>./configure</literal> и <literal>make njs</literal> -из корневого каталога njs. -Утилита доступна как <literal>./build/njs</literal>. -</para> - -</section> - -</article>
--- a/xml/ru/docs/njs/node_modules.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,546 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Использование модулей Node.js в njs" - link="/ru/docs/njs/node_modules.html" - lang="en" - rev="6"> - -<section id="intro"> - -<para> -Часто разработчику приходится использовать сторонний код и, -как правило, такой код доступен в виде библиотеки. -В JavaScript концепция модулей является новой и -до недавнего времени не была стандартизированa. -До сих пор множество платформ или браузеров не поддерживают модули, -по этой причине практически невозможно повторно использовать код. -В данной статье приводятся способы повторного использования -кода в njs при помощи <link url="https://nodejs.org/">Node.js</link>. -</para> - -<note> -В примерах статьи используется функциональность -<link doc="index.xml">njs</link> -<link doc="changes.xml" id="njs0.3.8">0.3.8</link> -</note> - -<para> -При добавлении стороннего кода в njs -может возникнуть несколько проблем: - -<list type="bullet"> - -<listitem> -большое количество файлов, ссылающихся друг на друга, и их зависимости -</listitem> - -<listitem> -платформозависимые API -</listitem> - -<listitem> -языковые конструкции нового стандарта -</listitem> - -</list> -</para> - -<para> -Однако это не является чем-то новым или специфичным для njs. -Разработчикам JavaScript приходится часто иметь дело с подобными случаями, -например при поддержке нескольких несхожих платформ -с разными свойствами. -Данные проблемы можно разрешить при помощи следующих инструментов: - -<list type="bullet"> - -<listitem> -Большое количество файлов, ссылающихся друг на друга, и их зависимости -<para> -Решение: слияние всего независимого кода в один файл. -Для этих целей могут использоваться утилиты -<link url="http://browserify.org/">browserify</link> или -<link url="https://webpack.js.org/">webpack</link>, -позволяющие преобразовать проект в один файл, содержащий -код и все зависимости. -</para> -</listitem> - -<listitem> -Платформозависимые API -<para> -Решение: использование библиотек, реализующих подобные API -в платформонезависимом режиме, однако в ущерб производительности. -Определённая функциональность может быть также реализована при помощи -<link url="https://polyfill.io/v3/">polyfill</link>. -</para> -</listitem> - -<listitem> -Языковые конструкции нового стандарта -<para> -Решение: трансплирование кода— -ряд преобразований, -заменяющих новые функции языка в соответствии со старым стандартом. -Для этих целей может использоваться -<link url="https://babeljs.io/"> babel</link>. -</para> -</listitem> - -</list> -</para> - -<para> -В статье также используются две относительно большие -библиотеки на основе npm: - -<list type="bullet"> - -<listitem> -<link url="https://www.npmjs.com/package/protobufjs">protobufjs</link>— -библиотека для создания и парсинга protobuf-сообщений, используемая -протоколом <link url="https://grpc.io/">gRPC</link> -</listitem> - -<listitem> -<link url="https://www.npmjs.com/package/dns-packet">dns-packet</link>— -библиотека для обработки пакетов протокола DNS -</listitem> - -</list> -</para> - -</section> - - -<section id="environment" name="Окружение"> - -<para> -<note> -В статье описываются общие принципы работы -и не ставится цель описания подробных сценариев работы с Node.js -и JavaScript. -Перед выполнением команд -необходимо ознакомиться с документацией соответствующих пакетов. -</note> -Сначала, предварительно установив и запустив Node.js, необходимо создать -пустой проект и установить зависимости; -для выполнения нижеперечисленных команд необходимо -находиться в рабочем каталоге: -<example> -$ 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 -</example> -</para> - -</section> - - -<section id="protobuf" name="Protobufjs"> - -<para> -Библиотека предоставляет парсер -для определения интерфейса <literal>.proto</literal>, -а также генератор кода для парсинга и генерации сообщений. -</para> - -<para> -В данном примере используется -файл -<link url="https://github.com/grpc/grpc/blob/master/examples/protos/helloworld.proto">helloworld.proto</link> -из примеров gRPC. -Целью является создание двух сообщений: -<literal>HelloRequest</literal> и -<literal>HelloResponse</literal>. -Также используется -<link url="https://github.com/protobufjs/protobuf.js/blob/master/README.md#reflection-vs-static-code">статический</link> -режим protobufjs вместо динамически генерируемых классов, так как -njs не поддерживает динамическое добавление новых функций -из соображений безопасности. -</para> - -<para> -Затем устанавливается библиотека, -из определения протокола генерируется код JavaScript, -реализующий маршалинг сообщений: -<example> -$ npm install protobufjs -$ npx pbjs -t static-module helloworld.proto > static.js -</example> -</para> - -<para> -Таким образом файл <literal>static.js</literal> становится новой зависимостью, -хранящей необходимый код для реализации обработки сообщений. -Функция <literal>set_buffer()</literal> содержит код, использующий -библиотеку для создания буфера с сериализованным -сообщением <literal>HelloRequest</literal>. -Код находится в файле <literal>code.js</literal>: -<example> -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); -</example> -</para> - -<para> -Для проверки работоспособности необходимо выполнить код при помощи node: -<example> -$ node ./code.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] -</example> -Результатом является закодированный фрейм <literal>gRPC</literal>. -Теперь фрейм можно запустить с njs: -<example> -$ njs ./code.js -Thrown: -Error: Cannot find module "./static.js" - at require (native) - at main (native) -</example> -</para> - -<para> -Так как модули не поддерживаются, то операция завершается получением исключения. -В этом случае можно использовать утилиту <literal>browserify</literal> -или другую подобную утилиту. -</para> - -<para> -Попытка обработки файла <literal>code.js</literal> завершится -большим количеством JS-кода, который предполагается запускать в браузере, -то есть сразу после загрузки. -Однако необходимо получить другой результат— -экспортируемую функцию, на которую -можно сослаться из конфигурации nginx. -Для этого потребуется создание кода-обёртки. -<note> -В целях упрощения в примерах данной статьи -используется <link doc="cli.xml">интерфейс комадной строки</link> njs. -На практике для запуска кода обычно используется njs-модуль для nginx. -</note> -</para> - -<para> -Файл <literal>load.js</literal> содержит код, загружающий библиотеку, -храняющую дескриптор в глобальном пространстве имён: -<example> -global.hello = require('./static.js'); -</example> -Данный код будет заменён объединённым содержимым. -Код будет использовать дескриптор "<literal>global.hello</literal>" для доступа -к библиотеке. -</para> - -<para> -Затем для получения всех зависимостей в один файл -код обрабатыается утилитой <literal>browserify</literal>: -<example> -$ npx browserify load.js -o bundle.js -d -</example> -В результате генерируется объёмный файл, содержащий все зависимости: -<example> -(function(){function...... -... -... -},{"protobufjs/minimal":9}]},{},[1]) -//# sourceMappingURL.............. -</example> -Для получения результирующего файла "<literal>njs_bundle.js</literal>" -необходимо объединить "<literal>bundle.js</literal>" и следующий код: -<example> -// Пример использования библиотеки 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); -</example> -Для проверки работоспособности необходимо запустить файл при помощи node: -<example> -$ node ./njs_bundle.js -Uint8Array [ - 0, 0, 0, 0, 12, 10, - 10, 84, 101, 115, 116, 83, - 116, 114, 105, 110, 103 -] -</example> -Дальнейшие шаги выполняются при помощи njs: -<example> -$ njs ./njs_bundle.js -Uint8Array [0,0,0,0,12,10,10,84,101,115,116,83,116,114,105,110,103] -</example> -Теперь необходимо задействовать njs API для преобразования -массива в байтовую строку для дальнейшего использования модулем nginx. -Данный код необходимо добавить перед строкой -<literal>return frame; }</literal>: -<example> -if (global.njs) { - return String.bytesFrom(frame) -} -</example> -Проверка работоспособности: -<example> -$ 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 -</example> -Экспортируемая функция получена. -Парсинг ответа может быть сделан аналогичным способом: -<example> -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); -} -</example> -</para> - -</section> - - -<section id="dnspacket" name="Пакет DNS"> - -<para> -В примере используется библиотека для создания и парсинга пакетов DNS. -Эта библиотека, а также её зависимости, -использует современные языковые конструкции, не поддерживаемые в njs. -Для поддержки таких конструкций -потребуется дополнительный шаг: транспилирование исходного кода. -</para> - -<para> -Необходимо установить дополнительные пакеты node: -<example> -$ npm install @babel/core @babel/cli @babel/preset-env babel-loader -$ npm install webpack webpack-cli -$ npm install buffer -$ npm install dns-packet -</example> -Файл конфигурации webpack.config.js: -<example> -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'] - } - } - }] - } -}; -</example> -В данном случае используется режим "<literal>production</literal>". -Конструкция "<literal>eval</literal>" не используется, так как -не поддерживается njs. -Точкой входа является файл <literal>load.js</literal>: -<example> -global.dns = require('dns-packet') -global.Buffer = require('buffer/').Buffer -</example> -Сначала необходимо создать единый файл для библиотек, как в предыдущих примерах: -<example> -$ npx browserify load.js -o bundle.js -d -</example> -Затем необходимо обработать утилитой webpack, что также запускает babel: -<example> -$ npx webpack --config webpack.config.js -</example> -Команда создаёт файл <literal>dist/wp_out.js</literal>, являющийся -трансплицированной версией <literal>bundle.js</literal>. -Далее необходимо объединить этот файл с <literal>code.js</literal>, -хранящим код: -<example> -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; -} -</example> -В данном примере генерируемый код не обёрнут в функцию, -явного вызова не требуется. -Результат доступен в каталоге "<literal>dist</literal>": -<example> -$ cat dist/wp_out.js code.js > njs_dns_bundle.js -</example> -Далее осуществляется вызов кода в конце файла: -<example> -var b = set_buffer(global.dns); -console.log(b); -</example> -И затем выполнение кода при помощи node: -<example> -$ 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 -] -</example> -Тестирование и запуск кода вместе с njs: -<example> -$ 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] -</example> -</para> - -<para> -Ответ можно распарсить следующим способом: -<example> -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', согласно запросу выше -} -</example> - -</para> - -</section> - -</article>
--- a/xml/ru/docs/njs/preload_objects.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,76 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Предзагруженные объекты" - link="/ru/docs/njs/preload_objects.html" - lang="ru" - rev="2" - toc="no"> - -<section id="summary"> - -<para> -Для каждого входящего запроса в njs создаётся отдельная виртуальная машина. -Это позволяет прогнозировать предсказуемое поглощение памяти -или осуществить изоляцию запросов. -Однако поскольку все запросы являются изолированными, то -если обработчику запроса необходимо получить доступ к данным, -ему нужно сначала их прочитать самому. -Это неэффективно, особенно если объём данных большой. -</para> - -<para> -Это ограничение можно обойти -при помощи разделяемого предзагруженного объекта. -Такие объекты создаются неизменяемыми и не имеют цепочки прототипов: -у них нет возможности -изменить значения или добавить/удалить свойства в объектах/массивах. -</para> - -</section> - - -<section id="working_with_preload_objects" - name="Работа с предзагруженными объектами"> - -<para> -Примеры работы с предзагруженными объектами в njs: - -<list type="bullet"> - -<listitem> -доступ к свойствам по имени: -<programlisting> -preloaded_object.prop_name -preloaded_object[prop_name] -</programlisting> -</listitem> - -<listitem> -перечисление свойств: -<programlisting> -for (i in preloaded_object_name) { - ... -} -</programlisting> -</listitem> - -<listitem> -применение встроенных методов, не изменяющих состояние, -при помощи <literal>call()</literal>: -<programlisting> -Array.prototype.filter.call(preloaded_object_name, ...) -</programlisting> -</listitem> - -</list> -</para> - -</section> - -</article>
--- a/xml/ru/docs/njs/reference.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1606 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Справочник" - link="/ru/docs/njs/reference.html" - lang="ru" - rev="59"> - -<section id="summary"> - -<para> -<link doc="index.xml">njs</link> предоставляет объекты, методы и свойства -для расширения функциональности nginx. -</para> - -<para> -Справочник содержит описания методов, свойств и модулей, -доступных только в njs и не соответствующих стандарту ECMAScript. -Описания методов и свойств njs, -соответствующих стандарту, доступны в -<link url="http://www.ecma-international.org/ecma-262/">спецификации -ECMAScript</link>. -Список всех методов и свойств njs доступен в разделе -<link doc="compatibility.xml">Совместимость</link>. -</para> - -</section> - - -<section id="http_stream" name="Объекты nginx"> - - -<section id="http" name="HTTP-запрос"> - -<para> -Объект <literal>HTTP</literal> доступен только в -модуле <link doc="../http/ngx_http_js_module.xml">ngx_http_js_module</link>. -Все строки в объекте <literal>HTTP</literal> являются -<link id="string">байтовыми строками</link>. - -<list type="tag"> - -<tag-name id="r_args"><literal>r.args{}</literal></tag-name> -<tag-desc> -объект аргументов запроса, только чтение -</tag-desc> - -<tag-name id="r_error"><literal>r.error(<value>строка</value>)</literal></tag-name> -<tag-desc> -записывает <literal>строку</literal> в лог-файл ошибок -на уровне лога <literal>error</literal> -</tag-desc> - -<tag-name id="r_finish"><literal>r.finish()</literal></tag-name> -<tag-desc> -завершает отправку ответа клиенту -</tag-desc> - -<tag-name id="r_headers_in"><literal>r.headersIn{}</literal></tag-name> -<tag-desc> -объект входящих заголовков, только чтение. -<para> -Доступ к заголовку запроса <literal>Foo</literal> -можно получить при помощи синтаксиса: -<literal>headersIn.foo</literal> или <literal>headersIn['Foo']</literal>. -</para> - -<para> -Заголовки запроса -<header>Authorization</header>, -<header>Content-Length</header>, -<header>Content-Range</header>, -<header>Content-Type</header>, -<header>ETag</header>, -<header>Expect</header>, -<header>From</header>, -<header>Host</header>, -<header>If-Match</header>, -<header>If-Modified-Since</header>, -<header>If-None-Match</header>, -<header>If-Range</header>, -<header>If-Unmodified-Since</header>, -<header>Max-Forwards</header>, -<header>Proxy-Authorization</header>, -<header>Referer</header>, -<header>Transfer-Encoding</header> и -<header>User-Agent</header> -могут иметь только одно значение поля -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>). -Дубликаты значений поля в заголовке запроса <header>Cookie</header> -разделяются точкой с запятой (<literal>;</literal>). -Дубликаты значений поля во всех остальных заголовках запроса -разделяются запятой. -</para> -</tag-desc> - -<tag-name id="r_headers_out"><literal>r.headersOut{}</literal></tag-name> -<tag-desc> -объект исходящих заголовков, доступно для записи. -<para> -Доступ к заголовку ответа <literal>Foo</literal> -можно получить при помощи синтаксиса: -<literal>headersOut.foo</literal> или <literal>headersOut['Foo']</literal>. -</para> - -<para> -Значения полей многозначных заголовков ответа -(<link doc="changes.xml" id="njs0.4.0">0.4.0</link>) -можно задать при помощи синтаксиса: -<example> -r.headersOut['Foo'] = ['a', 'b'] -</example> -результат: -<example> -Foo: a -Foo: b -</example> -Все предыдущие значения поля заголовка ответа <header>Foo</header> -будут удалены. -</para> - -<para> -В стандартных заголовках ответа, -поля которых могут принимать только одно значение, например -<header>Content-Type</header>, -учитывается только последний элемент массива. -Значения поля в заголовке ответа <header>Set-Cookie</header> -всегда возвращаются в виде массива. -Дубликаты значений поля в заголовках ответа -<header>Age</header>, -<header>Content-Encoding</header>, -<header>Content-Length</header>, -<header>Content-Type</header>, -<header>ETag</header>, -<header>Expires</header>, -<header>Last-Modified</header>, -<header>Location</header>, -<header>Retry-After</header> -игнорируются. -Дубликаты значений поля в других заголовках ответов -разделяются при помощи запятой. -</para> -</tag-desc> - -<tag-name id="r_http_version"><literal>r.httpVersion</literal></tag-name> -<tag-desc> -версия HTTP, только чтение -</tag-desc> - -<tag-name id="r_internal_redirect"><literal>r.internalRedirect(<value>uri</value>)</literal></tag-name> -<tag-desc> -осуществляет внутреннее перенаправление на указанный <literal>uri</literal>. -Если uri начинается с префикса “<literal>@</literal>”, -то он считается именованным location. -Перенаправление осуществляется после завершения выполнения обработчика. -</tag-desc> - -<tag-name id="r_log"><literal>r.log(<value>строка</value>)</literal></tag-name> -<tag-desc> -записывает <literal>строку</literal> в лог-файл ошибок -на уровне лога <literal>info</literal> -</tag-desc> - -<tag-name id="r_method"><literal>r.method</literal></tag-name> -<tag-desc> -HTTP метод, только чтение -</tag-desc> - -<tag-name id="r_parent"><literal>r.parent</literal></tag-name> -<tag-desc> -ссылается на родительский объект запроса -</tag-desc> - -<tag-name id="r_remote_address"><literal>r.remoteAddress</literal></tag-name> -<tag-desc> -адрес клиента, только чтение -</tag-desc> - -<tag-name id="r_raw_headers_in"><literal>r.rawHeadersIn{}</literal></tag-name> -<tag-desc> -возвращает массив пар ключей и значений -таким же, каким он был получен от клиента -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>). -<para> -Например для следующих заголовков запроса: -<example> -Host: localhost -Foo: bar -foo: bar2 -</example> -результат <literal>r.rawHeadersIn</literal>: -<example> -[ - ['Host', 'localhost'], - ['Foo', 'bar'], - ['foo', 'bar2'] -] -</example> -Значения полей всех заголовков <literal>foo</literal> -можно получить при помощи синтаксиса: -<example> -r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1]) -</example> -результат: -<example> -['bar', 'bar2'] -</example> -Имена полей заголовков не приводятся к нижнему регистру, -дубликаты значений поля не объединяются. -</para> -</tag-desc> - -<tag-name id="r_raw_headers_out"><literal>r.rawHeadersOut{}</literal></tag-name> -<tag-desc> -возвращает массив пар ключей и значений заголовков ответа -(<link doc="changes.xml" id="njs0.4.1">0.4.1</link>). -Имена полей заголовков не приводятся к нижнему регистру, -дубликаты значений поля не объединяются. -</tag-desc> - -<tag-name id="r_request_body"><literal>r.requestBody</literal></tag-name> -<tag-desc> -возвращает тело запроса клиента, если оно не было -записано во временный файл. -Чтобы убедиться, что тело запроса клиента находится в памяти, -его размер должен быть ограничен -<link doc="../http/ngx_http_core_module.xml" id="client_max_body_size"/>, -и также необходимо установить достаточный размер буфера при помощи -<link doc="../http/ngx_http_core_module.xml" id="client_body_buffer_size"/>. -Свойство доступно только в директиве -<link doc="../http/ngx_http_js_module.xml" id="js_content"/>. -</tag-desc> - -<tag-name id="r_response_body"><literal>r.responseBody</literal></tag-name> -<tag-desc> -хранит тело ответа <link id="r_subrequest">подзапроса</link>, только чтение. -Размер <literal>r.responseBody</literal> ограничивается директивой -<link doc="../http/ngx_http_core_module.xml" id="subrequest_output_buffer_size"/>. -</tag-desc> - -<tag-name id="r_return"><literal>r.return(код[, строка])</literal></tag-name> -<tag-desc> -отправляет -клиенту полный ответ с указанным <literal>кодом</literal> -<para> -Можно задать или URL перенаправления -(для кодов 301, 302, 303, 307 и 308), -или текст тела ответа (для остальных кодов) в качестве второго аргумента -</para> -</tag-desc> - -<tag-name id="r_send"><literal>r.send(<value>строка</value>)</literal></tag-name> -<tag-desc> -отправляет часть тела ответа клиенту -</tag-desc> - -<tag-name id="r_send_header"><literal>r.sendHeader()</literal></tag-name> -<tag-desc> -отправляет заголовки HTTP клиенту -</tag-desc> - -<tag-name id="r_status"><literal>r.status</literal></tag-name> -<tag-desc> -статус, доступно для записи -</tag-desc> - -<tag-name id="r_subrequest"><literal>r.subrequest(<value>uri</value>[, -<value>options</value>[, <value>callback</value>]])</literal></tag-name> -<tag-desc> -создаёт подзапрос с заданными <literal>uri</literal> и -<literal>options</literal> и устанавливает -необязательный <literal>callback</literal> завершения. - -<para> -<link doc="../dev/development_guide.xml.xml" id="http_subrequests">Подзапрос</link> -использует входящие заголовки клиентского запроса. -Для отправки на проксируемый сервер заголовков, отличных от оригинальных, -может использоваться директива -<link doc="../http/ngx_http_proxy_module.xml" id="proxy_set_header"/>. -Для отправки на проксируемый сервер нового набора заголовков -может использоваться директива -<link doc="../http/ngx_http_proxy_module.xml" id="proxy_pass_request_headers"/>. -</para> - -<para> -Если <literal>options</literal> является строкой, то в ней -содержится срока аргументов подзапроса. -В противном случае ожидается, что <literal>options</literal> является -объектом со следующими ключами: -<list type="tag"> -<tag-name><literal>args</literal></tag-name> -<tag-desc> -строка с аргументами, по умолчанию используется пустая строка -</tag-desc> -<tag-name><literal>body</literal></tag-name> -<tag-desc> -тело запроса, -по умолчанию используется тело запроса родительского объекта запроса -</tag-desc> - -<tag-name><literal>method</literal></tag-name> -<tag-desc> -метод HTTP, по умолчанию используется метод <literal>GET</literal> -</tag-desc> - -<tag-name><literal>detached</literal></tag-name> -<tag-desc> -логический флаг (<link doc="changes.xml" id="njs0.3.9">0.3.9</link>), -если <literal>true</literal>, -то создаваемый подзапрос является независимым подзапросом. -Ответы на независимые подзапросы игнорируются. -В отличие от обычных подзапросов независимый подзапрос -можно создать внутри обработчика переменной. -Флаг <literal>detached</literal> и аргумент <literal>callback</literal> -являются взаимоисключающими. -</tag-desc> - -</list> -</para> - -<para> -<literal>callback</literal> получает -объект ответа подзапроса с методами и свойствами, -идентичными родительскому объекту запроса. -</para> - -<para> -Начиная с версии njs <link doc="changes.xml" id="njs0.3.8">0.3.8</link> -если не указан <literal>callback</literal>, -то возвращается объект <literal>Promise</literal>, -который разрешается в объект ответа подзапроса. -</para> -</tag-desc> - -<tag-name id="r_uri"><literal>r.uri</literal></tag-name> -<tag-desc> -текущий <link doc="../http/ngx_http_core_module.xml" id="var_uri">URI</link> -запроса в -<link doc="../http/ngx_http_core_module.xml" id="location">нормализованном</link> -виде, только чтение -</tag-desc> - -<tag-name id="r_variables"><literal>r.variables{}</literal></tag-name> -<tag-desc> -объект переменных nginx, доступно для записи -(начиная с версии <link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</tag-desc> - -<tag-name id="r_warn"><literal>r.warn(<value>строка</value>)</literal></tag-name> -<tag-desc> -записывает <literal>строку</literal> в лог-файл ошибок -на уровне лога <literal>warning</literal> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="stream" name="Stream-сессия"> - -<para> -Объект stream-сессии доступен только в -модуле -<link doc="../stream/ngx_stream_js_module.xml">ngx_stream_js_module</link>. -Все строки в объекте <literal>stream</literal> являются -<link id="string">байтовыми строками</link>. -</para> - -<para> -<list type="tag"> - -<tag-name id="s_allow"><literal>s.allow()</literal></tag-name> -<tag-desc> -успешно финализирует обработчик фазы -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_decline"><literal>s.decline()</literal></tag-name> -<tag-desc> -финализирует обработчик фазы и передаёт контроль следующему обработчику -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_deny"><literal>s.deny()</literal></tag-name> -<tag-desc> -финализирует обработчик фазы с кодом ошибки доступа -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_done"><literal>s.done</literal>(<value>[код]</value>)</tag-name> -<tag-desc> -успешно финализирует текущий обработчик фазы -или финализирует его с указанным числовым кодом -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>). -</tag-desc> - -<tag-name id="s_error"><literal>s.error(<value>строка</value>)</literal></tag-name> -<tag-desc> -записывает отправленную <literal>строку</literal> в лог-файл ошибок -на уровне лога <literal>error</literal> -</tag-desc> - -<tag-name id="s_log"><literal>s.log(<value>строка</value>)</literal></tag-name> -<tag-desc> -записывает отправленную <value>строку</value> в лог-файл ошибок -на уровне лога <literal>info</literal> -</tag-desc> - -<tag-name id="s_off"><literal>s.off(<value>имяСобытия</value>)</literal></tag-name> -<tag-desc> -отменяет регистрацию callback'а, установленного методом -<link id="s_on">s.on()</link> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>) -</tag-desc> - -<tag-name id="s_on"><literal>s.on(<value>событие</value>, -<value>callback</value>)</literal></tag-name> -<tag-desc> -регистрирует <literal>callback</literal> -для указанного <literal>события</literal> -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>). - -<para> -<literal>Событием</literal> может являться одна из следующих строк: -<list type="tag"> -<tag-name><literal>upload</literal></tag-name> -<tag-desc> -новые данные от клиента -</tag-desc> - -<tag-name><literal>download</literal></tag-name> -<tag-desc> -новые данные к клиенту -</tag-desc> - -</list> -</para> - -<para> -Callback завершения имеет следующий прототип: -<literal>callback(данные, флаги)</literal>, где -<literal>данные</literal> являются строкой, -<literal>флаги</literal> являются объектом -со следующими свойствами: -<list type="tag"> -<tag-name id="s_on_callback_last"><literal>last</literal></tag-name> -<tag-desc> -логическое свойство, -true, если данные являются последним буфером. -</tag-desc> - -</list> -</para> -</tag-desc> - -<tag-name id="s_remote_address"><literal>s.remoteAddress</literal></tag-name> -<tag-desc> -адрес клиента, только чтение -</tag-desc> - -<tag-name id="s_send"><literal>s.send(<value>данные</value>[, -<value>параметры</value>])</literal></tag-name> -<tag-desc> -отправляет данные клиенту -(<link doc="changes.xml" id="njs0.2.4">0.2.4</link>). -<literal>Параметры</literal> являются объектом, используемым -для переопределения флагов буфера nginx, -полученных из буфера входных данных. -Флаги могут быть переопределены при помощи следующих флагов: -<para> -<list type="tag"> - -<tag-name><literal>last</literal></tag-name> -<tag-desc> -логическое свойство, -true, если буфер является последним буфером -</tag-desc> - -<tag-name><literal>flush</literal></tag-name> -<tag-desc> -логическое свойство, -true, если буфер должен иметь флаг <literal>flush</literal> -</tag-desc> -</list> -</para> -Метод может быть вызван несколько раз в течение одного вызова callback'a. -</tag-desc> - -<tag-name id="s_variables"><literal>s.variables{}</literal></tag-name> -<tag-desc> -объект переменных nginx, доступно для записи -(начиная с версии <link doc="changes.xml" id="njs0.2.8">0.2.8</link>) -</tag-desc> - -<tag-name id="s_warn"><literal>s.warn(<value>строка</value>)</literal></tag-name> -<tag-desc> -записывает отправленную <literal>строку</literal> в лог-файл ошибок -на уровне лога <literal>warning</literal> -</tag-desc> - -</list> -</para> - -</section> - -</section> - - -<section id="core" name="Core"> - - -<section id="core_global" name="Global"> - - -<section id="process" name="Process"> - -<para> -Объект <literal>process</literal> является глобальным объектом, -предоставляющим информацию о текущем процессе -(<link doc="changes.xml" id="njs0.3.3">0.3.3</link>). -</para> - -<para> -<list type="tag"> - -<tag-name id="process_argv"><literal>process.argv</literal></tag-name> -<tag-desc> -Возвращает массив, содержащий аргументы командной строки, -передаваемые в момент запуска текущего процесса. -</tag-desc> - -<tag-name id="process_env"><literal>process.env</literal></tag-name> -<tag-desc> -Возвращает объект, содержащий переменные окружения пользователя. -<note> -По умолчанию nginx удаляет все переменные окружения, унаследованные -от своего родительского процесса, кроме переменной TZ. -Для сохранения части унаследованных переменных -необходимо использовать директиву <link doc="../ngx_core_module.xml" id="env"/>. -</note> -</tag-desc> - -<tag-name id="process_pid"><literal>process.pid</literal></tag-name> -<tag-desc> -Возвращает PID текущего процесса. -</tag-desc> - -<tag-name id="process_ppid"><literal>process.ppid</literal></tag-name> -<tag-desc> -Возвращает PID текущего родительского процесса. -</tag-desc> - -</list> -</para> - -</section> - -</section> - - -<section id="string" name="String"> - -<para> -В njs существует два типа строк: строка Unicode (по умолчанию) и -байтовая строка. -</para> - -<para> -Строка Unicode соответствует строке ECMAScript, -содержащей символы Unicode. -</para> - -<para> -Байтовые строки содержат последовательность байт и -используются для сериализации строк Unicode -во внешние данные и десериализации из внешних источников. -Например метод <link id="string_toutf8">toUTF8()</link> сериализует -строку Unicode в байтовую строку используя кодировку UTF8: -<example> ->> '£'.toUTF8().toString('hex') -'c2a3' /* C2 A3 является UTF8-представлением codepoint 00A3 ('£') */ -</example> -Метод <link id="string_tobytes">toBytes()</link> сериализует -строку Unicode с codepoints до 255 в байтовую строку, -в противном случае возвращается <literal>null</literal>: -<example> ->> '£'.toBytes().toString('hex') -'a3' /* a3 является байтом, равным codepoint 00A3 ('£') */ -</example> - -<list type="tag"> - -<tag-name id="string_bytesfrom"><literal>String.bytesFrom(<value>массив</value> -| <value>строка</value>, <value>кодировка</value>)</literal></tag-name> -<tag-desc> -Создаёт байтовую строку или из массива, содержащего октеты, -или из кодированной строки -(<link doc="changes.xml" id="njs0.2.3">0.2.3</link>). -Кодировкой может быть -<literal>hex</literal>, -<literal>base64</literal> и -<literal>base64url</literal>. -Метод устарел начиная с -<link doc="changes.xml" id="njs0.4.4">0.4.4</link>, -вместо него следует использовать метод <literal>Buffer.from</literal>: -<example> ->> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString() -'buffer' - ->> Buffer.from('YnVmZmVy', 'base64').toString() -'buffer' -</example> -</tag-desc> - -<tag-name id="string_frombytes"><literal>String.prototype.fromBytes(<value>начало</value>[, -<value>конец</value>])</literal></tag-name> -<tag-desc> -Возвращает новую строку Unicode из байтовой строки, -в которой каждый байт заменяется соответствующей Unicode codepoint. -</tag-desc> - -<tag-name id="string_fromutf8"><literal>String.prototype.fromUTF8(<value>начало</value>[, -<value>конец</value>])</literal></tag-name> -<tag-desc> -Преобразует байтовую строку, содержащую валидную строку UTF8, -в строку Unicode, -иначе возвращается <literal>null</literal>. -</tag-desc> - -<tag-name id="string_tobytes"><literal>String.prototype.toBytes(<value>начало</value>[, -<value>конец</value>])</literal></tag-name> -<tag-desc> -Сериализует строку Unicode в байтовую строку. -Возвращает <literal>null</literal>, если в строке найден символ больше, чем 255. -</tag-desc> - -<tag-name id="string_tostring"><literal>String.prototype.toString(<value>кодировка</value>)</literal></tag-name> -<tag-desc> -<para> -Кодирует указанную строку в -<literal>hex</literal>, -<literal>base64</literal> или -<literal>base64url</literal>: -<example> ->> 'αβγδ'.toString('base64url') -'zrHOss6zzrQ' -</example> -До версии <link doc="changes.xml" id="njs0.4.3">0.4.3</link> -могла быть кодирована только <link id="string_tobytes">байтовая строка</link>: -<example> ->> 'αβγδ'.toUTF8().toString('base64url') -'zrHOss6zzrQ' -</example> -</para> -</tag-desc> - -<tag-name id="string_toutf8"><literal>String.prototype.toUTF8(<value>начало</value>[, -<value>конец</value>])</literal></tag-name> -<tag-desc> -Сериализует строку Unicode -в байтовую строку при помощи кодирования UTF8. -<example> ->> 'αβγδ'.toUTF8().length -8 ->> 'αβγδ'.length -4 -</example> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="textdecoder" name="Text Decoder"> - -<para> -Объект <literal>TextDecoder</literal> -создаёт поток кодовых точек из потока данных -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>). -</para> - -<para> -<list type="tag"> - -<tag-name><literal>TextDecoder([[<value>кодировка</value>], -<value>options</value>])</literal></tag-name> -<tag-desc> -Создаёт новый объект <literal>TextDecoder</literal> -для указанной <literal>кодировки</literal>, -на данный момент поддерживается только UTF-8. -Параметр <literal>options</literal> является -словарём <literal>TextDecoderOption</literal> со свойствами: - -<list type="tag"> - -<tag-name><literal>fatal</literal></tag-name> -<tag-desc> -логический флаг, указывающий, что -<link id="textdecoder_decode"><literal>TextDecoder.decode()</literal></link> -должен вызывать исключение <value>TypeError</value> в случае, если -найдена ошибка кодирования, по умолчанию <literal>false</literal>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="textdecoder_encoding"><literal>TextDecoder.prototype.encoding</literal></tag-name> -<tag-desc> -Возвращает строку с именем кодировки, используемой -<link id="textdecoder"><literal>TextDecoder()</literal></link>, -только чтение. -</tag-desc> - -<tag-name id="textdecoder_fatal"><literal>TextDecoder.prototype.fatal</literal></tag-name> -<tag-desc> -логический флаг, <literal>true</literal>, если -генерируется ошибка для невалидных символов, -только чтение. -</tag-desc> - -<tag-name id="textdecoder_ignorebom"><literal>TextDecoder.prototype.ignoreBOM</literal></tag-name> -<tag-desc> -логический флаг, <literal>true</literal>, если -игнорируется маркер порядка следования байтов, -только чтение. -</tag-desc> - -<tag-name id="textdecoder_decode"><literal>TextDecoder.prototype.decode(<value>буфер</value>, -[<value>options</value>])</literal></tag-name> -<tag-desc> -Возвращает строку с текстом, -декодированным из <literal>буфера</literal> при помощи -<link id="textdecoder"><literal>TextDecoder()</literal></link>. -Буфером может быть -<literal>ArrayBuffer</literal>. -Параметром <literal>options</literal> является -словарь <literal>TextDecodeOptions</literal> со свойствами: - -<list type="tag"> - -<tag-name><literal>stream</literal></tag-name> -<tag-desc> -логический флаг, указывающий, что -при последующих вызовах <literal>decode()</literal> -должны последовать дополнительные данные: -<literal>true</literal>, если данные обрабатываются блоками, и -<literal>false</literal> для последнего блока -или если данные не передаются блоками. -По умолчанию <literal>false</literal>. -</tag-desc> - -</list> -<example> ->> (new TextDecoder()).decode(new Uint8Array([206,177,206,178])) -αβ -</example> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="textencoder" name="Text Encoder"> - -<para> -Объект <literal>TextEncoder</literal> -создаёт поток данных в кодировке UTF-8 -из потока кодовых точек -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>). -</para> - -<para> -<list type="tag"> - -<tag-name><literal>TextEncoder()</literal></tag-name> -<tag-desc> -Возвращает только что созданный <literal>TextEncoder</literal>, -который создаёт поток данных в кодировке UTF-8. -</tag-desc> - -<tag-name id="textencoder_encode"><literal>TextEncoder.prototype.encode(<value>строка</value>)</literal></tag-name> -<tag-desc> -Кодирует <literal>строку</literal> в <literal>Uint8Array</literal>, -содержащий текст в кодировке UTF-8. -</tag-desc> - -<tag-name id="textencoder_encodeinto"><literal>TextEncoder.prototype.encodeInto(<value>строка</value>, -<value>uint8Array</value>)</literal></tag-name> -<tag-desc> -Преобразует <literal>строку</literal> в UTF-8, -сохраняет результат в целевом <literal>Uint8Array</literal> и -возвращает объект словаря, отражающий прогресс кодирования, со свойствами: - -<list type="tag"> - -<tag-name><literal>read</literal></tag-name> -<tag-desc> -количество блоков кода UTF-16 из исходной строки, -преобразованных в UTF-8 -</tag-desc> - -<tag-name><literal>written</literal></tag-name> -<tag-desc> -количество байтов, преобразованных в целевом <literal>Uint8Array</literal> -</tag-desc> - -</list> -</tag-desc> - -</list> -</para> - -</section> - - -<section id="njs_api_timers" name="Timers"> - -<para> -<list type="tag"> - -<tag-name id="cleartimeout"><literal>clearTimeout(<value>timeout</value>)</literal></tag-name> -<tag-desc> -Отменяет объект <literal>timeout</literal>, -созданный <link id="settimeout"><literal>setTimeout()</literal></link>. -</tag-desc> - -<tag-name id="settimeout"><literal>setTimeout(<value>функция</value>, -<value>миллисекунды</value>[, -<value>аргумент1</value>, -<value>аргументN</value>])</literal></tag-name> -<tag-desc> -Вызывает <literal>функцию</literal> -по прошествии указанного количества <literal>миллисекунд</literal>. -Указанной функции можно передать -один или более необязательных <literal>аргументов</literal>. -Возвращает объект <literal>timeout</literal>. -<example> -function handler(v) -{ - // ... -} - -t = setTimeout(handler, 12); - -// ... - -clearTimeout(t); -</example> -</tag-desc> - -</list> -</para> - -</section> - -</section> - - -<section id="built-in" name="Встроенные модули"> - -<section id="crypto" name="Crypto"> - -<para> -Модуль Crypto предоставляет поддержку криптографических функций. -Объект модуля Crypto доступен через <literal>require('crypto')</literal>. -</para> - -<para> -<list type="tag"> - -<tag-name id="crypto_createhash"><literal>crypto.createHash(<value>алгоритм</value>)</literal></tag-name> -<tag-desc> -Создаёт и возвращает объект <link id="crypto_hash">Hash</link>, -который может использоваться для создания hash digests -при помощи указанного <value>алгоритма</value>. -Алгоритмом может быть -<literal>md5</literal>, -<literal>sha1</literal> и -<literal>sha256</literal>. -</tag-desc> - -<tag-name id="crypto_createhmac"><literal>crypto.createHmac(<value>алгоритм</value>, -<value>секретный ключ</value>)</literal></tag-name> -<tag-desc> -Создаёт и возвращает объект <link id="crypto_hmac">HMAC</link>, который -использует заданный <value>алгоритм</value> и <value>секретный ключ</value>. -Алгоритм может быть -<literal>md5</literal>, -<literal>sha1</literal> и -<literal>sha256</literal>. -</tag-desc> - -</list> -</para> - - -<section id="crypto_hash" name="Hash"> - -<para> -<list type="tag"> - -<tag-name id="crypto_hash_update"><literal>hash.update(<value>данные</value>)</literal></tag-name> -<tag-desc> -Обновляет содержимое хэша с передаваемыми <value>данными</value>. -</tag-desc> - -<tag-name id="crypto_hash_digest"><literal>hash.digest([<value>кодировка</value>])</literal></tag-name> -<tag-desc> -Подсчитывает дайджест всех данных, передаваемых при помощи -<literal>hash.update()</literal>. -Кодировка может быть -<literal>hex</literal>, -<literal>base64</literal> и -<literal>base64url</literal>. -Если кодировка не указана, то будет возвращен объект буфера -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -<note> -До версии <link doc="changes.xml" id="njs0.4.4">0.4.4</link> -вместо объекта буфера возвращалась байтовая строка. -</note> -</tag-desc> - -</list> -</para> - -<para> -<example> ->> var cr = require('crypto') -undefined - ->> cr.createHash('sha1').update('A').update('B').digest('base64url') -'BtlFlCqiamG-GMPiK_GbvKjdK10' -</example> -</para> - -</section> - - -<section id="crypto_hmac" name="HMAC"> - -<para> -<list type="tag"> - -<tag-name id="crypto_hmac_update"><literal>hmac.update(<value>данные</value>)</literal></tag-name> -<tag-desc> -Обновляет содержимое HMAC с передаваемыми <value>данными</value>. -</tag-desc> - -<tag-name id="crypto_hmac_digest"><literal>hmac.digest([<value>кодировка</value>])</literal></tag-name> -<tag-desc> -Подсчитывает HMAC-дайджест всех данных, передаваемых при помощи -<literal>hmac.update()</literal>. -Кодировка может быть -<literal>hex</literal>, -<literal>base64</literal> и -<literal>base64url</literal>. -Если кодировка не указана, то будет возвращена байтовая строка. -</tag-desc> -</list> -</para> - -<para> -<example> ->> var cr = require('crypto') -undefined - ->> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url') -'Oglm93xn23_MkiaEq_e9u8zk374' -</example> -</para> - -</section> - -</section> - - -<section id="njs_api_fs" name="File System"> - -<para> -Модуль File System предоставляет набор функций для операций с файлами. -</para> - -<para> -Объект модуля доступен через <literal>require('fs')</literal>. -Начиная с версии <link doc="changes.xml" id="njs0.3.9">0.3.9</link> -доступны промисифицированные версии методов file system через -объект <literal>require('fs').promises</literal>: -<example> -> var fs = require('fs').promises; -undefined -> fs.readFile("/file/path").then((data)=>console.log(data)) -<file data> -</example> -<list type="tag"> - -<tag-name id="fs_accesssync"><literal>accessSync(<value>путь</value>[, -<value>mode</value>])</literal></tag-name> -<tag-desc> -Синхронно проверяет разрешения для файла или каталога, -указанного в <literal>пути</literal> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -Если проверка не удалась, то будет возвращена ошибка, -в противном случае метод возвратит undefined. -<list type="tag"> - -<tag-name><literal>mode</literal></tag-name> -<tag-desc> -По умолчанию -<link id="access_const"><literal>fs.constants.F_OK</literal></link>. -Является необязательным числом, -которое задаёт выполнение проверок доступа. -<example> -try { - fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK); - console.log('has access'); -} catch (e) { - console.log('no access');) -} -</example> -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_appendfilesync"><literal>appendFileSync(<value>имяФайла</value>, -<value>данные</value>[, <value>options</value>])</literal></tag-name> -<tag-desc> -Синхронно добавляет указанные <literal>данные</literal> -в файл с указанным <literal>именем</literal>. -<literal>Данными</literal> могут быть строка -или объект буфера (<link doc="changes.xml" id="njs0.4.4">0.4.4</link>. -Если файл не существует, то он будет создан. -Параметр <literal>options</literal> должен быть -объектом со следующими ключами: -<list type="tag"> - -<tag-name><literal>режим</literal></tag-name> -<tag-desc> -режим, по умолчанию <literal>0o666</literal> -</tag-desc> - -<tag-name><literal>флаг</literal></tag-name> -<tag-desc> -<link id="njs_api_fs_flags">флаг</link> файловой системы, -по умолчанию <literal>a</literal> -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_mkdirsync"><literal>mkdirSync(<value>путь</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Синхронно создаёт каталог по указанному <literal>пути</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>). -Параметр <literal>options</literal> должен быть -<literal>числом</literal>, которое задаёт -<link id="fs_mkdirsync_mode">режим</link>, -или объектом с ключами: -<list type="tag"> - -<tag-name id="fs_mkdirsync_mode"><literal>режим</literal></tag-name> -<tag-desc> -режим, по умолчанию <literal>0o777</literal>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_readdirsync"><literal>readdirSync(<value>путь</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Синхронно читает содержимое каталога -по указанному <literal>пути</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>). -Параметр <literal>options</literal> должен быть -строкой, определяющей <link id="fs_readdirsync_encoding">кодировку</link> -или объектом с ключами: -<list type="tag"> - -<tag-name id="fs_readdirsync_encoding"><literal>кодировка</literal></tag-name> -<tag-desc> -кодировка, по умолчанию <literal>utf8</literal>. -Кодировка может быть <literal>utf8</literal> и <literal>буфер</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -</tag-desc> - -<tag-name id="fs_readdirsync_withfiletypes"><literal>withFileTypes</literal></tag-name> -<tag-desc> -если <literal>true</literal>, то массив файлов будет содержать -объекты <link id="fs_dirent"><literal>fs.Dirent</literal></link>, -по умолчанию <literal>false</literal>. -</tag-desc> - -</list> -</tag-desc> - -<tag-name id="fs_readfilesync"><literal>readFileSync(<value>имяФайла</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Синхронно возвращает содержимое файла -с указанным <literal>именем</literal>. -Параметр <literal>options</literal> хранит -<literal>строку</literal>, которая задаёт кодировку. -Если кодировка указана, то будет возвращена строка, -иначе будет возвращён объект буфера -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -<note> -До версии <link doc="changes.xml" id="njs0.4.4">0.4.4</link> -возвращалась <link id="string_tobytes">байтовая строка</link> -в случае, если не была указана кодировка. -</note> -Иначе ожидается, что <literal>options</literal> является -объектом с ключами: -<list type="tag"> - -<tag-name><literal>кодировка</literal></tag-name> -<tag-desc> -кодировка, по умолчанию не указана. -Кодировка может быть <literal>utf8</literal>, -<literal>hex</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>base64</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>), -<literal>base64url</literal> -(<link doc="changes.xml" id="njs0.4.4">0.4.4</link>). -</tag-desc> - -<tag-name><literal>флаг</literal></tag-name> -<tag-desc> -<link id="njs_api_fs_flags">флаг</link> файловой системы, -по умолчанию <literal>r</literal> -</tag-desc> - -</list> -<example> ->> 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 -</example> -</tag-desc> - -<tag-name id="fs_realpathsync"><literal>realpathSync(<value>путь</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Синхронно вычисляет канонический путь при помощи преобразования -<literal>.</literal>, <literal>..</literal> и символических ссылок используя -<link url="http://man7.org/linux/man-pages/man3/realpath.3.html">realpath(3)</link>. -Аргумент <literal>options</literal> может быть строкой, определяющей кодировку, -или объектом со свойством encoding, определяющим символьную кодировку, -которая используется для передачи пути обратному вызову -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -</tag-desc> - -<tag-name id="fs_renamesync"><literal>renameSync(<value>старыйПуть</value>, -<value>новыйПуть</value>)</literal></tag-name> -<tag-desc> -Синхронно меняет имя или местоположение файла. -(<link doc="changes.xml" id="njs0.3.4">0.3.4</link>). -<example> ->> var fs = require('fs') -undefined ->> var file = fs.renameSync('hello.txt', 'HelloWorld.txt') -undefined -</example> -</tag-desc> - -<tag-name id="fs_rmdirsync"><literal>rmdirSync(<value>путь</value>)</literal></tag-name> -<tag-desc> -Синхронно удаляет каталог по указанному <literal>пути</literal> -(<link doc="changes.xml" id="njs0.4.2">0.4.2</link>). -</tag-desc> - -<tag-name id="fs_symlinksync"><literal>symlinkSync(<value>цель</value>, -<value>path</value>)</literal></tag-name> -<tag-desc> -Синхронно создаёт ссылку с именем <literal>путь</literal>, -указывающую на <literal>цель</literal> при помощи -<link url="http://man7.org/linux/man-pages/man2/symlink.2.html">symlink(2)</link> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -Относительные цели считаются относительно корневого каталога ссылки. -</tag-desc> - -<tag-name id="fs_unlinksync"><literal>unlinkSync(<value>путь</value>)</literal></tag-name> -<tag-desc> -Синхронно удаляет файл по указанному <literal>пути</literal> -(<link doc="changes.xml" id="njs0.3.9">0.3.9</link>). -</tag-desc> - -<tag-name id="fs_writefilesync"><literal>writeFileSync(<value>имяФайла</value>, -<value>данные</value>[, -<value>options</value>])</literal></tag-name> -<tag-desc> -Синхронно записывает <literal>данные</literal> в файл -с указанным <literal>именем</literal>. -<literal>Данными</literal> могут быть строка -или объект буфера (<link doc="changes.xml" id="njs0.4.4">0.4.4</link>. -Если файл не существует, то он будет создан. -Если файл существует, то он будет заменён. -Параметр <literal>options</literal> должен быть -объектом с ключами: -<list type="tag"> -<tag-name><literal>режим</literal></tag-name> -<tag-desc> -режим, по умолчанию <literal>0o666</literal> -</tag-desc> - -<tag-name><literal>флаг</literal></tag-name> -<tag-desc> -<link id="njs_api_fs_flags">флаг</link> файловой системы, -по умолчанию <literal>w</literal> -</tag-desc> - -</list> -<example> ->> var fs = require('fs') -undefined ->> var file = fs.writeFileSync('hello.txt', 'Hello world') -undefined -</example> -</tag-desc> - -</list> -</para> - - -<section id="fs_dirent" name="fs.Dirent"> - -<para> -<literal>fs.Dirent</literal> является представлением записи каталога— -файлом или подкаталогом . -В случае, если -<link id="fs_readdirsync"><literal>readdirSync()</literal></link> -вызывается с опцией -<link id="fs_readdirsync_withfiletypes"><literal>withFileTypes</literal></link> -получившийся массив содержит объекты <literal>fs.Dirent</literal>. - -<list type= "bullet" compact="no"> - -<listitem> -<literal>dirent.isBlockDevice()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -блочное устройство -</listitem> - -<listitem> -<literal>dirent.isCharacterDevice()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -символьное устройство. -</listitem> - -<listitem> -<literal>dirent.isDirectory()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -каталог файловой системы. -</listitem> - -<listitem> -<literal>dirent.isFIFO()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -FIFO-канал. -</listitem> - -<listitem> -<literal>dirent.isFile()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -обычный файл. -</listitem> - -<listitem> -<literal>dirent.isSocket()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -сокет. -</listitem> - -<listitem> -<literal>dirent.isSymbolicLink()</literal>—возвращает -<literal>true</literal>, если объект <literal>fs.Dirent</literal> описывает -символическую ссылку. -</listitem> - -<listitem> -<literal>dirent.name</literal>— -имя файла, на которое ссылается объект <literal>fs.Dirent</literal>. -</listitem> - -</list> -</para> - -</section> - - -<section id="access_const" name="Константы доступа к файлу"> - -<para> -Метод <link id="fs_accesssync"><literal>access()</literal></link> -может принимать следующие флаги. -Флаги экспортируются при помощи <literal>fs.constants</literal>: - -<list type= "bullet" compact="no"> - -<listitem> -<literal>F_OK</literal>—указывает, что файл может -быть видимым для для вызывающего процесса, -используется по умолчанию, если режим не указан -</listitem> - -<listitem> -<literal>R_OK</literal>—указывает, что файл может -читаться вызывающим процессом -</listitem> - -<listitem> -<literal>W_OK</literal>—указывает, что файл может -записываться вызывающим процессом -</listitem> - -<listitem> -<literal>X_OK</literal>—указывает, что файл может -выполняться вызывающим процессом -</listitem> - -</list> -</para> - -</section> - - -<section id="njs_api_fs_flags" name="Флаги файловой системы"> - -<para> -Опция <literal>флаг</literal> может принимать следующие значения: - -<list type= "bullet" compact="no"> - -<listitem> -<literal>a</literal>—открытие файла для добавления данных. -Если файл не существует, то он будет создан -</listitem> - -<listitem> -<literal>ax</literal>—то же, что и <literal>a</literal>, -но завершится неудачей, если файл существует -</listitem> - -<listitem> -<literal>a+</literal>—открытие файла для чтения и добавления данных. -Если файл не существует, то он будет создан -</listitem> - -<listitem> -<literal>ax+</literal>—то же, что и <literal>a+</literal>, -но завершится неудачей, если файл существует -</listitem> - -<listitem> -<literal>as</literal>—открытие файла для добавления данных -в синхронном режиме. -Если файл не существует, то он будет создан -</listitem> - -<listitem> -<literal>as+</literal>—открытие файла для чтения и добавления данных -в синхронном режиме. -Если файл не существует, то он будет создан -</listitem> - -<listitem> -<literal>r</literal>— открытие файла для чтения. -Если файл не существует, то возникнет исключение -</listitem> - -<listitem> -<literal>r+</literal>—открытие файла для чтения и записи. -Если файл не существует, то возникнет исключение -</listitem> - -<listitem> -<literal>rs+</literal>—открытие файла для чтения и записи -в синхронном режиме. -Указывает операционной системе не использовать кэш локальной файловой системы -</listitem> - -<listitem> -<literal>w</literal>—открытие файла для записи. -Если файл не существует, то он будет создан. -Если файл существует, то он будет заменён. -</listitem> - -<listitem> -<literal>wx</literal>—то же, что и <literal>w</literal>, -но завершится неудачей, если файл существует -</listitem> - -<listitem> -<literal>w+</literal>—открытие файла для чтения и записи. -Если файл не существует, то он будет создан. -Если файл существует, то он будет заменён. -</listitem> - -<listitem> -<literal>wx+</literal>—то же, что и <literal>w+</literal>, -но завершится неудачей, если файл существует -</listitem> - -</list> -</para> - -</section> - -</section> - - -<section id="querystring" name="Query String"> - -<para> -Модуль Query String предоставляет поддержку -синтаксического разбора и форматирования строки запроса URL. -(<link doc="changes.xml" id="njs0.4.3">0.4.3</link>). -Объект модуля Query String доступен через -<literal>require('querystring')</literal>. -</para> - -<para> -<list type="tag"> - -<tag-name id="querystring_decode"><literal>querystring.decode()</literal></tag-name> -<tag-desc> -является псевдонимом для -<link id="querystring_parse"><literal>querystring.parse()</literal></link>. -</tag-desc> - -<tag-name id="querystring_encode"><literal>querystring.encode()</literal></tag-name> -<tag-desc> -является псевдонимом для -<link id="querystring_stringify"><literal>querystring.stringify()</literal></link>. -</tag-desc> - -<tag-name id="querystring_escape"><literal>querystring.escape(<value>строка</value>)</literal></tag-name> -<tag-desc> -<para> -Кодирует заданную <literal>строку</literal>, -возвращает экранированную строку. -Метод используется методом -<link id="querystring_stringify"><literal>querystring.stringify()</literal></link> -и не должен использоваться напрямую. -</para> -</tag-desc> - -<tag-name id="querystring_parse"><literal>querystring.parse(<value>строка</value>[, -<value>separator</value>[, -<value>equal</value>[, -<value>options</value>]]])</literal></tag-name> -<tag-desc> -<para> -Осуществляет синтаксический разбор строки запроса и возвращает объект. -</para> - -<para> -Параметр <literal>separator</literal> является подстрокой, -разделяющей в строке запроса пары ключей и значений, -по умолчанию “<literal>&</literal>”. -</para> - -<para> -Параметр <literal>equal</literal> является подстрокой, -разделяющей в строке запроса ключи и значения, -по умолчанию “<literal>=</literal>”. -</para> - -<para> -Параметр <literal>options</literal> должен быть -объектом со следующими ключами: -<list type="tag"> -<tag-name><literal>decodeURIComponent</literal> -<value>функция</value></tag-name> -<tag-desc> -Функция, используемая -при декодировании процентно-кодированных символов в строке запроса, -по умолчанию -<link id="querystring_unescape"><literal>querystring.unescape()</literal></link> -</tag-desc> - -<tag-name><literal>maxKeys</literal> -<value>число</value></tag-name> -<tag-desc> -максимальное число ключей для синтаксического разбора, -по умолчанию <literal>1000</literal>. -Значение <literal>0</literal> удаляет ограничение на подсчёт ключей. -</tag-desc> - -</list> -По умолчанию предполагается, что процентно-кодированные символы в строке запроса -используют кодировку UTF-8, -неверная последовательность байтов UTF-8 будет заменена на -<literal>U+FFFD</literal>. -</para> - -<para> -Пример для строки запроса: -<example> -'foo=bar&abc=xyz&abc=123' -</example> -результат: -<example> -{ - foo: 'bar', - abc: ['xyz', '123'] -} -</example> -</para> - -</tag-desc> - -<tag-name id="querystring_stringify"><literal>querystring.stringify(<value>object</value>[, -<value>separator</value>[, -<value>equal</value>[, -<value>options</value>]]])</literal></tag-name> -<tag-desc> -<para> -Осуществляет синтаксический разбор объекта и возвращает строку запроса. -</para> - -<para> -Параметр <literal>separator</literal> является подстрокой, -разделяющей в строке запроса пары ключей и значений, -по умолчанию “<literal>&</literal>”. -</para> - -<para> -Параметр <literal>equal</literal> является подстрокой, -разделяющей в строке запроса ключи и значения, -по умолчанию “<literal>=</literal>”. -</para> - -<para> -Параметр <literal>options</literal> должен быть -объектом со следующими ключами: -<list type="tag"> -<tag-name><literal>encodeURIComponent</literal> -<value>функция</value></tag-name> -<tag-desc> -Функция, используемая при декодировании -URL-небезопасных символов в в процентно-кодированные символы в строке запроса, -по умолчанию -<link id="querystring_escape"><literal>querystring.escape()</literal></link>. -</tag-desc> - -</list> -</para> - -<para> -По умолчанию символы, требующие процентной кодировки внутри строки запроса, -кодируются в UTF-8. -Если требуется другая кодировка, то -необходимо указать опцию <literal>encodeURIComponent</literal>. -</para> - -<para> -Пример: -<example> -querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], 123: '' }); -</example> -результат: -<example> -'foo=bar&baz=qux&baz=quux&123=' -</example> -</para> - -</tag-desc> - -<tag-name id="querystring_unescape"><literal>querystring.unescape(<value>строка</value>)</literal></tag-name> -<tag-desc> -<para> -Осуществляет декодирование процентно-кодированных символов URL -в <literal>строке</literal>, -возвращает неэкранированную строку запроса. -Метод используется методом -<link id="querystring_parse"><literal>querystring.parse()</literal></link> -и не должен использоваться напрямую. -</para> -</tag-desc> - -</list> -</para> - -</section> - -</section> - -</article> -
--- a/xml/ru/docs/njs/typescript.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,114 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd"> - -<article name="Создание кода njs при помощи файлов деклараций TypeScript" - link="/en/docs/njs/typescript.html" - lang="en" - rev="1"> - -<section> - -<para> -<link url="https://www.typescriptlang.org">TypeScript</link>—это -типизированное подмножество JavaScript, -которое компилируется в обычный JavaScript. -</para> - -<para> -TypeScript поддерживает файлы деклараций, в которых содержится -типизированная информация существующих библиотек JavaScript. -С их помощью программы могут использовать значения в файлах также, -если бы эти значения были статически типизированными сущностями TypeScript. -</para> - -<para> -В njs файлы деклараций TypeScript предоставляются для -<link doc="reference.xml">API</link> и могут использоваться при: -<list type="bullet"> - -<listitem> -автозаполнении и проверки API в редакторе -</listitem> - -<listitem> -создании типобезопасного njs-кода. -</listitem> - -</list> -</para> - -</section> - - -<section id="get" name="Компиляция файлов деклараций TypeScript"> - -<para> -<example> -$ 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 -</example> -</para> - -</section> - - -<section id="autocomplete" name="Проверка API и автозаполнение"> - -<para> -Файлы деклараций <literal>*.d.ts</literal> необходимо поместить в место, -доступное редактору: -</para> - -<para> -<literal>test.js</literal>: -<example> -/// <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"); -} -</example> -</para> - -</section> - - -<section id="write" name="Создание типобезопасного njs кода"> - -<para> -<literal>test.ts</literal>: -<example> -/// <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"); -} -</example> -Установка TypeScript: -<example> -# npm install -g typescript -</example> -Компиляция TypeScript: -<example> -$ tsc test.ts -$ cat test.js -</example> -Созданный файл <literal>test.js</literal> может использоваться напрямую в njs. -</para> - -</section> - -</article>
--- a/xml/ru/docs/stream/ngx_stream_js_module.xml Wed Feb 14 20:05:57 2024 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,793 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Copyright (C) Nginx, Inc. - --> - -<!DOCTYPE module SYSTEM "../../../../dtd/module.dtd"> - -<module name="Модуль ngx_stream_js_module" - link="/ru/docs/stream/ngx_stream_js_module.html" - lang="ru" - rev="44"> - -<section id="summary"> - -<para> -Модуль <literal>ngx_stream_js_module</literal> позволяет задавать -обработчики на <link doc="../njs/index.xml">njs</link> — -подмножестве языка JavaScript. -</para> - -<para> -Инструкция по сборке и установке доступны -<link doc="../njs/install.xml">здесь</link>. -</para> - -</section> - - -<section id="example" name="Пример конфигурации"> - -<para> -Пример работает начиная с версии -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link>. -<example> -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; - } - } -} -</example> -</para> - -<para> -Файл <path>stream.js</path>: -<example> -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}; -</example> -</para> - -</section> - - -<section id="directives" name="Директивы"> - -<directive name="js_access"> -<syntax><value>функция</value> | <value>модуль.функция</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Задаёт функцию njs, которая будет вызываться в -<link doc="stream_processing.xml" id="access_phase">access</link>-фазе. -Начиная с <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -можно ссылаться на функцию модуля. -</para> - -<para> -Функция вызывается однократно при первом достижении сессией -<link doc="stream_processing.xml" id="access_phase">access</link>-фазы. -Функция вызывается со следующими аргументами: - -<list type="tag"> -<tag-name><literal>s</literal></tag-name> -<tag-desc> -объект <link doc="../njs/reference.xml" id="stream">stream-сессии</link> -</tag-desc> - -</list> -</para> - -<para> -В этой фазе может происходить инициализация, -также при помощи метода -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -может регистрироваться вызов -для каждого входящего блока данных пока не будет вызван один из методов: -<link doc="../njs/reference.xml" id="s_done"><literal>s.done()</literal></link> -<link doc="../njs/reference.xml" id="s_decline"><literal>s.decline()</literal></link>, -<link doc="../njs/reference.xml" id="s_allow"><literal>s.allow()</literal></link>. -При вызове любого из этих методов обработка сессии -переходит на <link doc="stream_processing.xml">следующую фазу</link> -и все текущие вызовы -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -сбрасываются. -</para> - -</directive> - - -<directive name="js_fetch_buffer_size"> -<syntax><value>размер</value></syntax> -<default>16k</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Задаёт <value>размер</value> буфера, который будет использоваться -для чтения и записи для -<link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_ciphers"> -<syntax><value>шифры</value></syntax> -<default>HIGH:!aNULL:!MD5</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Описывает разрешённые шифры для HTTPS-соединений -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -Шифры задаются в формате, поддерживаемом библиотекой OpenSSL. -</para> - -<para> -Полный список можно посмотреть с помощью команды -“<command>openssl ciphers</command>”. -</para> - -</directive> - - -<directive name="js_fetch_max_response_buffer_size"> -<syntax><value>размер</value></syntax> -<default>1m</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Задаёт максимальный <value>размер</value> ответа, полученного -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_protocols"> -<syntax> - [<literal>TLSv1</literal>] - [<literal>TLSv1.1</literal>] - [<literal>TLSv1.2</literal>] - [<literal>TLSv1.3</literal>]</syntax> -<default>TLSv1 TLSv1.1 TLSv1.2</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Разрешает указанные протоколы для HTTPS-соединений -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_timeout"> -<syntax><value>время</value></syntax> -<default>60s</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Задаёт таймаут при чтении и записи -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -Таймаут устанавливается не на всю передачу ответа, -а только между двумя операциями чтения. -Если по истечении этого времени данные не передавались, соединение закрывается. -</para> - -</directive> - - -<directive name="js_fetch_trusted_certificate"> -<syntax><value>файл</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Задаёт <value>файл</value> с доверенными сертификатами CA в формате PEM, -используемыми при -<link doc="../njs/reference.xml" id="fetch_verify">проверке</link> -HTTPS-сертификата -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify"> -<syntax><literal>on</literal> | <literal>off</literal></syntax> -<default>on</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.4</appeared-in> - -<para> -Разрешает или запрещает проверку сертификата HTTPS-сервера -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_fetch_verify_depth"> -<syntax><value>число</value></syntax> -<default>100</default> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.0</appeared-in> - -<para> -Устанавливает глубину проверки в цепочке HTTPS-сертификатов -при помощи <link doc="../njs/reference.xml" id="ngx_fetch">Fetch API</link>. -</para> - -</directive> - - -<directive name="js_filter"> -<syntax><value>функция</value> | <value>модуль.функция</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Задаёт фильтр данных. -Начиная с <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -можно ссылаться на функцию модуля. -Функция фильтра вызывается однократно при первом достижении сессией -<link doc="stream_processing.xml" id="content_phase">content</link>-фазы. -</para> - -<para> -Функция фильтра вызывается со следующими аргументами: -<list type="tag"> -<tag-name><literal>s</literal></tag-name> -<tag-desc> -объект <link doc="../njs/reference.xml" id="stream">stream-сессии</link> -</tag-desc> - -</list> -</para> - -<para> -В этой фазе может происходить инициализация, -также при помощи метода -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -может регистрироваться вызов -для каждого входящего блока данных. -Для отмены регистрации вызова и отмены фильтра -можно использовать метод -<link doc="../njs/reference.xml" id="s_off"><literal>s.off()</literal></link>. -</para> - -<para> -<note> -Так как обработчик <literal>js_filter</literal> -должен сразу возвращать результат, -то поддерживаются только синхронные операции. -Таким образом, асинхронные операции, например -<link doc="../njs/reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -или -<link doc="../njs/reference.xml" id="settimeout"><literal>setTimeout()</literal></link>, -не поддерживаются. -</note> -</para> - -</directive> - - -<directive name="js_import"> -<syntax><value>модуль.js</value> | -<value>имя_экспорта from модуль.js</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.4.0</appeared-in> - -<para> -Импортирует модуль, позволяющий задавать обработчики location и переменных -на njs. -<literal>Имя_экспорта</literal> является пространством имён -при доступе к функциям модуля. -Если <literal>имя_экспорта</literal> не задано, -то пространством имён будет являться имя модуля. -<example> -js_import stream.js; -</example> -В примере при доступе к экспорту в качестве -пространства имён используется имя модуля <literal>stream</literal>. -Если импортируемый модуль экспортирует <literal>foo()</literal>, -то для доступа используется <literal>stream.foo</literal>. -</para> - -<para> -Директив <literal>js_import</literal> может быть несколько. -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_include"> -<syntax><value>файл</value></syntax> -<default/> -<context>stream</context> - -<para> -Задаёт файл, который позволяет задавать обработчики server и переменных на njs: -<example> -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; -} -</example> -</para> - -<para> -Директива устарела в версии -<link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -и была удалена в версии -<link doc="../njs/changes.xml" id="njs0.7.1">0.7.1</link>. -Вместо неё следует использовать директиву <link id="js_import"/>. -</para> - -</directive> - - -<directive name="js_preload_object"> -<syntax><value>имя.json</value> | -<value>имя</value> from <value>файл.json</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.7.8</appeared-in> - -<para> -Предварительно загружает -<link doc="../njs/preload_objects.xml">неизменяемый объект</link> -во время конфигурации. -<literal>Имя</literal> используется в качестве имени глобальной переменной, -через которую объект доступен в коде njs. -Если <literal>имя</literal> не указано, -то будет использоваться имя файла. -<example> -js_preload_object map.json; -</example> -В примере <literal>map</literal> используется в качестве имени -во время доступа к предварительно загруженному объекту. -</para> - -<para> -Директив <literal>js_preload_object</literal> может быть несколько. -</para> - -</directive> - - -<directive name="js_preread"> -<syntax><value>функция</value> | <value>модуль.функция</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Задаёт функцию njs, которая будет вызываться в -<link doc="stream_processing.xml" id="preread_phase">preread</link>-фазе. -Начиная с <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -можно ссылаться на функцию модуля. -</para> - -<para> -Функция вызывается однократно при первом достижении сессией -<link doc="stream_processing.xml" id="preread_phase">preread</link>-фазы. -Функция вызывается со следующими аргументами: - -<list type="tag"> -<tag-name><literal>s</literal></tag-name> -<tag-desc> -объект <link doc="../njs/reference.xml" id="stream">stream-сессии</link> -</tag-desc> - -</list> -</para> - -<para> -В этой фазе может происходить инициализация, -также при помощи метода -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -может регистрироваться вызов -для каждого входящего блока данных пока не будет вызван один из методов: -<link doc="../njs/reference.xml" id="s_done"><literal>s.done()</literal></link> -<link doc="../njs/reference.xml" id="s_decline"><literal>s.decline()</literal></link>, -<link doc="../njs/reference.xml" id="s_allow"><literal>s.allow()</literal></link>. -При вызове любого из этих методов обработка сессии -переходит на <link doc="stream_processing.xml">следующую фазу</link> -и все текущие вызовы -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -сбрасываются. -</para> - -<para> -<note> -Так как обработчик <literal>js_preread</literal> -должен сразу возвращать результат, -то поддерживаются только синхронные операции. -Таким образом, асинхронные операции, например -<link doc="../njs/reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -или -<link doc="../njs/reference.xml" id="settimeout"><literal>setTimeout()</literal></link>, -не поддерживаются. -Тем не менее асинхронные операции поддерживаются в вызовах -<link doc="../njs/reference.xml" id="s_on"><literal>s.on()</literal></link> -в -<link doc="stream_processing.xml" id="preread_phase">preread</link>-фазе. -Подробнее см. -<link url="https://github.com/nginx/njs-examples#authorizing-connections-using-ngx-fetch-as-auth-request-stream-auth-request">пример</link>. -</note> -</para> - -</directive> - - -<directive name="js_path"> -<syntax> -<value>путь</value></syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.3.0</appeared-in> - -<para> -Задаёт дополнительный путь для модулей njs. -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_periodic"> -<syntax><value>функция</value> | - <value>модуль.функция</value> - [<literal>interval</literal>=<value>время</value>] - [<literal>jitter</literal>=<value>число</value>] - [<literal>worker_affinity</literal>=<value>маска</value>]</syntax> -<default/> -<context>server</context> -<appeared-in>0.8.1</appeared-in> - -<para> -Задаёт периодичность запуска обработчика содержимого. -В качестве первого аргумента обработчик получает -<link doc="../njs/reference.xml" id="periodic_session">объект сессии</link>, -также у обработчика есть доступ к глобальным объектам таким как -<link doc="../njs/reference.xml" id="ngx">ngx</link>. -</para> - -<para> -Необязательный параметр <literal>interval</literal> -задаёт интервал между двумя последовательными запусками, -по умолчанию 5 секунд. -</para> - -<para> -Необязательный параметр <literal>jitter</literal> -задаёт время, в пределах которого -случайным образом задерживается каждый запуск, -по умолчанию задержки нет. -</para> - -<para> -По умолчанию <literal>js_handler</literal> выполняется для рабочего процесса 0. -Необязательный параметр <literal>worker_affinity</literal> -позволяет указать рабочий процесс, -для которого будет выполняться обработчик содержимого location. -Рабочие процессы задаются битовой маской разрешённых к использованию рабочих -процессов. -Маска <literal>all</literal> позволяет обработчику выполняться -для всех рабочих процессов. -</para> - -<para> -Пример: -<example> -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); -} -</example> -</para> - -</directive> - - -<directive name="js_set"> -<syntax> -<value>$переменная</value> <value>функция</value> | -<value>модуль.функция</value></syntax> -<default/> -<context>stream</context> -<context>server</context> - -<para> -Задаёт <literal>функцию</literal> njs -для указанной <literal>переменной</literal>. -Начиная с <link doc="../njs/changes.xml" id="njs0.4.0">0.4.0</link> -можно ссылаться на функцию модуля. -</para> - -<para> -Функция вызывается в момент -первого обращения к переменной для данного запроса. -Точный момент вызова функции зависит от -<link doc="stream_processing.xml">фазы</link>, -в которой происходит обращение к переменной. -Это можно использовать для реализации дополнительной логики, -не относящейся к вычислению переменной. -Например, если переменная указана -в директиве <link doc="ngx_stream_log_module.xml" id="log_format"/>, -то её обработчик не будет выполняться до фазы записи в лог. -Этот обработчик также может использоваться для выполнения процедур -непосредственно перед освобождением запроса. -</para> - -<para> -<note> -Так как обработчик <literal>js_set</literal> -должен сразу возвращать результат, -то поддерживаются только синхронные операции. -Таким образом, асинхронные операции, например -<link doc="../njs/reference.xml" id="ngx_fetch"><literal>ngx.fetch()</literal></link> -или -<link doc="../njs/reference.xml" id="settimeout"><literal>setTimeout()</literal></link>, -не поддерживаются. -</note> -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - - -<directive name="js_shared_dict_zone"> -<syntax> - <literal>zone</literal>=<value>имя</value>:<value>размер</value> - [<literal>timeout</literal>=<value>время</value>] - [<literal>type</literal>=<literal>строка</literal>|<literal>число</literal>] - [<literal>evict</literal>]</syntax> -<default/> -<context>stream</context> -<appeared-in>0.8.0</appeared-in> - -<para> -Задаёт <value>имя</value> и <value>размер</value> зоны разделяемой памяти, -в которой хранится -<link doc="../njs/reference.xml" id="dict">словарь</link> ключей и значений, -разделяемый между рабочими процессами. -</para> - -<para> -По умолчанию в качестве ключа и значения используется строка. -Необязательный параметр <literal>type</literal> -позволяет изменить тип значения на число. -</para> - -<para> -Необязательный параметр <literal>timeout</literal> задаёт время, -по завершении которого все записи в словаре удаляются из зоны. -</para> - -<para> -Необязательный параметр <literal>evict</literal> удаляет самую старую -пару ключ-значение при переполнении зоны. -</para> - -<para> -Пример: -<example> -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)); - } -</example> -</para> - -</directive> - - -<directive name="js_var"> -<syntax><value>$переменная</value> [<value>значение</value>]</syntax> -<default/> -<context>stream</context> -<context>server</context> -<appeared-in>0.5.3</appeared-in> - -<para> -Объявляет -<link doc="../njs/reference.xml" id="r_variables">перезаписываемую</link> -переменную. -В качестве значения можно использовать текст, переменные и их комбинации. -</para> - -<para> -<note> -Директива может быть указана -на уровне <literal>server</literal> -начиная с <link doc="../njs/changes.xml" id="njs0.7.7">0.7.7</link>. -</note> -</para> - -</directive> - -</section> - - -<section id="properties" name="Свойства объекта сессии"> - -<para> -Каждый stream-обработчик njs получает один аргумент, -<link doc="../njs/reference.xml" id="stream">объект</link> stream-сессии. -</para> - -</section> - -</module>
--- a/xml/ru/index.xml Wed Feb 14 20:05:57 2024 +0300 +++ b/xml/ru/index.xml Wed Feb 14 20:06:00 2024 +0300 @@ -8,7 +8,7 @@ <article name="nginx" link="/ru/" lang="ru" - rev="162"> + rev="163"> <section> @@ -203,11 +203,7 @@ </listitem> <listitem> -Встроенный <link doc="docs/http/ngx_http_perl_module.xml">Perl</link>; -</listitem> - -<listitem> -сценарный язык <link doc="docs/njs/index.xml">njs</link>. +Встроенный <link doc="docs/http/ngx_http_perl_module.xml">Perl</link>. </listitem> </list> @@ -330,11 +326,7 @@ </listitem> <listitem> -<link doc="docs/stream/ngx_stream_split_clients_module.xml">A/B-тестирование</link>; -</listitem> - -<listitem> -сценарный язык <link doc="docs/njs/index.xml">njs</link>. +<link doc="docs/stream/ngx_stream_split_clients_module.xml">A/B-тестирование</link>. </listitem> </list>