Reference
njs provides objects, methods and properties for extending nginx functionality. This reference contains only njs specific properties, methods and modules not compliant with ECMAScript. Definitions of njs properties and methods compliant with ECMAScript can be found in ECMAScript specification . List of all njs properties and methods can be found in Compatibility .
nginx objects
HTTP Request
r.args{}
r.done()
r.error()
r.finish()
r.headersIn{}
r.headersOut{}
r.httpVersion
r.internal
r.internalRedirect()
r.log()
r.method
r.parent
r.remoteAddress
r.requestBody
r.requestBuffer
r.requestText
r.rawHeadersIn{}
r.rawHeadersOut{}
r.responseBody
r.responseBuffer
r.responseText
r.return()
r.send()
r.sendBuffer()
r.sendHeader()
r.setReturnValue()
r.status
r.subrequest()
r.uri
r.rawVariables{}
r.variables{}
r.warn()
The HTTP request object is available only in the
ngx_http_js_module
module.
All string properties of the object are
byte strings
.
r.args{}
r.args
as:
{a: "1", b: ["2", "4"], A: "3", B: "two words"}
More advanced parsing scenarios can be achieved with the
Query String
module
and with the
$args
variable, for example:
import qs from 'querystring';
function args(r) {
return qs.parse(r.variables.args);
The argument object
is evaluated at the first access to
r.args
.
If only a single argument is needed, for example
foo
,
nginx variables
can be used:
r.variables.arg_foo
Here,
nginx variables object
returns the first value for a given key,
case-insensitive, without percent-decoding.
To convert
r.args
back to a string,
the Query String
stringify
method can be used.
r.done()
r.error(
string
)
string
to the error log
on the
error
level of logging
As nginx has a
hardcoded
maximum line length limit,
only first 2048 bytes of the string can be logged.
request headers can have only one field value
(
0.4.1
).
Duplicate field values in “Cookie” headers
are separated by semicolon (
;
).
Duplicate field values in all other request headers are separated by commas.
r.headersOut{}
r.headersOut{}
is the response object of
a
subrequest
, it represents response headers.
In this case, field values in
“Accept-Ranges”,
“Connection”,
“Content-Disposition”,
“Content-Encoding”,
“Content-Length”,
“Content-Range”,
“Date”,
“Keep-Alive”,
“Server”,
“Transfer-Encoding”,
“X-Accel-*”
response headers may be omitted.
The “Foo” response header
can be accessed with the syntax:
headersOut.foo
or
headersOut['Foo']
.
Outgoing headers should be set before a response header is sent to a client,
otherwise header update will be ignored.
This means that
r.headersOut{}
is effectively writable in:
For standard response headers
that accept only a single field value such as
“Content-Type”,
only the last element of the array will take effect.
Field values of the “Set-Cookie” response header
are always returned as an array.
Duplicate field values in
“Age”,
“Content-Encoding”,
“Content-Length”,
“Content-Type”,
“ETag”,
“Expires”,
“Last-Modified”,
“Location”,
“Retry-After”
response headers are ignored.
Duplicate field values in all other response headers
are separated by commas.
r.httpVersion
r.internal
r.internalRedirect(
uri
)
uri
.
If the uri starts with the “
@
” prefix,
it is considered a named location.
Redirected requests become internal and can access the
internal
locations.
The actual redirect happens after the handler execution is completed.
After redirect,
a new njs VM is started in the target location,
the VM in the original location is stopped.
Values of
nginx variables
are kept
and can be used to pass information to the target location.
Since
0.5.3
,
the variable declared with the
js_var
directive for
http
or
stream
can be used.
client request body if it has not been written to a temporary file
(since
0.5.0
).
To ensure that the client request body is in memory,
its size should be limited by
client_max_body_size
,
and a sufficient buffer size should be set using
client_body_buffer_size
.
The property is available only in the
js_content
directive.
r.requestText
r.requestBuffer
,
but returns a
string
.
Note that
it may convert bytes invalid in UTF-8 encoding into the replacement character.
r.rawHeadersIn{}
r.rawHeadersIn
will be:
['Host', 'localhost'],
['Foo', 'bar'],
['foo', 'bar2']
All
foo
headers
can be collected with the syntax:
r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1])
the output will be:
['bar', 'bar2']
Header field names are not converted to lower case,
duplicate field values are not merged.
r.rawHeadersOut{}
r.responseBody
r.responseBuffer
the
r.responseText
property
should be used instead.
r.responseBuffer
r.responseBuffer
is limited by the
subrequest_output_buffer_size
directive.
r.responseText
r.responseBuffer
but returns a string
(since
0.5.0
).
Note that
it may convert bytes invalid in UTF-8 encoding into the replacement character.
r.return(status[,
string | Buffer])
status
to the client.
The response can be a string or Buffer
(
0.5.0
).
It is possible to specify either a redirect URL
(for codes 301, 302, 303, 307, and 308)
or the response body text (for other codes) as the second argument
r.send(string
| Buffer)
r.sendBuffer(
data
[,
options
])
options
is an object used
to override nginx buffer flags derived from an incoming data chunk buffer.
The flags can be overridden with the following flags:
boolean,
true if the buffer is the last buffer
flush
flush
flag
The method may be called only from the
js_body_filter
function.
r.sendHeader()
r.setReturnValue(
value
)
r.status
r.subrequest(
uri
[,
options
[,
callback
]])
uri
and
options
, and installs
an optional completion
callback
.
subrequest
shares its input headers with the client request.
To send headers different from original headers to a proxied server, the
proxy_set_header
directive can be used.
To send a completely new set of headers to a proxied server, the
proxy_pass_request_headers
directive can be used.
If
options
is a string, then it
holds the subrequest arguments string.
Otherwise,
options
is expected to be
an object with the following keys:
arguments string, by default an empty string is used
request body,
by default the request body of the parent request object is used
method
GET
method is used
detached
true
, the created subrequest is a detached subrequest.
Responses to detached subrequests are ignored.
Unlike ordinary subrequests, a detached subrequest
can be created inside a variable handler.
The
detached
flag and callback argument
are mutually exclusive.
if a
callback
is not provided,
the
Promise
object
that resolves to the
subrequest response object
is returned.
For example, to view all response headers in the subrequest:
async function handler(r) [
let reply = await r.subrequest('/path');
for (var h in reply.headersOut) {
r.log(`${h}: ${reply.headersOut[h]}`);
r.return(200);
nginx treats variables referenced in
nginx.conf
and unreferenced variables differently.
When a variable is referenced, it may be cacheable,
but when it is unreferenced it is always uncacheable.
For example, when the
$request_id
variable is only accessed from njs,
it has a new value every time it is evaluated.
But, when the
$request_id
is referenced, for example:
proxy_set_header X-Request-Id $request_id;
the
r.variables.request_id
returns the same value every time.
A variable is writable if:
it was created using the
js_var
directive for
http
or
stream
(since
0.5.3
)
it is referenced in nginx configuration file
Even so, some embedded variables still cannot be assigned a value (for example,
$http_
).
r.warn(
string
)
string
to the error log
on the
warning
level of logging
As nginx has a
hardcoded
maximum line length limit,
only first 2048 bytes of the string can be logged.
phase
handler
to a code value, by default
0
.
The actual finalization happens when the js handler is completed
and all pending events, for example, from
ngx.fetch()
or
setTimeout()
,
are processed
(
0.2.4
).
Possible code values:
successful finalization, passing control to the next phase
-5
—
undecided, passing control to the next handler of the current phase (if any)
403
—
access is forbidden
The completion callback has the following prototype:
callback(data, flags)
, where
data
is string or Buffer (depending on the event type)
flags
is an object
with the following properties:
a boolean value, true if data is a last buffer.
adds data to the chain of data chunks that will be forwarded in
the forward direction:
in download callback to a client; in upload to an upstream server
(
0.2.4
).
The actual forwarding happens later,
when the all the data chunks of the current chain are processed.
The data can be a string or Buffer
(
0.5.0
).
The
options
is an object used
to override nginx buffer flags derived from an incoming data chunk buffer.
The flags can be overridden with the following flags:
boolean,
true if the buffer is the last buffer
flush
flush
flag
The method can be called multiple times per callback invocation.
s.sendDownstream()
s.sendUpstream()
s.status
$status
variable,
read only
(since
0.5.2
)
s.setReturnValue(
value
)
s.variables{}
s.warn(
string
)
string
to the error log
on the
warning
level of logging
As nginx has a
hardcoded
maximum line length limit,
only first 2048 bytes of the string can be logged.
Appends a new value into an existing header in the
Headers
object,
or adds the header if it does not already exist
(since
0.7.10
).
delete()
Headers
object
(since
0.7.10
).
get()
getAll(
name
)
forEach()
Headers
object
(since
0.7.10
).
has()
set()
Headers
object,
or adds the header if it does not already exist
(since
0.7.10
).
Request
Request()
Request.arrayBuffer()
Request.bodyUsed
Request.cache
Request.credentials
Request.headers
Request.json()
Request.method
Request.mode
Request.text()
Request.url
The
Request
interface of the
Fetch API
is available since
0.7.10
.
A new
Request
object can be created using the
Request()
constructor:
Request[
resource
[,
options
]])
Request
object to fetch
that can be passed later to
ngx.fetch()
.
The
resource
can be a URL
or an existing
Request
object.
The
options
is an optional argument
that is expected to be an object with the following keys:
The request body, by default is empty.
headers
Headers
object,
can be a
string
,
an
array
of name-value pairs,
or an existing
Headers
object.
method
Headers
object,
can be a
string
,
an
array
of name-value pairs,
or an existing
Headers
object.
status
statusText
Response
stream and reads it to completion.
Returns a
Promise
that resolves with
an
ArrayBuffer
.
bodyUsed
true
if the body was read.
headers
Headers
read-only object
associated with the
Response
.
json()
Response
stream and reads it to completion.
Returns a
Promise
that resolves with
the result of parsing the body text as JSON.
A boolean value,
true
if the response was successful (status codes between 200–299).
redirected
true
if the response is the result of a redirect.
status
statusText
text()
Response
stream and reads it to completion.
Returns a
Promise
that resolves with a string.
The type of the response.
The URL of the response.
ngx.build
ngx.conf_file_path
ngx.conf_prefix
ngx.error_log_path
ngx.fetch()
ngx.log()
ngx.prefix
ngx.version
ngx.version_number
ngx.worker_id
The
ngx
global object is available
since
0.5.0
.
ngx.build
--build=name
argument
of the
configure
script,
by default is
""
(
0.8.0
)
ngx.conf_file_path
ngx.conf_prefix
ngx.error_log_path
ngx.fetch(
resource
,
[
options
])
resource
(
0.5.1
), which can be an
URL or the
Request
object
(
0.7.10
).
Returns a
Promise
that resolves with
the
Response
object.
Since
0.7.0
,
the
https://
scheme is supported,
redirects are not handled.
If the URL in the
resource
is specified as a domain name,
it is determined using a
resolver
.
If the
https://
scheme is specified, the
js_fetch_trusted_certificate
directive should be configured
for the authentication of the
resource
's HTTPS server.
The
options
parameter is expected to be an object
with the following keys:
request body,
by default is empty
buffer_size
4096
headers
max_response_body_size
32768
method
GET
method is used
verify
true
(
0.7.0
)
Example:
let reply = await ngx.fetch('http://nginx.org/');
let body = await reply.text();
r.return(200, body);
writes a message to the error log with the specified level of logging.
The
level
parameter specifies one of the log levels,
the
message
parameter can be a string or Buffer.
The following log levels can be specified:
ngx.INFO
,
ngx.WARN
, and
ngx.ERR
.
As nginx has a
hardcoded
maximum line length limit,
only first 2048 bytes of the string can be logged.
a number that corresponds to nginx internal worker id,
the value is between
0
and the value specified in the
worker_processes
directive
(
0.8.0
)
built-in objects
crypto
сrypto.getRandomValues()
сrypto.subtle.encrypt()
сrypto.subtle.decrypt()
сrypto.subtle.deriveBits()
сrypto.subtle.deriveKey()
сrypto.subtle.digest()
сrypto.subtle.exportKey()
сrypto.subtle.generateKey()
сrypto.subtle.importKey()
сrypto.subtle.sign()
сrypto.subtle.verify()
The
crypto
object is a global object
that allows using cryptographic functionality
(since
0.7.0
).
сrypto.getRandomValues
(
typedArray
)
typedArray
but with its contents replaced with the newly generated random numbers.
Possible values:
typedArray
Int8Array
,
Int16Array
,
Uint16Array
,
Int32Array
, or
Uint32Array
Returns a
Promise
that fulfills with
an
ArrayBuffer
containing the ciphertext.
Possible values:
algorithm
RSA-OAEP
,
pass the object with the following keys:
DataView
—
the initial value of the counter block,
must be 16 bytes long (the AES block size).
The rightmost length bits of this block are used for the counter,
and the rest is used for the nonce.
For example, if length is set to 64,
then the first half of counter is the nonce
and the second half is used for the counter
length
is the number of bits in the counter block
that are used for the actual counter.
The counter must be big enough that it doesn't wrap.
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.
DataView
that contains additional data that
will not be encrypted but will be authenticated along with the encrypted data.
If
additionalData
is specified,
then the same data must be specified in the corresponding call to
decrypt()
:
if the data given to the
decrypt()
call
does not match the original data,
the decryption will throw an exception.
The bit length of
additionalData
must be smaller than
2^64 - 1
.
tagLength
(optional, default is
128
) -
a
number
that determines the size in bits
of the authentication tag generated in the encryption operation
and used for authentication in the corresponding decryption
Possible values:
104
,
112
,
120
, or
128
.
The AES-GCM specification recommends that it should be
104
,
112
,
120
, or
128
,
although
32
or
bits may be acceptable in some applications.
an object
that specifies the algorithm to be used, and any extra parameters as required.
The values given for the extra parameters must match
those passed into the corresponding
encrypt()
call.
for
RSA-OAEP
,
pass the object with the following keys:
DataView
—
the initial value of the counter block,
must be 16 bytes long (the AES block size).
The rightmost length bits of this block are used for the counter,
and the rest is used for the nonce.
For example, if length is set to 64,
then the first half of counter is the nonce
and the second half is used for the counter.
length
is the number of bits in the counter block
that are used for the actual counter.
The counter must be big enough that it doesn't wrap.
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).
DataView
that contains additional data that
will not be encrypted but will be authenticated along with the encrypted data.
If
additionalData
is specified,
then the same data must be specified in the corresponding call to
decrypt()
:
if the data given to the
decrypt()
call
does not match the original data,
the decryption will throw an exception.
The bit length of
additionalData
must be smaller than
2^64 - 1
.
tagLength
(optional, default is
128
) -
a
number
that determines the size in bits
of the authentication tag generated in the encryption operation
and used for authentication in the corresponding decryption.
Possible values:
104
,
112
,
120
, or
128
.
The AES-GCM specification recommends that it should be
104
,
112
,
120
, or
128
,
although
32
or
bits may be acceptable in some applications.
a
CryptoKey
that contains the key to be used for decryption.
If
RSA-OAEP
is used, this is the
privateKey
property of the
CryptoKeyPair
object.
ArrayBuffer
,
TypedArray
, or
DataView
that contains the data to be decrypted (also known as ciphertext)
Derives an array of bits from a base key.
Returns a
Promise
which will be fulfilled with an
ArrayBuffer
that contains the derived bits.
Possible values:
algorithm
HKDF
,
pass the object with the following keys:
DataView
that represents random or pseudo-random value
with the same length as the output of the
digest
function.
Unlike the input key material passed into
deriveKey()
,
salt does not need to be kept secret.
info
is an
ArrayBuffer
,
TypedArray
, or
DataView
that represents application-specific contextual information
used to bind the derived key to an application or context,
and enables deriving different keys for different contexts
while using the same input key material.
This property is required but may be an empty buffer.
that represents random or pseudo-random value
of at least
16
bytes.
Unlike the input key material passed into
deriveKey()
,
salt does not need to be kept secret.
iterations
is a
number
that represents the number of times the hash function will be executed
in
deriveKey()
is a
CryptoKey
that represents the input to the derivation algorithm
- the initial key material for the derivation function:
for example, for
PBKDF2
it might be a password,
imported as a
CryptoKey
using
сrypto.subtle.importKey()
length
8
DataView
that represents random or pseudo-random value
with the same length as the output of the
digest
function.
Unlike the input key material passed into
deriveKey()
,
salt does not need to be kept secret.
info
is an
ArrayBuffer
,
TypedArray
, or
DataView
that represents application-specific contextual information
used to bind the derived key to an application or context,
and enables deriving different keys for different contexts
while using the same input key material.
This property is required but may be an empty buffer.
that represents random or pseudo-random value
of at least
16
bytes.
Unlike the input key material passed into
deriveKey()
,
salt does not need to be kept secret.
iterations
is a
number
that represents the number of times the hash function will be executed
in
deriveKey()
is a
CryptoKey
that represents the input to the derivation algorithm
- the initial key material for the derivation function:
for example, for
PBKDF2
it might be a password,
imported as a
CryptoKey
using
сrypto.subtle.importKey()
.
derivedKeyAlgorithm
HMAC
,
pass the object with the following keys:
length
(optional) is a
number
that represents the length in bits of the key.
If not specified, the length of the key is equal to
the block size of the chozen hash function
is an
Array
that indicates what can be done with the derived key.
The key usages must be allowed by the algorithm
set in
derivedKeyAlgorithm
.
Possible values:
encrypt
decrypt
verify
deriveKey
deriveBits
wrapKey
unwrapKey
Promise
which will be fulfilled with the digest.
Possible values:
algorithm
SHA-1
(not for cryptographic applications),
SHA-256
,
SHA-384
, or
SHA-512
is an
ArrayBuffer
,
TypedArray
, or
DataView
that contains the data to be digested
Exports a key: takes a key as
a
CryptoKey
object
and returns the key in an external, portable format
(since
0.7.10
).
If the
format
was
jwk
,
then the
Promise
fulfills with a JSON object
containing the key.
Otherwise, the promise fulfills with an
ArrayBuffer
containing the key.
Possible values:
format
pkcs8
Promise
that fulfills with the generated key
a
CryptoKey
or
CryptoKeyPair
object.
Possible values:
algorithm
RSASSA-PKCS1-v1_5
,
RSA-PSS
, or
RSA-OAEP
,
pass the object with the following keys:
name
is a string, should be set to
RSASSA-PKCS1-v1_5
,
RSA-PSS
, or
RSA-OAEP
,
depending on the used algorithm
hash
is a string that represents
the name of the
digest
function to use, can be
SHA-256
,
SHA-384
, or
SHA-512
namedCurve
is a string that represents
the name of the elliptic curve to use, may be
P-256
,
P-384
, or
P-521
length
(optional) is a number that represents
the length in bits of the key.
If omitted, the length of the key is equal to the length of the digest
generated by the chosen digest function.
AES-GCM
,
pass the string identifying the algorithm or an object
of the form
{ "name": "ALGORITHM" }
,
where
ALGORITHM
is the name of the algorithm
Imports a key: takes as input a key in an external, portable format
and gives a
CryptoKey
object.
Returns a
Promise
that fulfills with the imported key
as a
CryptoKey
object.
Possible values:
format
pkcs8
namedCurve
is a string that represents
the name of the elliptic curve to use, may be
P-256
,
P-384
, or
P-521
length
(optional) is a number that represents
the length in bits of the key.
If omitted, the length of the key is equal to the length of the digest
generated by the chosen digest function.
AES-GCM
,
pass the string identifying the algorithm or an object
of the form
{ "name": "ALGORITHM" }
,
where
ALGORITHM
is the name of the algorithm
PBKDF2
,
pass the
PBKDF2
string
HKDF
,
pass the
HKDF
string
Returns
signature
as a
Promise
that fulfills with an
ArrayBuffer
containing the signature.
Possible values:
algorithm
CryptoKey
object
that the key to be used for signing.
If algorithm identifies a public-key cryptosystem, this is the private key.
is an
ArrayBuffer
,
TypedArray
, or
DataView
object that contains the data to be signed
Verifies a digital signature,
returns a
Promise
that fulfills with a boolean value:
true
if the signature is valid,
otherwise
false
.
Possible values:
algorithm
CryptoKey
object
that the key to be used for verifying.
It is the secret key for a symmetric algorithm
and the public key for a public-key system.
signature
ArrayBuffer
,
TypedArray
, or
DataView
that contains the signature to verify
is an
ArrayBuffer
,
TypedArray
, or
DataView
object that contains the data whose signature is to be verified
The
CryptoKey
object
represents a cryptographic
key
obtained
from one of the
SubtleCrypto
methods:
сrypto.subtle.generateKey()
,
сrypto.subtle.deriveKey()
,
сrypto.subtle.importKey()
.
CryptoKey.algorithm
CryptoKey.extractable
true
if the key can be exported
(since
0.8.0
),
read-only
CryptoKey.type
secret
private
CryptoKeyPair
public
CryptoKeyPair
.
Returns a number with the current version of njs.
For example, “0.7.4” is returned as
0x000704
(since
0.7.4
).
njs.dump(
value
)
njs.memoryStats
process.env
process.pid
process.ppid
String
By default all strings in njs are Unicode strings. They correspond to ECMAScript strings that contain Unicode characters. Before 0.8.0 , byte strings were also supported.
Byte strings
Since
0.8.0
,
the support for byte strings and byte string methods were removed.
When working with byte sequence,
the
Buffer
object
and
Buffer
properties, such as
r.requestBuffer
,
r.rawVariables
,
should be used.
Byte strings contain a sequence of bytes
and are used to serialize Unicode strings
to external data and deserialize from external sources.
For example, the
toUTF8()
method serializes
a Unicode string to a byte string using UTF-8 encoding:
>> '£'.toUTF8().toString('hex')
'c2a3' /* C2 A3 is the UTF-8 representation of 00A3 ('£') code point */
The
toBytes()
method serializes
a Unicode string with code points up to 255 into a byte string,
otherwise,
null
is returned:
>> '£'.toBytes().toString('hex')
'a3' /* a3 is a byte equal to 00A3 ('£') code point */
The
Buffer.from
method should be used instead:
>> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString()
'buffer'
>> Buffer.from('YnVmZmVy', 'base64').toString()
'buffer'
Before
0.4.4
,
created a byte string either from an array that contained octets,
or from an encoded string
(
0.2.3
),
the encoding could be
hex
,
base64
, and
base64url
.
String.prototype.fromBytes(
start
[,
end
])
String.prototype.fromUTF8(
start
[,
end
])
TextDecoder
method
should be used instead.
Before
0.7.7
,
converted a byte string containing a valid UTF-8 string
into a Unicode string,
otherwise
null
was returned.
String.prototype.toBytes(
start
[,
end
])
null
if a character larger than 255 was
found in the string.
String.prototype.toString(
encoding
)
hex
,
base64
, or
base64url
:
>> 'αβγδ'.toString('base64url')
'zrHOss6zzrQ'
Before version
0.4.3
,
only a
byte string
could be encoded:
>> 'αβγδ'.toUTF8().toString('base64url')
'zrHOss6zzrQ'
Creates a new
TextDecoder
object
for specified
encoding
,
currently, only UTF-8 is supported.
The
options
is
TextDecoderOptions
dictionary with the property:
fatal
TextDecoder.decode()
must throw the
TypeError
exception when
a coding error is found, by default is
false
.
boolean flag indicating if
additional data will follow in subsequent calls to
decode()
:
true
if processing the data in chunks, and
false
for the final chunk
or if the data is not chunked.
By default is
false
.
The
TextEncoder
object
produces a byte stream with UTF-8 encoding
from a stream of code points
(
0.4.3
).
TextEncoder()
TextEncoder
that will generate a byte stream with UTF-8 encoding.
TextEncoder.prototype.encode(
string
)
string
into a
Uint8Array
with UTF-8 encoded text.
TextEncoder.prototype.encodeInto(
string
,
uint8Array
)
string
to UTF-8,
puts the result into destination
Uint8Array
, and
returns a dictionary object that shows the progress of the encoding.
The dictionary object contains two members:
the number of UTF-16 units of code from the source
string
converted to UTF-8
written
Uint8Array
after a specified number of
milliseconds
.
One or more optional
arguments
can be passed to the specified function.
Returns a
timeout
object.
function handler(v)
// ...
t = setTimeout(handler, 12);
// ...
clearTimeout(t);
Decodes a string of data which has been encoded
using
Base64
encoding.
The
encodedData
parameter is a binary string
that contains Base64-encoded data.
Returns a string that contains decoded data from
encodedData
.
The similar
btoa()
method
can be used to encode and transmit data
which may otherwise cause communication problems,
then transmit it and use the
atob()
method
to decode the data again.
For example, you can encode, transmit, and decode control characters
such as ASCII values
0
through
31
.
const encodedData = btoa("text to encode"); // encode a string
const decodedData = atob(encodedData); // decode the string
Creates a Base64-encoded ASCII string from a binary string.
The
stringToEncode
parameter is a binary string to encode.
Returns an ASCII string containing the Base64 representation of
stringToEncode
.
The method can be used to encode data
which may otherwise cause communication problems, transmit it,
then use the
atob()
method
to decode the data again.
For example, you can encode control characters
such as ASCII values
0
through
31
.
const encodedData = btoa("text to encode"); // encode a string
const decodedData = atob(encodedData); // decode the string
Allocates a new Buffer of a specified
size
.
If
fill
is not specified, the Buffer will be zero-filled.
If
fill
is specified,
the allocated Buffer will be initialized by calling
buf.fill(fill)
.
If
fill
and
encoding
are specified,
the allocated Buffer will be initialized by calling
buf.fill(fill,
encoding)
.
The
fill
parameter may be a
string
,
Buffer
,
Uint8Array
, or
integer
.
Buffer.allocUnsafe(
size
)
Buffer.alloc()
,
with the difference that the memory allocated for the buffer is not initialized,
the contents of the new buffer is unknown and may contain sensitive data.
Buffer.byteLength(
value
[,
encoding
])
encoding
.
The value can be a
string
,
Buffer
,
TypedArray
,
DataView
, or
ArrayBuffer
.
If the value is a
string
,
the
encoding
parameter is its encoding, can be
utf8
,
hex
,
base64
,
base64url
;
by default is
utf8
.
Buffer.compare(
buffer1
,
buffer2
)
buffer1
with
buffer2
when sorting arrays of Buffer instances.
Returns
buffer1
is the same as
buffer2
,
buffer2
should come before
buffer1
when sorted, or
-1
if
buffer2
should come after
buffer1
when sorted.
Buffer.concat(
list
[,
totalLength
])
totalLength
is not specified,
it is calculated from the Buffer instances in list by adding their lengths.
If
totalLength
is specified,
it is coerced to an unsigned integer.
If the combined length of the Buffers in list exceeds
totalLength
,
the result is truncated to
totalLength
.
Buffer.from(
array
)
0
–
255
.
Array entries outside that range will be truncated.
Buffer.from(
arrayBuffer
,
byteOffset
[,
length
]])
ArrayBuffer
without copying the underlying memory.
The optional
byteOffset
and
length
arguments
specify a memory range within the
arrayBuffer
that will be shared by the Buffer.
Buffer.from(
buffer
)
Buffer.from(
object
[,
offsetOrEncoding
[,
length
]])
valueOf()
function
returns a value not strictly equal to object,
returns
Buffer.from(object.valueOf()
,
offsetOrEncoding
,
length
).
Buffer.from(
string
[,
encoding
])
string
.
The
encoding
parameter identifies the character encoding
to be used when converting a string into bytes.
The encoding can be
utf8
,
hex
,
base64
,
base64url
;
by default is
utf8
.
Buffer.isBuffer(
object
)
true
if
object
is a Buffer.
Buffer.isEncoding(
encoding
)
true
if encoding is the name of a supported character encoding.
buffer[
index
]
index
in
buffer
.
The values refer to individual bytes,
so the legal value range is between 0 and 255 (decimal).
buf.buffer
ArrayBuffer
object
based on which this Buffer object is created.
buf.byteOffset
byteOffset
of the Buffers
underlying
ArrayBuffer
object.
buf.compare(
target
[,
targetStart
[,
targetEnd
[,
sourceStart
[,
sourceEnd
]]]])
target
and returns a number
indicating whether buffer comes before, after, or is the same
as
target
in sort order.
Comparison is based on the actual sequence of bytes in each Buffer.
The
targetStart
is an integer specifying
the offset within
target
at which to begin comparison,
by default is 0.
The
targetEnd
is an integer specifying
the offset within
target
at which to end comparison,
by default is
target.length
.
The
sourceStart
is an integer specifying
the offset within buffer at which to begin comparison,
by default is 0.
The
sourceEnd
is an integer specifying
the offset within buffer at which to end comparison (not inclusive),
by default is
buf.length
.
buf.copy(
target
[,
targetStart
[,
sourceStart
[,
sourceEnd
]]])
target
,
even if the target memory region overlaps with buffer.
The
target
parameter is a
Buffer
or
Uint8Array
to copy into.
The
targetStart
is an integer specifying
the offset within target at which to begin writing,
by default is 0.
The
sourceStart
is an integer specifying
the offset within buffer from which to begin copying,
by default is 0.
The
sourceEnd
is an integer specifying
the offset within buffer at which to stop copying (not inclusive)
by default is
buf.length
.
buf.equals(
otherBuffer
)
true
if both Buffer and
otherBuffer
have exactly the same bytes.
buf.fill(
value
[,
offset
[,
end
]][,
encoding
])
value
.
If the
offset
and
end
are not specified,
the entire Buffer will be filled.
The
value
is coerced to
uint32
if it is not a
string
,
Buffer
, or
integer
.
If the resulting integer is greater than 255,
the Buffer will be filled with
value
and 255.
buf.includes(
value
[,
byteOffset
][,
encoding
])
buf.indexOf()
!== -1
,
returns
true
if the
value
was found
in Buffer.
buf.indexOf(
value
[,
byteOffset
][,
encoding
])
value
in Buffer, or
-1
if Buffer does not contain value.
The
value
can be a
string
with specified
encoding
(by default
utf8
),
Buffer
,
Unit8Array
,
or a number between 0 and 255.
buf.lastIndexOf(
value
[,
byteOffset
][,
encoding
])
buf.indexOf()
,
except the last occurrence of the
value
is found
instead of the first occurrence.
The
value
can be a string, Buffer, or
integer between 1 and 255.
If the
value
is an empty string or empty Buffer,
byteOffset
will be returned.
buf.length
buf.readIntBE(
offset
,
byteLength
)
byteLength
from
buf
at the specified
offset
and interprets the result as a big-endian,
two's complement signed value supporting up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The similar methods are also supported:
buf.readInt8([offset])
,
buf.readInt16BE([offset])
,
buf.readInt32BE([offset])
.
buf.readIntLE(
offset
,
byteLength
)
byteLength
from
buf
at the specified
offset
and interprets the result as a little-endian,
two's complement signed value supporting up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The similar methods are also supported:
buf.readInt8([offset])
,
buf.readInt16LE([offset])
,
buf.readInt32LE([offset])
.
buf.readUIntBE(
offset
,
byteLength
)
byteLength
from
buf
at the specified
offset
and interprets the result as a big-endian
integer supporting up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The similar methods are also supported:
buf.readUInt8([offset])
,
buf.readUInt16BE([offset])
,
buf.readUInt32BE([offset])
.
buf.readUIntLE(
offset
,
byteLength
)
byteLength
from
buf
at the specified
offset
and interprets the result as a little-endian
integer supporting up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The similar methods are also supported:
buf.readUInt8([offset])
,
buf.readUInt16LE([offset])
,
buf.readUInt32LE([offset])
.
buf.readDoubleBE
([
offset
])
buf
at the specified
offset
.
buf.readDoubleLE
([
offset
])
buf
at the specified
offset
.
buf.readFloatBE
([
offset
])
buf
at the specified
offset
.
buf.readFloatLE
([
offset
])
buf
at the specified
offset
.
buf.subarray([
start
[,
end
]])
buf
that references the same memory as the original,
but offset and cropped by
start
and
end
.
If
end
is greater than
buf.length
,
the same result as that of end equal to
buf.length
is returned.
buf.slice([
start
[,
end
]])
buf
that references the same memory as the original,
but offset and cropped by the
start
and
end
values.
The method is not compatible with the
Uint8Array.prototype.slice()
,
which is a superclass of Buffer.
To copy the slice, use
Uint8Array.prototype.slice()
.
buf.swap16
()
buf
as an array of unsigned 16-bit numbers
and swaps the byte order in-place.
Throws an error if
buf.length
is not a multiple of 2.
buf.swap32
()
buf
as an array of unsigned 32-bit numbers
and swaps the byte order in-place.
Throws an error if
buf.length
is not a multiple of 4.
buf.swap64
()
buf
as an array of 64-bit numbers
and swaps byte order in-place.
Throws an error if
buf.length
is not a multiple of 8.
buf.toJSON
()
buf.
JSON.stringify()
implicitly calls this function when stringifying a Buffer instance.
buf.toString([
encoding
[,
start
[,
end
]]])
buf
to a string
according to the specified character
encoding
which can be
utf8
,
hex
,
base64
,
base64url
.
The
start
and
end
parameters
may be passed to decode only a subset of Buffer.
buf.write(
string
[,
offset
[,
length
]][,
encoding
])
string
to
buf
at
offset
according to the character
encoding
.
The
length
parameter is the number of bytes to write.
If Buffer did not contain enough space to fit the entire string,
only part of string will be written,
however, partially encoded characters will not be written.
The
encoding
can be
utf8
,
hex
,
base64
,
base64url
.
buf.writeIntBE(
value
,
offset
,
byteLength
)
byteLength
bytes of
value
to
buf
at the specified
offset
as big-endian.
Supports up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The following similar methods are also supported:
buf.writeInt8
,
buf.writeInt16BE
,
buf.writeInt32BE
.
buf.writeIntLE(
value
,
offset
,
byteLength
)
byteLength
bytes of
value
to
buf
at the specified
offset
as little-endian.
Supports up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The following similar methods are also supported:
buf.writeInt8
,
buf.writeInt16LE
,
buf.writeInt32LE
.
buf.writeUIntBE(
value
,
offset
,
byteLength
)
byteLength
bytes of
value
to
buf
at the specified
offset
as big-endian.
Supports up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The following similar methods are also supported:
buf.writeUInt8
,
buf.writeUInt16BE
,
buf.writeUInt32BE
.
buf.writeUIntLE(
value
,
offset
,
byteLength
)
byteLength
bytes of
value
to
buf
at the specified
offset
as little-endian.
Supports up to 48 bits of accuracy.
The
byteLength
parameter is an integer between 1 and 6
specifying the number of bytes to read.
The following similar methods are also supported:
buf.writeUInt8
,
buf.writeUInt16LE
,
buf.writeUInt32LE
.
buf.writeDoubleBE(
value
,
[
offset
])
value
to
buf
at the specified
offset
as big-endian.
buf.writeDoubleLE(
value
,
[
offset
])
value
to
buf
at the specified
offset
as little-endian.
buf.writeFloatBE(
value
,
[
offset
])
value
to
buf
at the specified
offset
as big-endian.
buf.writeFloatLE(
value
,
[
offset
])
value
to
buf
at the specified
offset
as little-endian.
Crypto
crypto.createHash()
crypto.createHmac()
Since
0.7.0
,
extended crypto API is available as a global
crypto
object.
The Crypto module provides cryptographic functionality support.
The Crypto module object is returned by
require('crypto')
.
crypto.createHash(
algorithm
)
algorithm
.
The algorithm can be
md5
,
sha1
, and
sha256
.
crypto.createHmac(
algorithm
,
secret key
)
algorithm
and
secret key
.
The algorithm can be
md5
,
sha1
, and
sha256
.
hash.update()
hash.digest()
>> cr.createHash('sha1').update('A').update('B').digest('base64url')
'BtlFlCqiamG-GMPiK_GbvKjdK10'
hmac.update()
hmac.digest()
Calculates the HMAC digest of all of the data passed using
hmac.update()
.
The encoding can be
hex
,
base64
, and
base64url
.
If encoding is not provided, a Buffer object
(
0.4.4
) is returned.
Before version
0.4.4
,
a byte string was returned instead of a Buffer object.
>> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url')
'Oglm93xn23_MkiaEq_e9u8zk374'
File System
fs.accessSync()
fs.appendFileSync()
fs.fstatSync()
fs.lstatSync()
fs.mkdirSync()
fs.openSync()
fs.promises.open()
fs.readSync()
fs.readdirSync()
fs.readFileSync()
fs.realpathSync()
fs.renameSync()
fs.rmdirSync()
fs.statSync()
fs.symlinkSync()
fs.writeSync()
fs.writeSync()
fs.unlinkSync()
fs.writeFileSync()
The File System module provides operations with files.
The module object is returned by
require('fs')
.
Since
0.3.9
,
promissified versions of file system methods are available through
require('fs').promises
object:
> var fs = require('fs').promises;
undefined
> fs.readFile("/file/path").then((data)=>console.log(data))
<file data>
accessSync(
path
[,
mode
])
path
(
0.3.9
).
If the check fails, an error will be returned,
otherwise, the method will return undefined.
an optional integer
that specifies the accessibility checks to be performed,
by default is
fs.constants.F_OK
try {
fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK);
console.log('has access');
} catch (e) {
console.log('no access');)
Synchronously appends specified
data
to a file with provided
filename
.
The
data
is expected to be a string
or a Buffer object (
0.4.4
).
If the file does not exist, it will be created.
The
options
parameter is expected to be
an object with the following keys:
mode option, by default is
0o666
file system
flag
,
by default is
a
(
0.7.7
).
The
fd
parameter is an integer
representing the file descriptor used by the method.
lstatSync(
path
[,
options
])
fs.Stats
object
for the symbolic link referred to by
path
(
0.7.1
).
The
options
parameter is expected to be
an object with the following keys:
throwIfNoEntry
undefined
,
by default is
false
.
Synchronously creates a directory at the specified
path
(
0.4.2
).
The
options
parameter is expected to be an
integer
that specifies
the
mode
,
or an object with the following keys:
mode option, by default is
0o777
.
Reads the content of a file path using file descriptor
fd
,
returns the number of bytes read
(
0.7.7
).
buffer
buffer
value can be a
Buffer
,
TypedArray
, or
DataView
offset
integer
representing
the position in buffer to write the data to
length
integer
representing
the number of bytes to read
position
integer
or
null
,
by default is
null
.
If
position
is
null
,
data will be read from the current file position,
and the file position will be updated.
If position is an
integer
,
the file position will be unchanged
The
options
parameter is expected to be
a string that specifies
encoding
or an object with the following keys:
encoding
utf8
.
The encoding can be
utf8
and
buffer
(
0.4.4
).
withFileTypes
true
, the files array will contain
fs.Dirent
objects,
by default is
false
.
Synchronously returns the contents of the file
with provided
filename
.
The
options
parameter holds
string
that specifies encoding.
If an encoding is specified, a string is returned,
otherwise, a Buffer object
(
0.4.4
) is returned.
Before version
0.4.4
,
a
byte string
was returned
if encoding was not specified.
Otherwise,
options
is expected to be
an object with the following keys:
encoding
utf8
,
(
0.4.4
),
base64
(
0.4.4
),
base64url
(
0.4.4
).
file system
flag
,
by default is
r
>> var file = fs.readFileSync('/file/path.tar.gz')
undefined
>> var gzipped = file.slice(0,2).toString('hex') === '1f8b'; gzipped
realpathSync(
path
[,
options
])
.
,
..
and symbolic links using
realpath(3)
.
The
options
argument can be a string specifying an encoding,
or an object with an encoding property specifying the character encoding
to use for the path passed to the callback
(
0.3.9
).
renameSync(
oldPath
,
newPath
)
oldPath
to
newPath
(
0.3.4
).
>> var fs = require('fs')
undefined
>> var file = fs.renameSync('hello.txt', 'HelloWorld.txt')
undefined
rmdirSync(
path
)
path
(
0.4.2
).
statSync(
path
,[
options
])
fs.Stats
object
for the specified
path
(
0.7.1
).
The
path
can be a
string
or
buffer
.
The
options
parameter is expected to be
an object with the following keys:
throwIfNoEntry
undefined
,
by default is
true
.
is an
integer
specifying the number of bytes to write,
by default is an offset of
Buffer.byteLength
position
integer
or
null
,
by default is
null
.
See also
pwrite(2)
.
refers to the offset from the beginning of the file
where this data should be written,
can be an
integer
or
null
, by default is
null
.
See also
pwrite(2)
encoding
string
,
by default is
utf8
Synchronously writes
data
to a file
with provided
filename
.
The
data
is expected to be a string
or a Buffer object (
0.4.4
).
If the file does not exist, it will be created,
if the file exists, it will be replaced.
The
options
parameter is expected to be
an object with the following keys:
mode option, by default is
0o666
file system
flag
,
by default is
w
for a numeric file descriptor
(
0.7.7
).
Instances of the
FileHandle
object are created by the
fs.promises.open()
method.
If a
FileHandle
is not closed using the
filehandle.close()
method,
it will try to automatically close the file descriptor,
helping to prevent memory leaks.
Please do not rely on this behavior because it can be unreliable.
Instead, always explicitly close a
FileHandle
.
filehandle.close()
promise
, fulfills with undefined upon success.
filehandle.fd
FileHandle
object.
filehandle.read(
buffer
,
offset
[,
length
[,
position
]])
buffer
Buffer
,
TypedArray
, or
DataView
offset
integer
representing the location in the buffer at which to start filling
length
integer
representing the number of bytes to read
position
integer
,
null
.
If
null
, data will be read from the current file position
and the position will be updated.
If position is an
integer
,
the current file position will remain unchanged.
Returns a
Promise
which fulfills upon success
with an object with two properties:
bytesRead
integer
representing the number of bytes read
buffer
Buffer
,
TypedArray
, or
DataView
is an
integer
representing
the start position from within buffer where the data to write begins
length
integer
representing
the number of bytes from buffer to write, by default
is an offset of
Buffer.byteLength
position
integer
or
null
,
by default is
null
.
If
position
is not a
number
,
the data will be written at the current position.
See the POSIX
pwrite(2)
documentation for details.
Returns a
Promise
which is resolved with an object
containing two properties:
bytesWritten
integer
representing the number of bytes written
buffer
Buffer
,
TypedArray
, or
DataView
the offset from the beginning of the file
where the data from buffer should be written,
can be an
integer
or
null
,
by default is
null
.
If
position
is not a
number
,
the data will be written at the current position.
See the POSIX
pwrite(2)
documentation for details.
encoding
utf8
Returns a
Promise
which is resolved with an object
containing two properties:
bytesWritten
integer
representing the number of bytes written
buffer
Buffer
,
TypedArray
, or
DataView
fs.Stats
The
fs.Stats
object provides information about a file.
The object is returned from
fs.statSync()
and
fs.lstatSync()
.
w+
— open a file for reading and writing.
If the file does not exist, it will be created.
If the file exists, it will be replaced
wx+
— the same as
w+
but fails if the file already exists
Query String
querystring.decode()
querystring.encode()
querystring.escape()
querystring.parse()
querystring.stringify()
querystring.unescape()
The Query String module provides support
for parsing and formatting URL query strings
(
0.4.3
).
The Query String module object is returned by
require('querystring')
.
querystring.decode()
querystring.parse()
.
querystring.encode()
querystring.stringify()
.
querystring.escape(
string
)
string
,
returns an escaped query string.
The method is used by
querystring.stringify()
and should not be used directly.
querystring.parse(
string
[,
separator
[,
equal
[,
options
]]])
separator
parameter is a substring
for delimiting key and value pairs in the query string,
by default is “
&
”.
The
equal
parameter is a substring
for delimiting keys and values in the query string,
by default is “
=
”.
The
options
parameter is expected to be
an object with the following keys:
decodeURIComponent
function
querystring.unescape()
maxKeys
number
1000
.
The
0
value removes limitations for counting keys.
By default, percent-encoded characters within the query string are assumed
to use the UTF-8 encoding,
invalid UTF-8 sequences will be replaced with
the
U+FFFD
replacement character.
For example, for the following query string
'foo=bar&abc=xyz&abc=123'
the output will be:
foo: 'bar',
abc: ['xyz', '123']
The
separator
parameter is a substring
for delimiting key and value pairs in the query string,
by default is “
&
”.
The
equal
parameter is a substring
for delimiting keys and values in the query string,
by default is “
=
”.
The
options
parameter is expected to be
an object with the following keys:
encodeURIComponent
function
querystring.escape()
.
By default, characters that require percent-encoding within the query string
are encoded as UTF-8.
If other encoding is required, then
encodeURIComponent
option should be specified.
For example, for the following command
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], 123: '' });
the query string will be:
'foo=bar&baz=qux&baz=quux&123='
Performs decoding of URL percent-encoded characters
of the
string
,
returns an unescaped query string.
The method is used by
querystring.parse()
and should not be used directly.
The XML module allows working with XML documents
(since
0.7.10
).
The XML module object is returned by
require('xml')
.
Example:
const xml = require("xml");
let data = `<note><to b="bar" a= "foo" >Tove</to><from>Jani</from></note>`;
let doc = xml.parse(data);
console.log(doc.note.to.$text) /* 'Tove' */
console.log(doc.note.to.$attr$b) /* 'bar' */
console.log(doc.note.$tags[1].$text) /* 'Jani' */
let dec = new TextDecoder();
let c14n = dec.decode(xml.exclusiveC14n(doc.note));
console.log(c14n) /* '<note><to a="foo" b="bar">Tove</to><from>Jani</from></note>' */
c14n = dec.decode(xml.exclusiveC14n(doc.note.to));
console.log(c14n) /* '<to a="foo" b="bar">Tove</to>' */
c14n = dec.decode(xml.exclusiveC14n(doc.note, doc.note.to /* excluding 'to' */));
console.log(c14n) /* '<note><from>Jani</from></note>' */
Canonicalizes
root_node
and its children according to
Canonical XML Version 1.1
.
The
root_node
can be
XMLNode
or
XMLDoc
wrapper object
around XML structure.
Returns Buffer object that contains canonicalized output.
allows omitting from the output a part of the document
corresponding to the node and its children
withComments
false
by default.
If
true
, canonicalization corresponds to
Exclusive XML
Canonicalization Version 1.0
.
Returns Buffer object that contains canonicalized output.
prefix_list
nd
is recursively copied before adding to the node
node.removeAllAttributes()
node.removeAttribute(
attr_name
)
attr_name
(since
0.7.11
)
node.removeChildren(
tag_name
)
tag_name
(since
0.7.11
).
If
tag_name
is absent, all children tags are removed
node.removeText()
node.setAttribute(
attr_name
,
value
)
attr_name
(since
0.7.11
).
When the value is
null
,
the attribute named
attr_name
is deleted
node.setText(
value
)
null
, the text of the node is deleted.
The zlib module provides compression functionality using the
“deflate” and “inflate” algorithms
(since
0.7.12
).
The zlib module object is returned by
require('zlib')
.
deflateRawSync(
string
|
Buffer
[,
options
])
Buffer
,
TypedArray
, or
DataView
.
Options
is an optional object that contains
zlib_options
.
Returns Buffer instance that contains the compressed data.
deflateSync(
string
|
Buffer
[,
options
])
Buffer
,
TypedArray
, or
DataView
.
Options
is an optional object that contains
zlib_options
.
Returns Buffer instance that contains the compressed data.
inflateRawSync(
string
|
Buffer
)
inflateSync(
string
|
Buffer
)
zlib options
chunkSize
— is an integer,
by default is
1024
dictionary
— is a
Buffer
,
TypedArray
, or
DataView
.
by default is empty
level
— is an integer, compression only,
see
zlib_compression_levels
memLevel
— is an integer
from
1
to
9
, compression only
strategy
— is an integer, compression only,
see
zlib_compression_strategy
windowBits
— is an integer
from
-15
to
-9
for raw data,
from
9
to
15
for an ordinary stream
zlib compression levels
NameDescription
zlib.constants.Z_NO_COMPRESSION
no compression
zlib.constants.Z_BEST_SPEED
fastest, produces the least compression
zlib.constants.Z_DEFAULT_COMPRESSION
trade-off between speed and compression
zlib.constants.Z_BEST_COMPRESSION
slowest, produces the most compression