Reference
nginx objects HTTP Request Stream Session Response ngx built-in objects crypto njs process String web API Text Decoder Text Encoder timers built-in modules Buffer Crypto File System Query String |
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
The HTTP request object is available only in the ngx_http_js_module module. All string properties of the object are byte strings.
r.args{}
- request arguments object, read-only
r.done()
- after calling this function, next data chunks will be passed to client without calling js_body_filter (0.5.2). May be called only from the js_body_filter function
r.error(
string
)-
writes a
string
to the error log on theerror
level of logging r.finish()
- finishes sending a response to the client
r.headersIn{}
-
incoming headers object, read-only.
The
Foo
request header can be accessed with the syntax:headersIn.foo
orheadersIn['Foo']
.The “Authorization”, “Content-Length”, “Content-Range”, “Content-Type”, “ETag”, “Expect”, “From”, “Host”, “If-Match”, “If-Modified-Since”, “If-None-Match”, “If-Range”, “If-Unmodified-Since”, “Max-Forwards”, “Proxy-Authorization”, “Referer”, “Transfer-Encoding”, and “User-Agent” request headers can have only one field value (0.4.1). Duplicate field values in “Cookie” headers are separated by semicolon (
;
). Duplicate field values in all other request headers are separated by commas. r.headersOut{}
-
outgoing headers object, writable.
The “Foo” response header can be accessed with the syntax:
headersOut.foo
orheadersOut['Foo']
.Field values of multi-value response headers (0.4.0) can be set with the syntax:
r.headersOut['Foo'] = ['a', 'b']
where the output will be:
Foo: a Foo: b
All previous field values of the “Foo” response header will be deleted.
For standard response headers that accept only a single field value such as “Content-Type”, only the last element of the array will take effect. Field values of the “Set-Cookie” response header are always returned as an array. Duplicate field values in “Age”, “Content-Encoding”, “Content-Length”, “Content-Type”, “ETag”, “Expires”, “Last-Modified”, “Location”, “Retry-After” response headers are ignored. Duplicate field values in all other response headers are separated by commas.
r.httpVersion
- HTTP version, read-only
r.internalRedirect(
uri
)-
performs an
internal
redirect
to the specified
uri
. If the uri starts with the “@
” prefix, it is considered a named location. Redirected requests become internal and can access the internal locations. The actual redirect happens after the handler execution is completed.After redirect, a new njs VM is started in the target location, the VM in the original location is stopped. Values of nginx variables are kept and can be used to pass information to the target location. Since 0.5.3, the variable declared with the
js_var
directive for http or stream can be used. r.log(
string
)-
writes a
string
to the error log on theinfo
level of logging r.method
- HTTP method, read-only
r.parent
- references the parent request object
r.remoteAddress
- client address, read-only
r.requestBody
-
the property is deprecated since
0.5.0,
the
r.requestBuffer
orr.requestText
property should be used instead. r.requestBuffer
- client request body if it has not been written to a temporary file (since 0.5.0). To ensure that the client request body is in memory, its size should be limited by 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
-
the same as
r.requestBuffer
, but returns astring
. Note that it may convert bytes invalid in UTF-8 encoding into the replacement character. r.rawHeadersIn{}
-
returns an array of key-value pairs
exactly as they were received from the client
(0.4.1).
For example, with the following request headers:
Host: localhost Foo: bar foo: bar2
the output of
r.rawHeadersIn
will be:[ ['Host', 'localhost'], ['Foo', 'bar'], ['foo', 'bar2'] ]
All
foo
headers can be collected with the syntax:r.rawHeadersIn.filter(v=>v[0].toLowerCase() == 'foo').map(v=>v[1])
the output will be:
['bar', 'bar2']
Header field names are not converted to lower case, duplicate field values are not merged.
r.rawHeadersOut{}
- returns an array of key-value pairs of response headers (0.4.1). Header field names are not converted to lower case, duplicate field values are not merged.
r.responseBody
-
the property is deprecated since
0.5.0,
the
r.responseBuffer
or ther.responseText
property should be used instead. r.responseBuffer
-
holds the subrequest response body,
read-only
(since 0.5.0).
The size of
r.responseBuffer
is limited by the subrequest_output_buffer_size directive. r.responseText
-
the same as
r.responseBuffer
but returns a string (since 0.5.0). Note that it may convert bytes invalid in UTF-8 encoding into the replacement character. r.return(status[, string | Buffer])
-
sends the entire response
with the specified
status
to the client. The response can be a string or Buffer (0.5.0).It is possible to specify either a redirect URL (for codes 301, 302, 303, 307, and 308) or the response body text (for other codes) as the second argument
r.send(string | Buffer)
- sends a part of the response body to the client. The data sent can be a string or Buffer (0.5.0)
r.sendBuffer(
data
[,options
])-
adds data to the chain of data chunks to be forwarded to the next body filter
(0.5.2).
The actual forwarding happens later,
when the all the data chunks of the current chain are processed.
The data can be a string or Buffer. The
options
is an object used to override nginx buffer flags derived from an incoming data chunk buffer. The flags can be overridden with the following flags:last
- boolean, true if the buffer is the last buffer
flush
-
boolean,
true if the buffer should have the
flush
flag
r.sendHeader()
- sends the HTTP headers to the client
r.setReturnValue(
value
)-
sets the return value of the
js_set handler
(0.7.0).
Unlike an ordinary return statement,
this method should be used when the handler is JS async function.
For example:
async function js_set(r) { const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host); r.setReturnValue(digest); }
r.status
- status, writable
r.subrequest(
uri
[,options
[,callback
]])-
creates a subrequest with the given
uri
andoptions
, and installs an optional completioncallback
.A subrequest shares its input headers with the client request. To send headers different from original headers to a proxied server, the proxy_set_header directive can be used. To send a completely new set of headers to a proxied server, the proxy_pass_request_headers directive can be used.
If
options
is a string, then it holds the subrequest arguments string. Otherwise,options
is expected to be an object with the following keys:args
- arguments string, by default an empty string is used
body
- request body, by default the request body of the parent request object is used
method
-
HTTP method, by default the
GET
method is used detached
-
boolean flag (0.3.9),
if
true
, the created subrequest is a detached subrequest. Responses to detached subrequests are ignored. Unlike ordinary subrequests, a detached subrequest can be created inside a variable handler. Thedetached
flag and callback argument are mutually exclusive.
The completion
callback
receives a subrequest response object with methods and properties identical to the parent request object.Since 0.3.8, if a
callback
is not provided, thePromise
object that resolves to the subrequest response object is returned. r.uri
- current URI in request, normalized, read-only
r.rawVariables{}
- nginx variables as Buffers, writable (since 0.5.0)
r.variables{}
-
nginx variables object, writable
(since 0.2.8).
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_
). -
it was created using the
r.warn(
string
)-
writes a
string
to the error log on thewarning
level of logging
Stream Session
The stream session object is available only in the ngx_stream_js_module module. All string properties of the object are byte strings.
s.allow()
-
an alias to
s.done(0)
(0.2.4) s.decline()
-
an alias to
s.done(-5)
(0.2.4) s.deny()
-
an alias to
s.done(403)
(0.2.4) s.done([
)code
]-
sets an exit
code
for the current phase handler to a code value, by default0
. The actual finalization happens when the js handler is completed and all pending events, for example, fromngx.fetch()
orsetTimeout()
, are processed (0.2.4).Possible code values:
-
0
— successful finalization, passing control to the next phase -
-5
— undecided, passing control to the next handler of the current phase (if any) -
403
— access is forbidden
js_access
orjs_preread
. -
s.error(
string
)-
writes a sent
string
to the error log on theerror
level of logging s.log(
string
)-
writes a sent
string
to the error log on theinfo
level of logging s.off(
eventName
)- unregisters the callback set by the s.on() method (0.2.4)
s.on(
event
,callback
)-
registers a
callback
for the specifiedevent
(0.2.4).An
event
may be one of the following strings:upload
- new data (string) from a client
download
- new data (string) to a client
upstream
- new data (Buffer) from a client (since 0.5.0)
downstream
- new data (Buffer) to a client (since 0.5.0)
The completion callback has the following prototype:
callback(data, flags)
, wheredata
is string or Buffer (depending on the event type)flags
is an object with the following properties:last
- a boolean value, true if data is a last buffer.
s.remoteAddress
- client address, read-only
s.rawVariables
- nginx variables as Buffers, writable (since 0.5.0)
s.send(
data
[,options
])-
adds data to the chain of data chunks that will be forwarded in
the forward direction:
in download callback to a client; in upload to an upstream server
(0.2.4).
The actual forwarding happens later,
when the all the data chunks of the current chain are processed.
The data can be a string or Buffer (0.5.0). The
options
is an object used to override nginx buffer flags derived from an incoming data chunk buffer. The flags can be overridden with the following flags:last
- boolean, true if the buffer is the last buffer
flush
-
boolean,
true if the buffer should have the
flush
flag
s.status
-
session status code, an alias to the
$status
variable, read only (since 0.5.2) s.setReturnValue(
value
)-
sets the return value of the
js_set handler
(0.7.0).
Unlike an ordinary return statement,
this method should be used when the handler is JS async function.
For example:
async function js_set(r) { const digest = await crypto.subtle.digest('SHA-256', r.headersIn.host); r.setReturnValue(digest); }
s.variables{}
- nginx variables object, writable (since 0.2.8). A variable can be writable only if it is referenced in nginx configuration file. Even so, some embedded variables still cannot be assigned a value.
s.warn(
string
)-
writes a sent
string
to the error log on thewarning
level of logging
Response
The Response
interface is available since
0.5.1.
arrayBuffer()
-
Takes a
Response
stream and reads it to completion. Returns aPromise
that resolves with anArrayBuffer
. bodyUsed
-
A boolean value,
true
if the body was read. headers
-
The
Headers
read-only object associated with theResponse
:get(
name
)- returns a string containing the values of all headers with the specified name separated by a comma and a space
getAll(
name
)- returns an array containing the values of all headers with the specified name
has(
name
)- returns a boolean value indicating whether a header with the specified name exists
json()
-
Takes a
Response
stream and reads it to completion. Returns aPromise
that resolves with the result of parsing the body text as JSON. ok
-
A boolean value,
true
if the response was successful (status codes between 200–299). redirected
-
A boolean value,
true
if the response is the result of a redirect. status
- The status code of the response.
statusText
- The status message corresponding to the status code.
text()
-
Takes a
Response
stream and reads it to completion. Returns aPromise
that resolves with a string. type
- The type of the response.
url
- The URL of the response.
ngx
The ngx
global object is available
since 0.5.0.
ngx.fetch(
url
, [options
])-
Makes a request to fetch an URL
(0.5.1),
returns a
Promise
that resolves with theResponse
object. Since 0.7.0, thehttps://
scheme is supported, redirects are not handled.The
options
parameter is expected to be an object with the following keys:body
- request body, by default is empty
buffer_size
-
the buffer size for reading the response,
by default is
4096
headers
- request headers object
max_response_body_size
-
the maximum size of the response body in bytes,
by default is
32768
method
-
HTTP method,
by default the
GET
method is used verify
-
enables or disables verification of the HTTPS server certificate,
by default is
true
(0.7.0)
Example:
ngx.fetch('http://nginx.org/') .then(reply => reply.text()) .then(body => r.return(200, body)) .catch(e => r.return(501, e.message))
ngx.log
(level
,message
)-
Writes a message to the error log with the specified level of logging.
The
level
parameter specifies one of the log levels, themessage
parameter can be a string or Buffer. The following log levels can be specified:ngx.INFO
,ngx.WARN
, andngx.ERR
.
built-in objects
crypto
The crypto
object is a global object
that allows using cryptographic functionality
(since 0.7.0).
сrypto.getRandomValues
(typedArray
)-
Gets cryptographically strong random values.
Returns the same array passed as
typedArray
but with its contents replaced with the newly generated random numbers. Possible values:typedArray
-
can be
Int8Array
,Int16Array
,Uint16Array
,Int32Array
, orUint32Array
сrypto.subtle.encrypt
(algorithm
,key
,data
)-
Encrypts
data
using the providedalgorithm
andkey
. Returns aPromise
that fulfills with anArrayBuffer
containing the ciphertext. Possible values:algorithm
-
an object that specifies
the algorithm to be used and any extra parameters if required:
-
for
RSA-OAEP
, pass the object with the following keys:-
name
is a string, should be set toRSA-OAEP
:crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
-
-
for
AES-CTR
, pass the object with the following keys:-
name
is a string, should be set toAES-CTR
-
counter
is anArrayBuffer
,TypedArray
, orDataView
— the initial value of the counter block, must be 16 bytes long (the AES block size). The rightmost length bits of this block are used for the counter, and the rest is used for the nonce. For example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter -
length
is the number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap.
-
-
for
AES-CBC
, pass the object with the following keys:-
name
is a string, should be set toAES-CBC
-
iv
or the initialization vector, is anArrayBuffer
,TypedArray
, orDataView
, must be 16 bytes, unpredictable, and preferably cryptographically random. However, it need not be secret, for example, it may be transmitted unencrypted along with the ciphertext.
-
-
for
AES-GCM
, pass the object with the following keys:-
name
is a string, should be set toAES-GCM
-
iv
or the initialization vector, is anArrayBuffer
,TypedArray
, orDataView
, must be 16 bytes, and must be unique for every encryption operation carried out with a given key -
additionalData
(optional) is anArrayBuffer
,TypedArray
, orDataView
that contains additional data that will not be encrypted but will be authenticated along with the encrypted data. IfadditionalData
is specified, then the same data must be specified in the corresponding call todecrypt()
: if the data given to thedecrypt()
call does not match the original data, the decryption will throw an exception. The bit length ofadditionalData
must be smaller than2^64 - 1
. -
tagLength
(optional, default is128
) - anumber
that determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption Possible values:32
,64
,96
,104
,112
,120
, or128
. The AES-GCM specification recommends that it should be96
,104
,112
,120
, or128
, although32
or64
bits may be acceptable in some applications.
-
-
for
key
-
a
CryptoKey
that contains the key to be used for encryption data
-
an
ArrayBuffer
,TypedArray
, orDataView
that contains the data to be encrypted (also known as the plaintext)
сrypto.subtle.decrypt
(algorithm
,key
,data
)-
Decrypts encrypted data.
Returns a
Promise
with the decrypted data. Possible values:algorithm
-
an object
that specifies the algorithm to be used, and any extra parameters as required.
The values given for the extra parameters must match
those passed into the corresponding
encrypt()
call.-
for
RSA-OAEP
, pass the object with the following keys:-
name
is a string, should be set toRSA-OAEP
:crypto.subtle.encrypt({name: "RSA-OAEP"}, key, data)
-
-
for
AES-CTR
, pass the object with the following keys:-
name
is a string, should be set toAES-CTR
-
counter
is anArrayBuffer
,TypedArray
, orDataView
— the initial value of the counter block, must be 16 bytes long (the AES block size). The rightmost length bits of this block are used for the counter, and the rest is used for the nonce. For example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter. -
length
is the number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap.
-
-
for
AES-CBC
, pass the object with the following keys:-
name
is a string, should be set toAES-CBC
-
iv
or the initialization vector, is anArrayBuffer
,TypedArray
, orDataView
, must be 16 bytes, unpredictable, and preferably cryptographically random. However, it need not be secret (for example, it may be transmitted unencrypted along with the ciphertext).
-
-
for
AES-GCM
, pass the object with the following keys:-
name
is a string, should be set toAES-GCM
-
iv
or the initialization vector, is anArrayBuffer
,TypedArray
, orDataView
, must be 16 bytes, and must be unique for every encryption operation carried out with a given key -
additionalData
(optional) is anArrayBuffer
,TypedArray
, orDataView
that contains additional data that will not be encrypted but will be authenticated along with the encrypted data. IfadditionalData
is specified, then the same data must be specified in the corresponding call todecrypt()
: if the data given to thedecrypt()
call does not match the original data, the decryption will throw an exception. The bit length ofadditionalData
must be smaller than2^64 - 1
. -
tagLength
(optional, default is128
) - anumber
that determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption. Possible values:32
,64
,96
,104
,112
,120
, or128
. The AES-GCM specification recommends that it should be96
,104
,112
,120
, or128
, although32
or64
bits may be acceptable in some applications.
-
-
for
key
-
a
CryptoKey
that contains the key to be used for decryption. IfRSA-OAEP
is used, this is theprivateKey
property of theCryptoKeyPair
object. data
-
an
ArrayBuffer
,TypedArray
, orDataView
that contains the data to be decrypted (also known as ciphertext)
сrypto.subtle.deriveBits
(algorithm
,baseKey
,length
)-
Derives an array of bits from a base key.
Returns a
Promise
which will be fulfilled with anArrayBuffer
that contains the derived bits. Possible values:algorithm
-
is an object that defines the derivation algorithm to use:
-
for
HKDF
, pass the object with the following keys:-
name
is a string, should be set toHKDF
-
hash
is a string with the digest algorithm to use:SHA-1
,SHA-256
,SHA-384
, orSHA-512
-
salt
is anArrayBuffer
,TypedArray
, orDataView
that represents random or pseudo-random value with the same length as the output of thedigest
function. Unlike the input key material passed intoderiveKey()
, salt does not need to be kept secret. -
info
is anArrayBuffer
,TypedArray
, orDataView
that represents application-specific contextual information used to bind the derived key to an application or context, and enables deriving different keys for different contexts while using the same input key material. This property is required but may be an empty buffer.
-
-
for
PBKDF2
, pass the object with the following keys:-
name
is a string, should be set toPBKDF2
-
hash
is a string with the digest algorithm to use:SHA-1
,SHA-256
,SHA-384
, orSHA-512
-
salt
is anArrayBuffer
,TypedArray
, orDataView
that represents random or pseudo-random value of at least16
bytes. Unlike the input key material passed intoderiveKey()
, salt does not need to be kept secret. -
iterations
is anumber
that represents the number of times the hash function will be executed inderiveKey()
-
-
for
baseKey
-
is a
CryptoKey
that represents the input to the derivation algorithm - the initial key material for the derivation function: for example, forPBKDF2
it might be a password, imported as aCryptoKey
usingсrypto.subtle.importKey()
length
-
is a number representing the number of bits to derive.
For browsers compatibility,
the number should be a multiple of
8
сrypto.subtle.deriveKey
(algorithm
,baseKey
,derivedKeyAlgorithm
,extractable
,keyUsages
)-
Derives a secret key from a master key.
Possible values:
algorithm
-
is an object that defines the derivation algorithm to use:
-
for
HKDF
, pass the object with the following keys:-
name
is a string, should be set toHKDF
-
hash
is a string with the digest algorithm to use:SHA-1
,SHA-256
,SHA-384
, orSHA-512
-
salt
is anArrayBuffer
,TypedArray
, orDataView
that represents random or pseudo-random value with the same length as the output of thedigest
function. Unlike the input key material passed intoderiveKey()
, salt does not need to be kept secret. -
info
is anArrayBuffer
,TypedArray
, orDataView
that represents application-specific contextual information used to bind the derived key to an application or context, and enables deriving different keys for different contexts while using the same input key material. This property is required but may be an empty buffer.
-
-
for
PBKDF2
, pass the object with the following keys:-
name
is a string, should be set toPBKDF2
-
hash
is a string with the digest algorithm to use:SHA-1
,SHA-256
,SHA-384
, orSHA-512
-
salt
is anArrayBuffer
,TypedArray
, orDataView
that represents random or pseudo-random value of at least16
bytes. Unlike the input key material passed intoderiveKey()
, salt does not need to be kept secret. -
iterations
is anumber
that represents the number of times the hash function will be executed inderiveKey()
-
-
for
baseKey
-
is a
CryptoKey
that represents the input to the derivation algorithm - the initial key material for the derivation function: for example, forPBKDF2
it might be a password, imported as aCryptoKey
usingсrypto.subtle.importKey()
. derivedKeyAlgorithm
-
is an object
that defines the algorithm the derived key will be used for:
-
for
HMAC
, pass the object with the following keys:-
name
is a string, should be set toHMAC
-
hash
is a string with the name of the digest function to use:SHA-1
,SHA-256
,SHA-384
, orSHA-512
-
length
(optional) is anumber
that represents the length in bits of the key. If not specified, the length of the key is equal to the block size of the chozen hash function
-
-
for
AES-CTR
,AES-CBC
, orAES-GCM
, pass the object with the following keys:-
name
is a string, should be set toAES-CTR
,AES-CBC
, orAES-GCM
, depending on the algorithm used -
length
is anumber
that represents the length in bits of the key to generate:128
,192
, or256
-
-
for
extractable
- is a boolean value that indicates whether it will be possible to export the key
keyUsages
-
is an
Array
that indicates what can be done with the derived key. The key usages must be allowed by the algorithm set inderivedKeyAlgorithm
. Possible values:encrypt
- key for encrypting messages
decrypt
- key for decrypting messages
sign
- key for signing messages
verify
- key for verifying signatures
deriveKey
- key for deriving a new key
deriveBits
- key for deriving bits
wrapKey
- key for wrapping a key
unwrapKey
- key for unwrapping a key
сrypto.subtle.digest
(algorithm
,data
)-
Generates a digest of the given data.
Takes as its arguments an identifier for the digest algorithm to use
and the data to digest.
Returns a
Promise
which will be fulfilled with the digest. Possible values:algorithm
-
is a string that defines the hash function to use:
SHA-1
(not for cryptographic applications),SHA-256
,SHA-384
, orSHA-512
data
-
is an
ArrayBuffer
,TypedArray
, orDataView
that contains the data to be digested
сrypto.subtle.importKey
(format
,keyData
,algorithm
,extractable
,keyUsages
)-
Imports a key: takes as input a key in an external, portable format
and gives a
CryptoKey
object. Returns aPromise
that fulfills with the imported key as aCryptoKey
object. Possible values:format
-
a string that describes the data format of the key to import,
can be the following:
raw
- the raw data format
pkcs8
- the PKCS #8 format
spki
- the SubjectPublicKeyInfo format
keyData
-
the
ArrayBuffer
,TypedArray
, orDataView
object that contains the key in the given format algorithm
-
a dictionary object that defines the type of key to import
and provides extra algorithm-specific parameters:
-
for
RSASSA-PKCS1-v1_5
,RSA-PSS
, orRSA-OAEP
, pass the object with the following keys:-
name
is a string, should be set toRSASSA-PKCS1-v1_5
,RSA-PSS
, orRSA-OAEP
, depending on the used algorithm -
hash
is a string that represents the name of thedigest
function to use, can beSHA-256
,SHA-384
, orSHA-512
-
-
for
ECDSA
, pass the object with the following keys:-
name
is a string, should be set toECDSA
-
namedCurve
is a string that represents the name of the elliptic curve to use, may beP-256
,P-384
, orP-521
-
-
for
HMAC
, pass the object with the following keys:-
name
is a string, should be set toHMAC
-
hash
is a string that represents the name of thedigest
function to use, can beSHA-256
,SHA-384
, orSHA-512
-
length
(optional) is a number that represents the length in bits of the key. If omitted, the length of the key is equal to the length of the digest generated by the chosen digest function.
-
-
for
AES-CTR
,AES-CBC
, orAES-GCM
, pass the string identifying the algorithm or an object of the form{ "name": "ALGORITHM" }
, whereALGORITHM
is the name of the algorithm -
for
PBKDF2
, pass thePBKDF2
string -
for
HKDF
, pass theHKDF
string
-
for
extractable
- boolean value that indicates if it is possible to export the key
keyUsages
-
an
array
that indicates possible actions with the key:encrypt
- key for encrypting messages
decrypt
- key for decrypting messages
sign
- key for signing messages
verify
- key for verifying signatures
deriveKey
- key for deriving a new key
deriveBits
- key for deriving bits
wrapKey
- key for wrapping a key
unwrapKey
- key for unwrapping a key
сrypto.subtle.sign
(algorithm
,key
,data
)-
Returns
signature
as aPromise
that fulfills with anArrayBuffer
containing the signature. Possible values:algorithm
-
is a string or object that specifies the signature algorithm to use
and its parameters:
-
for
RSASSA-PKCS1-v1_5
, pass the string identifying the algorithm or an object of the form{ "name": "ALGORITHM" }
-
for
RSA-PSS
, pass the object with the following keys:-
name
is a string, should be set toRSA-PSS
-
saltLength
is a longinteger
that represents the length of the random salt to use, in bytes
-
-
for
ECDSA
, pass the object with the following keys:-
name
is a string, should be set toECDSA
-
hash
is an identifier for the digest algorithm to use, can beSHA-256
,SHA-384
, orSHA-512
-
-
for
HMAC
, pass the string identifying the algorithm or an object of the form{ "name": "ALGORITHM" }
-
for
key
-
is a
CryptoKey
object that the key to be used for signing. If algorithm identifies a public-key cryptosystem, this is the private key. data
-
is an
ArrayBuffer
,TypedArray
, orDataView
object that contains the data to be signed
сrypto.subtle.verify
(algorithm
,key
,signature
,data
)-
Verifies a digital signature,
returns a
Promise
that fulfills with a boolean value:true
if the signature is valid, otherwisefalse
. Possible values:algorithm
-
is a string or object that specifies the algorithm to use
and its parameters:
-
for
RSASSA-PKCS1-v1_5
, pass the string identifying the algorithm or an object of the form{ "name": "ALGORITHM" }
-
for
RSA-PSS
, pass the object with the following keys:-
name
is a string, should be set toRSA-PSS
-
saltLength
is a longinteger
that represents the length of the random salt to use, in bytes
-
-
for
ECDSA
, pass the object with the following keys:-
name
is a string, should be set toECDSA
-
hash
is an identifier for the digest algorithm to use, can beSHA-256
,SHA-384
, orSHA-512
-
-
for
HMAC
, pass the string identifying the algorithm or an object of the form{ "name": "ALGORITHM" }
-
for
key
-
is a
CryptoKey
object that the key to be used for verifying. It is the secret key for a symmetric algorithm and the public key for a public-key system. signature
-
is an
ArrayBuffer
,TypedArray
, orDataView
that contains the signature to verify data
-
is an
ArrayBuffer
,TypedArray
, orDataView
object that contains the data whose signature is to be verified
njs
The njs
object is a global object
that represents the current VM instance
(since 0.2.0).
njs.version
- Returns a string with the current version of njs (for example, “0.7.0”).
njs.dump(
value
)- Returns the pretty-print string representation for a value.
njs.on(
event
,callback
)-
Registers a callback for the specified VM event
(since 0.5.2).
An event may be one of the following strings:
exit
- is called before the VM is destroyed. The callback is called without arguments.
process
The process
object is a global object
that provides information about the current process
(0.3.3).
process.argv
- Returns an array that contains the command line arguments passed when the current process was launched.
process.env
-
Returns an object containing the user environment.
By default, nginx removes all environment variables inherited from its parent process except the TZ variable. Use the env directive to preserve some of the inherited variables.
process.pid
- Returns the PID of the current process.
process.ppid
- Returns the PID of the current parent process.
String
There are two types of strings in njs: a Unicode string (default) and a byte string.
A Unicode string corresponds to an ECMAScript string which contains Unicode characters.
Byte strings contain a sequence of bytes and are used to serialize Unicode strings to external data and deserialize from external sources. For example, the toUTF8() method serializes a Unicode string to a byte string using UTF-8 encoding:
>> '£'.toUTF8().toString('hex') 'c2a3' /* C2 A3 is the UTF-8 representation of 00A3 ('£') code point */
The toBytes() method serializes
a Unicode string with code points up to 255 into a byte string,
otherwise, null
is returned:
>> '£'.toBytes().toString('hex') 'a3' /* a3 is a byte equal to 00A3 ('£') code point */
String.bytesFrom(
array
|string
,encoding
)-
Creates a byte string either from an array that contains octets,
or from an encoded string
(0.2.3).
The encoding can be
hex
,base64
, andbase64url
. The method is deprecated since 0.4.4, theBuffer.from
method should be used instead:>> Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]).toString() 'buffer' >> Buffer.from('YnVmZmVy', 'base64').toString() 'buffer'
String.prototype.fromBytes(
start
[,end
])- Returns a new Unicode string from a byte string where each byte is replaced with a corresponding Unicode code point.
String.prototype.fromUTF8(
start
[,end
])-
Converts a byte string containing a valid UTF-8 string
into a Unicode string,
otherwise
null
is returned. String.prototype.toBytes(
start
[,end
])-
Serializes a Unicode string to a byte string.
Returns
null
if a character larger than 255 is found in the string. String.prototype.toString(
encoding
)-
Encodes a string to
hex
,base64
, orbase64url
:>> 'αβγδ'.toString('base64url') 'zrHOss6zzrQ'
Before version 0.4.3, only a byte string could be encoded:
>> 'αβγδ'.toUTF8().toString('base64url') 'zrHOss6zzrQ'
String.prototype.toUTF8(
start
[,end
])-
Serializes a Unicode string
to a byte string using UTF-8 encoding.
>> 'αβγδ'.toUTF8().length 8 >> 'αβγδ'.length 4
web API
Text Decoder
The TextDecoder
produces a stream of code points
from a stream of bytes
(0.4.3).
TextDecoder([[
encoding
],options
])-
Creates a new
TextDecoder
object for specifiedencoding
, currently, only UTF-8 is supported. Theoptions
isTextDecoderOptions
dictionary with the property:fatal
-
boolean flag indicating if
TextDecoder.decode()
must throw theTypeError
exception when a coding error is found, by default isfalse
.
TextDecoder.prototype.encoding
-
Returns a string with the name of the encoding used by
TextDecoder()
, read-only. TextDecoder.prototype.fatal
-
boolean flag,
true
if the error mode is fatal, read-only. TextDecoder.prototype.ignoreBOM
-
boolean flag,
true
if the byte order marker is ignored, read-only. TextDecoder.prototype.decode(
buffer
, [options
])-
Returns a string with the text
decoded from the
buffer
byTextDecoder()
. The buffer can beArrayBuffer
. Theoptions
isTextDecodeOptions
dictionary with the property:stream
-
boolean flag indicating if
additional data will follow in subsequent calls to
decode()
:true
if processing the data in chunks, andfalse
for the final chunk or if the data is not chunked. By default isfalse
.
>> (new TextDecoder()).decode(new Uint8Array([206,177,206,178])) αβ
Text Encoder
The TextEncoder
object
produces a byte stream with UTF-8 encoding
from a stream of code points
(0.4.3).
TextEncoder()
-
Returns a newly constructed
TextEncoder
that will generate a byte stream with UTF-8 encoding. TextEncoder.prototype.encode(
string
)-
Encodes
string
into aUint8Array
with UTF-8 encoded text. TextEncoder.prototype.encodeInto(
string
,uint8Array
)-
Encodes a
string
to UTF-8, puts the result into destinationUint8Array
, and returns a dictionary object that shows the progress of the encoding. The dictionary object contains two members:read
-
the number of UTF-16 units of code from the source
string
converted to UTF-8 written
-
the number of bytes modified in the destination
Uint8Array
timers
clearTimeout(
timeout
)-
Cancels a
timeout
object created bysetTimeout()
. setTimeout(
function
,milliseconds
[,argument1
,argumentN
])-
Calls a
function
after a specified number ofmilliseconds
. One or more optionalarguments
can be passed to the specified function. Returns atimeout
object.function handler(v) { // ... } t = setTimeout(handler, 12); // ... clearTimeout(t);
built-in modules
Buffer
Buffer.alloc(
size
[,fill
[,encoding
]]))-
Allocates a new Buffer of a specified
size
. Iffill
is not specified, the Buffer will be zero-filled. Iffill
is specified, the allocated Buffer will be initialized by callingbuf.fill(fill)
. Iffill
andencoding
are specified, the allocated Buffer will be initialized by callingbuf.fill(fill, encoding)
.The
fill
parameter may be astring
,Buffer
,Uint8Array
, orinteger
. Buffer.allocUnsafe(
size
)-
The same as
Buffer.alloc()
, with the difference that the memory allocated for the buffer is not initialized, the contents of the new buffer is unknown and may contain sensitive data. Buffer.byteLength(
value
[,encoding
])-
Returns the byte length of a specified value,
when encoded using
encoding
. The value can be astring
,Buffer
,TypedArray
,DataView
, orArrayBuffer
. If the value is astring
, theencoding
parameter is its encoding, can beutf8
,hex
,base64
,base64url
; by default isutf8
. Buffer.compare(
buffer1
,buffer2
)-
Compares
buffer1
withbuffer2
when sorting arrays of Buffer instances. Returns0
ifbuffer1
is the same asbuffer2
,1
ifbuffer2
should come beforebuffer1
when sorted, or-1
ifbuffer2
should come afterbuffer1
when sorted. Buffer.concat(
list
[,totalLength
])-
Returns a new Buffer
which is the result of concatenating all the Buffer instances in the list.
If there are no items in the list or the total length is 0,
a new zero-length Buffer is returned.
If
totalLength
is not specified, it is calculated from the Buffer instances in list by adding their lengths. IftotalLength
is specified, it is coerced to an unsigned integer. If the combined length of the Buffers in list exceedstotalLength
, the result is truncated tototalLength
. Buffer.from(
array
)-
Allocates a new Buffer using an array of bytes
in the range
0
–255
. Array entries outside that range will be truncated. Buffer.from(
arrayBuffer
,byteOffset
[,length
]])-
Creates a view of the
ArrayBuffer
without copying the underlying memory. The optionalbyteOffset
andlength
arguments specify a memory range within thearrayBuffer
that will be shared by the Buffer. Buffer.from(
buffer
)- Copies the passed buffer data onto a new Buffer instance.
Buffer.from(
object
[,offsetOrEncoding
[,length
]])-
For objects whose
valueOf()
function returns a value not strictly equal to object, returnsBuffer.from(object.valueOf()
,offsetOrEncoding
,length
). Buffer.from(
string
[,encoding
])-
Creates a new Buffer with a
string
. Theencoding
parameter identifies the character encoding to be used when converting a string into bytes. The encoding can beutf8
,hex
,base64
,base64url
; by default isutf8
. Buffer.isBuffer(
object
)-
A boolean value,
returns
true
ifobject
is a Buffer. Buffer.isEncoding(
encoding
)-
A boolean value,
returns
true
if encoding is the name of a supported character encoding. buffer[
index
]-
The index operator that can be used to get and set the octet
at position
index
inbuffer
. The values refer to individual bytes, so the legal value range is between 0 and 255 (decimal). buf.buffer
-
The underlying
ArrayBuffer
object based on which this Buffer object is created. buf.byteOffset
-
An integer,
specifying the
byteOffset
of the Buffers underlyingArrayBuffer
object. buf.compare(
target
[,targetStart
[,targetEnd
[,sourceStart
[,sourceEnd
]]]])-
Compares buffer with
target
and returns a number indicating whether buffer comes before, after, or is the same astarget
in sort order. Comparison is based on the actual sequence of bytes in each Buffer. ThetargetStart
is an integer specifying the offset withintarget
at which to begin comparison, by default is 0. ThetargetEnd
is an integer specifying the offset withintarget
at which to end comparison, by default istarget.length
. ThesourceStart
is an integer specifying the offset within buffer at which to begin comparison, by default is 0. ThesourceEnd
is an integer specifying the offset within buffer at which to end comparison (not inclusive), by default isbuf.length
. buf.copy(
target
[,targetStart
[,sourceStart
[,sourceEnd
]]])-
Copies data from a region of buffer to a region in
target
, even if the target memory region overlaps with buffer. Thetarget
parameter is aBuffer
orUint8Array
to copy into.The
targetStart
is an integer specifying the offset within target at which to begin writing, by default is 0. ThesourceStart
is an integer specifying the offset within buffer from which to begin copying, by default is 0. ThesourceEnd
is an integer specifying the offset within buffer at which to stop copying (not inclusive) by default isbuf.length
. buf.equals(
otherBuffer
)-
A boolean value,
returns
true
if both Buffer andotherBuffer
have exactly the same bytes. buf.fill(
value
[,offset
[,end
]][,encoding
])-
Fills the Buffer with the specified
value
. If theoffset
andend
are not specified, the entire Buffer will be filled. Thevalue
is coerced touint32
if it is not astring
,Buffer
, orinteger
. If the resulting integer is greater than 255, the Buffer will be filled withvalue
and 255. buf.includes(
value
[,byteOffset
][,encoding
])-
Equivalent to
buf.indexOf()
!== -1
, returnstrue
if thevalue
was found in Buffer. buf.indexOf(
value
[,byteOffset
][,encoding
])-
Returns an integer which is the index of the first occurrence of
value
in Buffer, or-1
if Buffer does not contain value. Thevalue
can be astring
with specifiedencoding
(by defaultutf8
),Buffer
,Unit8Array
, or a number between 0 and 255. buf.lastIndexOf(
value
[,byteOffset
][,encoding
])-
The same as
buf.indexOf()
, except the last occurrence of thevalue
is found instead of the first occurrence. Thevalue
can be a string, Buffer, or integer between 1 and 255. If thevalue
is an empty string or empty Buffer,byteOffset
will be returned. buf.length
- Returns the number of bytes in Buffer.
buf.readIntBE(
offset
,byteLength
)-
Reads the
byteLength
frombuf
at the specifiedoffset
and interprets the result as a big-endian, two's complement signed value supporting up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The similar methods are also supported:
buf.readInt8([offset])
,buf.readInt16BE([offset])
,buf.readInt32BE([offset])
. buf.readIntLE(
offset
,byteLength
)-
Reads the
byteLength
frombuf
at the specifiedoffset
and interprets the result as a little-endian, two's complement signed value supporting up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The similar methods are also supported:
buf.readInt8([offset])
,buf.readInt16LE([offset])
,buf.readInt32LE([offset])
. buf.readUIntBE(
offset
,byteLength
)-
Reads the
byteLength
frombuf
at the specifiedoffset
and interprets the result as a big-endian integer supporting up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The similar methods are also supported:
buf.readUInt8([offset])
,buf.readUInt16BE([offset])
,buf.readUInt32BE([offset])
. buf.readUIntLE(
offset
,byteLength
)-
Reads the
byteLength
frombuf
at the specifiedoffset
and interprets the result as a little-endian integer supporting up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The similar methods are also supported:
buf.readUInt8([offset])
,buf.readUInt16LE([offset])
,buf.readUInt32LE([offset])
. buf.readDoubleBE
([offset
])-
Reads a 64-bit, big-endian double from
buf
at the specifiedoffset
. buf.readDoubleLE
([offset
])-
Reads a 64-bit, little-endian double from
buf
at the specifiedoffset
. buf.readFloatBE
([offset
])-
Reads a 32-bit, big-endian float from
buf
at the specifiedoffset
. buf.readFloatLE
([offset
])-
Reads a 32-bit, little-endian float from
buf
at the specifiedoffset
. buf.subarray[
start
[,end
]])-
Returns a new
buf
that references the same memory as the original, but offset and cropped bystart
andend
. Ifend
is greater thanbuf.length
, the same result as that of end equal tobuf.length
is returned. buf.slice[
start
[,end
]])-
Returns a new
buf
that references the same memory as the original, but offset and cropped by thestart
andend
values. The method is not compatible with theUint8Array.prototype.slice()
, which is a superclass of Buffer. To copy the slice, useUint8Array.prototype.slice()
. buf.swap16
()-
Interprets
buf
as an array of unsigned 16-bit numbers and swaps the byte order in-place. Throws an error ifbuf.length
is not a multiple of 2. buf.swap32
()-
Interprets
buf
as an array of unsigned 32-bit numbers and swaps the byte order in-place. Throws an error ifbuf.length
is not a multiple of 4. buf.swap64
()-
Interprets
buf
as an array of 64-bit numbers and swaps byte order in-place. Throws an error ifbuf.length
is not a multiple of 8. buf.toJSON
()-
Returns a JSON representation of
buf.
JSON.stringify()
implicitly calls this function when stringifying a Buffer instance. buf.toString([
encoding
[,start
[,end
]]])-
Decodes
buf
to a string according to the specified characterencoding
which can beutf8
,hex
,base64
,base64url
. Thestart
andend
parameters may be passed to decode only a subset of Buffer. buf.write(
string
[,offset
[,length
]][,encoding
])-
Writes a
string
tobuf
atoffset
according to the characterencoding
. Thelength
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. Theencoding
can beutf8
,hex
,base64
,base64url
. buf.writeIntBE(
value
,offset
,byteLength
)-
Writes
byteLength
bytes ofvalue
tobuf
at the specifiedoffset
as big-endian. Supports up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The following similar methods are also supported:
buf.writeInt8
,buf.writeInt16BE
,buf.writeInt32BE
. buf.writeIntLE(
value
,offset
,byteLength
)-
Writes
byteLength
bytes ofvalue
tobuf
at the specifiedoffset
as little-endian. Supports up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The following similar methods are also supported:
buf.writeInt8
,buf.writeInt16LE
,buf.writeInt32LE
. buf.writeUIntBE(
value
,offset
,byteLength
)-
Writes
byteLength
bytes ofvalue
tobuf
at the specifiedoffset
as big-endian. Supports up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The following similar methods are also supported:
buf.writeUInt8
,buf.writeUInt16BE
,buf.writeUInt32BE
. buf.writeUIntLE(
value
,offset
,byteLength
)-
Writes
byteLength
bytes ofvalue
tobuf
at the specifiedoffset
as little-endian. Supports up to 48 bits of accuracy. ThebyteLength
parameter is an integer between 1 and 6 specifying the number of bytes to read.The following similar methods are also supported:
buf.writeUInt8
,buf.writeUInt16LE
,buf.writeUInt32LE
. buf.writeDoubleBE(
value
, [offset
])-
Writes the
value
tobuf
at the specifiedoffset
as big-endian. buf.writeDoubleLE(
value
, [offset
])-
Writes the
value
tobuf
at the specifiedoffset
as little-endian. buf.writeFloatBE(
value
, [offset
])-
Writes the
value
tobuf
at the specifiedoffset
as big-endian. buf.writeFloatLE(
value
, [offset
])-
Writes the
value
tobuf
at the specifiedoffset
as little-endian.
Crypto
Since 0.7.0, extended crypto API is available as a global crypto object.
The Crypto module provides cryptographic functionality support.
The Crypto module object is returned by require('crypto')
.
crypto.createHash(
algorithm
)-
Creates and returns a Hash object
that can be used to generate hash digests
using the given
algorithm
. The algorithm can bemd5
,sha1
, andsha256
. crypto.createHmac(
algorithm
,secret key
)-
Creates and returns an HMAC object that uses
the given
algorithm
andsecret key
. The algorithm can bemd5
,sha1
, andsha256
.
Hash
hash.update(
data
)-
Updates the hash content with the given
data
. hash.digest([
encoding
])-
Calculates the digest of all of the data passed using
hash.update()
. The encoding can behex
,base64
, andbase64url
. If encoding is not provided, a Buffer object (0.4.4) is returned.Before version (0.4.4), a byte string was returned instead of a Buffer object.
>> var cr = require('crypto') undefined >> cr.createHash('sha1').update('A').update('B').digest('base64url') 'BtlFlCqiamG-GMPiK_GbvKjdK10'
HMAC
hmac.update(
data
)-
Updates the HMAC content with the given
data
. hmac.digest([
encoding
])-
Calculates the HMAC digest of all of the data passed using
hmac.update()
. The encoding can behex
,base64
, andbase64url
. If encoding is not provided, a Buffer object (0.4.4) is returned.Before version 0.4.4, a byte string was returned instead of a Buffer object.
>> var cr = require('crypto') undefined >> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url') 'Oglm93xn23_MkiaEq_e9u8zk374'
File System
The File System module provides operations with files.
The module object is returned by require('fs')
.
Since 0.3.9,
promissified versions of file system methods are available through
require('fs').promises
object:
> var fs = require('fs').promises; undefined > fs.readFile("/file/path").then((data)=>console.log(data)) <file data>
accessSync(
path
[,mode
])-
Synchronously tests permissions for a file or directory
specified in the
path
(0.3.9). If the check fails, an error will be returned, otherwise, the method will return undefined.mode
-
by default is
fs.constants.F_OK
. The mode argument is an optional integer that specifies the accessibility checks to be performed.try { fs.accessSync('/file/path', fs.constants.R_OK | fs.constants.W_OK); console.log('has access'); } catch (e) { console.log('no access');) }
appendFileSync(
filename
,data
[,options
])-
Synchronously appends specified
data
to a file with providedfilename
. Thedata
is expected to be a string or a Buffer object (0.4.4). If the file does not exist, it will be created. Theoptions
parameter is expected to be an object with the following keys:mode
-
mode option, by default is
0o666
flag
-
file system flag,
by default is
a
lstatSync(
path
[,options
])-
Synchronously retrieves
the
fs.Stats
object for the symbolic link referred to bypath
(0.7.1). Theoptions
parameter is expected to be an object with the following keys:throwIfNoEntry
-
a boolean value which indicates
whether an exception is thrown if no file system entry exists,
rather than returning
undefined
, by default isfalse
.
mkdirSync(
path
[,options
])-
Synchronously creates a directory at the specified
path
(0.4.2). Theoptions
parameter is expected to be aninteger
that specifies the mode, or an object with the following keys:mode
-
mode option, by default is
0o777
.
readdirSync(
path
[,options
])-
Synchronously reads the contents of a directory
at the specified
path
(0.4.2). Theoptions
parameter is expected to be a string that specifies encoding or an object with the following keys: readFileSync(
filename
[,options
])-
Synchronously returns the contents of the file
with provided
filename
. Theoptions
parameter holdsstring
that specifies encoding. If an encoding is specified, a string is returned, otherwise, a Buffer object (0.4.4) is returned.Before version 0.4.4, a byte string was returned if encoding was not specified.
Otherwise,options
is expected to be an object with the following keys:encoding
-
encoding, by default is not specified.
The encoding can be
utf8
,hex
(0.4.4),base64
(0.4.4),base64url
(0.4.4). flag
-
file system flag,
by default is
r
>> var fs = require('fs') undefined >> var file = fs.readFileSync('/file/path.tar.gz') undefined >> var gzipped = file.slice(0,2).toString('hex') === '1f8b'; gzipped true
realpathSync(
path
[,options
])-
Synchronously computes the canonical pathname by resolving
.
,..
and symbolic links using realpath(3). Theoptions
argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback (0.3.9). renameSync(
oldPath
,newPath
)-
Synchronously changes the name or location of a file from
oldPath
tonewPath
(0.3.4).>> var fs = require('fs') undefined >> var file = fs.renameSync('hello.txt', 'HelloWorld.txt') undefined
rmdirSync(
path
)-
Synchronously removes a directory at the specified
path
(0.4.2). statSync(
path
,[options
])-
Synchronously retrieves
the
fs.Stats
object for the specifiedpath
(0.7.1). Thepath
can be astring
orbuffer
. Theoptions
parameter is expected to be an object with the following keys:throwIfNoEntry
-
a boolean value which indicates whether
an exception is thrown if no file system entry exists
rather than returning
undefined
, by default istrue
.
symlinkSync(
target
,path
)-
Synchronously creates the link called
path
pointing totarget
using symlink(2) (0.3.9). Relative targets are relative to the link’s parent directory. unlinkSync(
path
)-
Synchronously unlinks a file by
path
(0.3.9). writeFileSync(
filename
,data
[,options
])-
Synchronously writes
data
to a file with providedfilename
. Thedata
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. Theoptions
parameter is expected to be an object with the following keys:mode
-
mode option, by default is
0o666
flag
-
file system flag,
by default is
w
>> var fs = require('fs') undefined >> var file = fs.writeFileSync('hello.txt', 'Hello world') undefined
fs.Dirent
fs.Dirent
is a representation of a directory entry —
a file or a subdirectory.
When
readdirSync()
is called with the
withFileTypes
option,
the resulting array contains fs.Dirent
objects.
-
dirent.isBlockDevice()
— returnstrue
if thefs.Dirent
object describes a block device. -
dirent.isCharacterDevice()
— returnstrue
if thefs.Dirent
object describes a character device. -
dirent.isDirectory()
— returnstrue
if thefs.Dirent
object describes a file system directory. -
dirent.isFIFO()
— returnstrue
if thefs.Dirent
object describes a first-in-first-out (FIFO) pipe. -
dirent.isFile()
— returnstrue
if thefs.Dirent
object describes a regular file. -
dirent.isSocket()
— returnstrue
if thefs.Dirent
object describes a socket. -
dirent.isSymbolicLink()
— returnstrue
if thefs.Dirent
object describes a symbolic link. -
dirent.name
— the name of the filefs.Dirent
object refers to.
fs.Stats
The fs.Stats
object provides information about a file.
The object is returned from
fs.statSync() and
fs.lstatSync().
-
stats.isBlockDevice()
— returnstrue
if thefs.Stats
object describes a block device. -
stats.isDirectory()
— returnstrue
if thefs.Stats
object describes a file system directory. -
stats.isFIFO()
— returnstrue
if thefs.Stats
object describes a first-in-first-out (FIFO) pipe. -
stats.isFile()
— returnstrue
if thefs.Stats
object describes a regular file. -
stats.isSocket()
— returnstrue
if thefs.Stats
object describes a socket. -
stats.isSymbolicLink()
— returnstrue
if thefs.Stats
object describes a symbolic link. -
stats.dev
— the numeric identifier of the device containing the file. -
stats.ino
— the file system specificInode
number for the file. -
stats.mode
— a bit-field describing the file type and mode. -
stats.nlink
— the number of hard-links that exist for the file. -
stats.uid
— the numeric user identifier of the user that owns the file (POSIX). -
stats.gid
— the numeric group identifier of the group that owns the file (POSIX). -
stats.rdev
— the numeric device identifier if the file represents a device. -
stats.size
— the size of the file in bytes. -
stats.blksize
— the file system block size for i/o operations. -
stats.blocks
— the number of blocks allocated for this file. -
stats.atimeMs
— the timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch. -
stats.mtimeMs
— the timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch. -
stats.ctimeMs
— the timestamp indicating the last time this file was changed expressed in milliseconds since the POSIX Epoch. -
stats.birthtimeMs
— the timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch. -
stats.atime
— the timestamp indicating the last time this file was accessed. -
stats.mtime
— the timestamp indicating the last time this file was modified. -
stats.ctime
— the timestamp indicating the last time this file was changed. -
stats.birthtime
— the timestamp indicating the creation time of this file.
File Access Constants
The access()
method
can accept the following flags.
These flags are exported by fs.constants
:
-
F_OK
— indicates that the file is visible to the calling process, used by default if no mode is specified -
R_OK
— indicates that the file can be read by the calling process -
W_OK
— indicates that the file can be written by the calling process -
X_OK
— indicates that the file can be executed by the calling process
File System Flags
The flag
option can accept the following values:
-
a
— open a file for appending. The file is created if it does not exist -
ax
— the same asa
but fails if the file already exists -
a+
— open a file for reading and appending. If the file does not exist, it will be created -
ax+
— the same asa+
but fails if the file already exists -
as
— open a file for appending in synchronous mode. If the file does not exist, it will be created -
as+
— open a file for reading and appending in synchronous mode. If the file does not exist, it will be created -
r
— open a file for reading. An exception occurs if the file does not exist -
r+
— open a file for reading and writing. An exception occurs if the file does not exist -
rs+
— open a file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache -
w
— open a file for writing. If the file does not exist, it will be created. If the file exists, it will be replaced -
wx
— the same asw
but fails if the file already exists -
w+
— open a file for reading and writing. If the file does not exist, it will be created. If the file exists, it will be replaced -
wx+
— the same asw+
but fails if the file already exists
Query String
The Query String module provides support
for parsing and formatting URL query strings
(0.4.3).
The Query String module object is returned by
require('querystring')
.
querystring.decode()
-
is an alias for
querystring.parse()
. querystring.encode()
-
is an alias for
querystring.stringify()
. querystring.escape(
string
)-
Performs URL encoding of the given
string
, returns an escaped query string. The method is used byquerystring.stringify()
and should not be used directly. querystring.parse(
string
[,separator
[,equal
[,options
]]])-
Parses the query string URL and returns an object.
The
separator
parameter is a substring for delimiting key and value pairs in the query string, by default is “&
”.The
equal
parameter is a substring for delimiting keys and values in the query string, by default is “=
”.The
options
parameter is expected to be an object with the following keys:decodeURIComponent
function
-
Function used
to decode percent-encoded characters in the query string,
by default is
querystring.unescape()
maxKeys
number
-
the maximum number of keys to parse,
by default is
1000
. The0
value removes limitations for counting keys.
By default, percent-encoded characters within the query string are assumed to use the UTF-8 encoding, invalid UTF-8 sequences will be replaced with the
U+FFFD
replacement character.For example, for the following query string
'foo=bar&abc=xyz&abc=123'
the output will be:
{ foo: 'bar', abc: ['xyz', '123'] }
querystring.stringify(
object
[,separator
[,equal
[,options
]]])-
Serializes an object and returns a URL query string.
The
separator
parameter is a substring for delimiting key and value pairs in the query string, by default is “&
”.The
equal
parameter is a substring for delimiting keys and values in the query string, by default is “=
”.The
options
parameter is expected to be an object with the following keys:encodeURIComponent
function
-
The function to use when converting
URL-unsafe characters to percent-encoding in the query string,
by default is
querystring.escape()
.
By default, characters that require percent-encoding within the query string are encoded as UTF-8. If other encoding is required, then
encodeURIComponent
option should be specified.For example, for the following command
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], 123: '' });
the query string will be:
'foo=bar&baz=qux&baz=quux&123='
querystring.unescape(
string
)-
Performs decoding of URL percent-encoded characters of the
string
, returns an unescaped query string. The method is used byquerystring.parse()
and should not be used directly.