WOW Node For Starter Programmer
WOW Node For Starter Programmer
js
About this documentation
Usage and example
Assertion testing
Async hooks
Buffer
C++ addons
C/C++ addons with Node-API
C++ embedder API
Child processes
Cluster
Command-line options
Console
Crypto
Debugger
Deprecated APIs
Diagnostics Channel
DNS
Domain
Errors
Events
File system
Globals
HTTP
HTTP/2
HTTPS
Inspector
Internationalization
Modules: CommonJS modules
Modules: ECMAScript modules
Modules: module API
Modules: Packages
Net
OS
Path
Performance hooks
Policies
Process
Punycode
Query strings
Readline
REPL
Report
Stream
String decoder
Timers
TLS/SSL
Trace events
TTY
UDP/datagram
URL
Utilities
V8
VM
WASI
Worker threads
Zlib
Table of contents
HTTP
Class: http.Agent
new Agent([options])
agent.createConnection(opti
ons[, callback])
agent.keepSocketAlive(socke
t)
agent.reuseSocket(socket,
request)
agent.destroy()
agent.freeSockets
agent.getName(options)
agent.maxFreeSockets
agent.maxSockets
agent.maxTotalSockets
agent.requests
agent.sockets
Class: http.ClientRequest
Event: 'abort'
Event: 'connect'
Event: 'continue'
Event: 'information'
Event: 'response'
Event: 'socket'
Event: 'timeout'
Event: 'upgrade'
request.abort()
request.aborted
request.connection
request.end([data[,
encoding]][, callback])
request.destroy([error])
request.destroyed
request.finished
request.flushHeaders()
request.getHeader(name)
request.getRawHeaderNames()
request.maxHeadersCount
request.path
request.method
request.host
request.protocol
request.removeHeader(name)
request.reusedSocket
request.setHeader(name,
value)
request.setNoDelay([noDelay
])
request.setSocketKeepAlive(
[enable][, initialDelay])
request.setTimeout(timeout[
, callback])
request.socket
request.writableEnded
request.writableFinished
request.write(chunk[,
encoding][, callback])
Class: http.Server
Event: 'checkContinue'
Event: 'checkExpectation'
Event: 'clientError'
Event: 'close'
Event: 'connect'
Event: 'connection'
Event: 'request'
Event: 'upgrade'
server.close([callback])
server.headersTimeout
server.listen()
server.listening
server.maxHeadersCount
server.requestTimeout
server.setTimeout([msecs][,
callback])
server.timeout
server.keepAliveTimeout
Class: http.ServerResponse
Event: 'close'
Event: 'finish'
response.addTrailers(header
s)
response.connection
response.cork()
response.end([data[,
encoding]][, callback])
response.finished
response.flushHeaders()
response.getHeader(name)
response.getHeaderNames()
response.getHeaders()
response.hasHeader(name)
response.headersSent
response.removeHeader(name)
response.sendDate
response.setHeader(name,
value)
response.setTimeout(msecs[,
callback])
response.socket
response.statusCode
response.statusMessage
response.uncork()
response.writableEnded
response.writableFinished
response.write(chunk[,
encoding][, callback])
response.writeContinue()
response.writeHead(statusCo
de[, statusMessage][,
headers])
response.writeProcessing()
Class: http.IncomingMessage
Event: 'aborted'
Event: 'close'
message.aborted
message.complete
message.destroy([error])
message.headers
message.httpVersion
message.method
message.rawHeaders
message.rawTrailers
message.setTimeout(msecs[,
callback])
message.socket
message.statusCode
message.statusMessage
message.trailers
message.url
Class: http.OutgoingMessage
Event: drain
Event: finish
Event: prefinish
outgoingMessage.addTrailers
(headers)
outgoingMessage.connection
outgoingMessage.cork()
outgoingMessage.destroy([er
ror])
outgoingMessage.end(chunk[,
encoding][, callback])
outgoingMessage.flushHeader
s()
outgoingMessage.getHeader(n
ame)
outgoingMessage.getHeaderNa
mes()
outgoingMessage.getHeaders(
)
outgoingMessage.hasHeader(n
ame)
outgoingMessage.headersSent
outgoingMessage.pipe()
outgoingMessage.removeHeade
r()
outgoingMessage.setHeader(n
ame, value)
outgoingMessage.setTimeout(
msesc[, callback])
outgoingMessage.socket
outgoingMessage.uncork()
outgoingMessage.writableCor
ked
outgoingMessage.writableEnd
ed
outgoingMessage.writableFin
ished
outgoingMessage.writableHig
hWaterMark
outgoingMessage.writableLen
gth
outgoingMessage.writableObj
ectMode
outgoingMessage.write(chunk
[, encoding][, callback])
http.METHODS
http.STATUS_CODES
http.createServer([options][,
requestListener])
http.get(options[, callback])
http.get(url[, options][,
callback])
http.globalAgent
http.maxHeaderSize
http.request(options[, callback])
http.request(url[, options][,
callback])
http.validateHeaderName(name)
http.validateHeaderValue(name,
value)
HTTP#
Stability: 2 - Stable
Source Code: lib/http.js
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'host': 'mysite.com',
'accept': '*/*' }
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'mysite.com',
'accepT', '*/*' ]
Class: http.Agent#
Sockets are removed from an agent when the socket emits either
a 'close' event or an 'agentRemove' event. When intending to keep one HTTP
request open for a long time without keeping it in the agent, something like
the following may be done:
agent:false:
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
new Agent([options])#
History
options <Object> Set of configurable
options to set on the agent. Can have
the following fields:
o keepAlive <boolean> Keep sockets
around even when there are no
outstanding requests, so they can
be used for future requests
without having to reestablish a
TCP connection. Not to be
confused with the keep-alive value
of the Connection header.
The Connection: keep-alive header
is always sent when using an
agent except when
the Connection header is explicitly
specified or when
the keepAlive and maxSockets optio
ns are respectively set
to false and Infinity, in which
case Connection: close will be
used. Default: false.
o keepAliveMsecs <number> When
using the keepAlive option,
specifies the initial delay for TCP
Keep-Alive packets. Ignored when
the keepAlive option
is false or undefined. Default: 1000.
o maxSockets <number> Maximum
number of sockets to allow per
host. If the same host opens
multiple concurrent connections,
each request will use new socket
until the maxSockets value is
reached. If the host attempts to
open more connections
than maxSockets, the additional
requests will enter into a pending
request queue, and will enter
active connection state when an
existing connection terminates.
This makes sure there are at
most maxSockets active
connections at any point in time,
from a given
host. Default: Infinity.
o maxTotalSockets <number> Maximu
m number of sockets allowed for
all hosts in total. Each request will
use a new socket until the
maximum is
reached. Default: Infinity.
o maxFreeSockets <number> Maximum
number of sockets to leave open
in a free state. Only relevant
if keepAlive is set
to true. Default: 256.
o scheduling <string> Scheduling
strategy to apply when picking the
next free socket to use. It can
be 'fifo' or 'lifo'. The main
difference between the two
scheduling strategies is
that 'lifo' selects the most
recently used socket,
while 'fifo' selects the least
recently used socket. In case of a
low rate of request per second,
the 'lifo' scheduling will lower
the risk of picking a socket that
might have been closed by the
server due to inactivity. In case of
a high rate of request per second,
the 'fifo' scheduling will
maximize the number of open
sockets, while
the 'lifo' scheduling will keep it
as low as possible. Default: 'lifo'.
o timeout <number> Socket timeout in
milliseconds. This will set the
timeout when the socket is
created.
agent.createConnection(options[, callback])#
options <Object> Options containing
connection details.
Check net.createConnection() for the
format of the options
callback <Function> Callback function
that receives the created socket
Returns: <stream.Duplex>
agent.keepSocketAlive(socket)#
socket <stream.Duplex>
socket.setKeepAlive(true, this.keepAliveMsecs);
socket.unref();
return true;
agent.reuseSocket(socket, request)#
socket <stream.Duplex>
request <http.ClientRequest>
socket.ref();
agent.freeSockets#
<Object>
agent.getName(options)#
agent.maxFreeSockets#
<number>
agent.maxSockets#
<number>
agent.maxTotalSockets#
<number>
agent.requests#
<Object>
An object which contains queues of requests that have not yet been assigned
to sockets. Do not modify.
agent.sockets#
<Object>
Class: http.ClientRequest#
Extends: <Stream>
Node.js does not check whether Content-Length and the length of the body
which has been transmitted are equal or not.
Event: 'abort'#
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort().
Event: 'connect'#
response <http.IncomingMessage>
socket <stream.Duplex>
head <Buffer>
Event: 'continue'#
Emitted when the server sends a '100 Continue' HTTP response, usually
because the request contained 'Expect: 100-continue'. This is an instruction
that the client should send the request body.
Event: 'information'#
info <Object>
o httpVersion <string>
o httpVersionMajor <integer>
o httpVersionMinor <integer>
o statusCode <integer>
o statusMessage <string>
o headers <Object>
o rawHeaders <string[]>
Emitted when the server sends a 1xx intermediate response (excluding 101
Upgrade). The listeners of this event will receive an object containing the
HTTP version, status code, status message, key-value headers object, and
array with the raw header names followed by their respective values.
const options = {
host: '127.0.0.1',
port: 8080,
path: '/length_request'
};
// Make a request
const req = http.request(options);
req.end();
101 Upgrade statuses do not fire this event due to their break from the
traditional HTTP request/response chain, such as web sockets, in-place TLS
upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for
the 'upgrade' event instead.
Event: 'response'#
response <http.IncomingMessage>
Event: 'socket'#
Added in: v0.5.3
socket <stream.Duplex>
Event: 'timeout'#
Emitted when the underlying socket times out from inactivity. This only
notifies that the socket has been idle. The request must be aborted
manually.
See also: request.setTimeout().
Event: 'upgrade'#
response <http.IncomingMessage>
socket <stream.Duplex>
head <Buffer>
// make a request
const options = {
port: 1337,
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
request.abort()#
Marks the request as aborting. Calling this will cause remaining data in the
response to be dropped and the socket to be destroyed.
request.aborted#
History
<boolean>
request.connection#
Added in: v0.3.0Deprecated since: v13.0.0
Stability: 0 - Deprecated. Use request.socket.
<stream.Duplex>
See request.socket.
History
data <string> | <Buffer>
encoding <string>
callback <Function>
Returns: <this>
Finishes sending the request. If any parts of the body are unsent, it will flush
them to the stream. If the request is chunked, this will send the
terminating '0\r\n\r\n'.
request.destroy([error])#
History
request.destroyed#
Added in: v14.1.0
<boolean>
request.finished#
<boolean>
request.flushHeaders()#
That's usually desired (it saves a TCP round-trip), but not when the first data
is not sent until possibly much later. request.flushHeaders() bypasses the
optimization and kickstarts the request.
request.getHeader(name)#
name <string>
Returns: <any>
Reads out a header on the request. The name is case-insensitive. The type of
the return value depends on the arguments provided to request.setHeader().
request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type');
// 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length');
// 'contentLength' is of type number
const cookie = request.getHeader('Cookie');
// 'cookie' is of type string[]
request.getRawHeaderNames()#
Returns: <string[]>
Returns an array containing the unique names of the current outgoing raw
headers. Header names are returned with their exact casing being set.
request.setHeader('Foo', 'bar');
request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
request.maxHeadersCount#
<number> Default: 2000
request.path#
request.method#
request.host#
request.protocol#
request.removeHeader(name)#
name <string>
request.removeHeader('Content-Type');
request.reusedSocket#
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
By marking a request whether it reused socket or not, we can do automatic
error retry base on it.
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();
request.setHeader(name, value)#
name <string>
value <any>
Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, request.getHeader() may return non-
string values. However, the non-string values will be converted to strings for
network transmission.
request.setHeader('Content-Type', 'application/json');
or
request.setNoDelay([noDelay])#
noDelay <boolean>
Once a socket is assigned to this request and is
connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable][, initialDelay])#
enable <boolean>
initialDelay <number>
request.setTimeout(timeout[, callback])#
History
timeout <number> Milliseconds before a
request times out.
callback <Function> Optional function to
be called when a timeout occurs. Same
as binding to the 'timeout' event.
Returns: <http.ClientRequest>
request.socket#
<stream.Duplex>
Reference to the underlying socket. Usually users will not want to access this
property. In particular, the socket will not emit 'readable' events because of
how the protocol parser attaches to the socket.
request.writableEnded#
<boolean>
request.writableFinished#
<boolean>
Is true if all data has been flushed to the underlying system, immediately
before the 'finish' event is emitted.
chunk <string> | <Buffer>
encoding <string>
callback <Function>
Returns: <boolean>
Sends a chunk of the body. By calling this method many times, a request
body can be sent to a server. In that case, it is suggested to use
the ['Transfer-Encoding', 'chunked'] header line when creating the request.
The encoding argument is optional and only applies when chunk is a string.
Defaults to 'utf8'.
Returns true if the entire data was flushed successfully to the kernel buffer.
Returns false if all or part of the data was queued in user
memory. 'drain' will be emitted when the buffer is free again.
Class: http.Server#
Extends: <net.Server>
Event: 'checkContinue'#
request <http.IncomingMessage>
response <http.ServerResponse>
Event: 'checkExpectation'#
Event: 'clientError'#
History
exception <Error>
socket <stream.Duplex>
Default behavior is to try close the socket with a HTTP '400 Bad Request', or
a HTTP '431 Request Header Fields Too Large' in the case of
a HPE_HEADER_OVERFLOW error. If the socket is not writable or has already
written data it is immediately destroyed.
In some cases, the client has already received the response and/or the
socket has already been destroyed, like in case of ECONNRESET errors. Before
trying to send data to the socket, it is better to check that it is still writable.
Event: 'close'#
Event: 'connect'#
request <http.IncomingMessage> Argumen
ts for the HTTP request, as it is in
the 'request' event
socket <stream.Duplex> Network socket
between the server and client
head <Buffer> The first packet of the
tunneling stream (may be empty)
Emitted each time a client requests an HTTP CONNECT method. If this event is
not listened for, then clients requesting a CONNECT method will have their
connections closed.
After this event is emitted, the request's socket will not have a 'data' event
listener, meaning it will need to be bound in order to handle data sent to the
server on that socket.
Event: 'connection'#
socket <stream.Duplex>
This event can also be explicitly emitted by users to inject connections into
the HTTP server. In that case, any Duplex stream can be passed.
Event: 'request'#
request <http.IncomingMessage>
response <http.ServerResponse>
Emitted each time there is a request. There may be multiple requests per
connection (in the case of HTTP Keep-Alive connections).
Event: 'upgrade'#
History
request <http.IncomingMessage> Argumen
ts for the HTTP request, as it is in
the 'request' event
socket <stream.Duplex> Network socket
between the server and client
head <Buffer> The first packet of the
upgraded stream (may be empty)
Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.
After this event is emitted, the request's socket will not have a 'data' event
listener, meaning it will need to be bound in order to handle data sent to the
server on that socket.
server.close([callback])#
callback <Function>
server.headersTimeout#
<number> Default: 60000
Limit the amount of time the parser will wait to receive the complete HTTP
headers.
server.listen()#
Starts the HTTP server listening for connections. This method is identical
to server.listen() from net.Server.
server.listening#
server.maxHeadersCount#
<number> Default: 2000
server.requestTimeout#
<number> Default: 0
Sets the timeout value in milliseconds for receiving the entire request from
the client.
If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the
connection.
server.setTimeout([msecs][, callback])#
History
Sets the timeout value for sockets, and emits a 'timeout' event on the Server
object, passing the socket as an argument, if a timeout occurs.
server.timeout#
History
<number> Timeout in
milliseconds. Default: 0 (no timeout)
The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.
server.keepAliveTimeout#
<number> Timeout in
milliseconds. Default: 5000 (5 seconds).
The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.
Class: http.ServerResponse#
Extends: <Stream>
Event: 'close'#
Event: 'finish'#
response.addTrailers(headers)#
headers <Object>
This method adds HTTP trailing headers (a header but at the end of the
message) to the response.
response.connection#
<stream.Duplex>
See response.socket.
response.cork()#
See writable.cork().
response.end([data[, encoding]][, callback])#
History
data <string> | <Buffer>
encoding <string>
callback <Function>
Returns: <this>
This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete. The
method, response.end(), MUST be called on each response.
response.finished#
<boolean>
response.flushHeaders()#
response.getHeader(name)#
name <string>
Returns: <any>
Reads out a header that's already been queued but not sent to the client. The
name is case-insensitive. The type of the return value depends on the
arguments provided to response.setHeader().
response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]
response.getHeaderNames()#
Returns: <string[]>
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
response.getHeaders()#
Returns: <Object>
Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are
the header names and the values are the respective header values. All header
names are lowercase.
response.hasHeader(name)#
name <string>
Returns: <boolean>
response.headersSent#
<boolean>
response.removeHeader(name)#
name <string>
response.removeHeader('Content-Encoding');
response.sendDate#
<boolean>
When true, the Date header will be automatically generated and sent in the
response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date header in
responses.
response.setHeader(name, value)#
name <string>
value <any>
Returns: <http.ServerResponse>
Sets a single header value for implicit headers. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, response.getHeader() may return
non-string values. However, the non-string values will be converted to
strings for network transmission. The same response object is returned to
the caller, to enable call chaining.
response.setHeader('Content-Type', 'text/html');
or
response.setTimeout(msecs[, callback])#
msecs <number>
callback <Function>
Returns: <http.ServerResponse>
response.socket#
<stream.Duplex>
Reference to the underlying socket. Usually users will not want to access this
property. In particular, the socket will not emit 'readable' events because of
how the protocol parser attaches to the socket. After response.end(), the
property is nulled.
<number> Default: 200
response.statusCode = 404;
After response header was sent to the client, this property indicates the
status code which was sent out.
response.statusMessage#
<string>
After response header was sent to the client, this property indicates the
status message which was sent out.
response.uncork()#
See writable.uncork().
response.writableEnded#
<boolean>
Is true after response.end() has been called. This property does not indicate
whether the data has been flushed, for this
use response.writableFinished instead.
response.writableFinished#
<boolean>
Is true if all data has been flushed to the underlying system, immediately
before the 'finish' event is emitted.
chunk <string> | <Buffer>
encoding <string> Default: 'utf8'
callback <Function>
Returns: <boolean>
This sends a chunk of the response body. This method may be called
multiple times to provide successive parts of the body.
This is the raw HTTP body and has nothing to do with higher-level multi-
part body encodings that may be used.
Returns true if the entire data was flushed successfully to the kernel buffer.
Returns false if all or part of the data was queued in user
memory. 'drain' will be emitted when the buffer is free again.
response.writeContinue()#
Sends a HTTP/1.1 100 Continue message to the client, indicating that the
request body should be sent. See the 'checkContinue' event on Server.
History
statusCode <number>
statusMessage <string>
headers <Object> | <Array>
Returns: <http.ServerResponse>
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404. The last argument, headers, are the response headers.
Optionally one can give a human-readable statusMessage as the second
argument.
headers may be an Array where the keys and values are in the same list. It
is not a list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values. The array is in the same
format as request.rawHeaders.
response.writeProcessing()#
Sends a HTTP/1.1 102 Processing message to the client, indicating that the
request body should be sent.
Class: http.IncomingMessage#
History
Extends: <stream.Readable>
An IncomingMessage object is created
by http.Server or http.ClientRequest and passed as the first argument to
the 'request' and 'response' event respectively. It may be used to access
response status, headers and data.
Event: 'aborted'#
Event: 'close'#
message.aborted#
<boolean>
message.complete#
<boolean>
message.destroy([error])#
History
error <Error>
Returns: <this>
message.headers#
<Object>
Key-value pairs of header names and values. Header names are lower-cased.
Duplicates
of age, authorization, content-length, con
tent-type, etag, expires, from, host, if-
modified-since, if-unmodified-since, last
-modified, location, max-forwards, proxy-
authorization, referer, retry-after, serv
er, or user-agent are discarded.
set-cookie is always an array. Duplicates
are added to the array.
For duplicate cookie headers, the values
are joined together with '; '.
For all other headers, the values are
joined together with ', '.
message.httpVersion#
<string>
In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server. Probably
either '1.1' or '1.0'.
message.method#
<string>
message.rawHeaders#
<string[]>
Header names are not lowercased, and duplicates are not merged.
message.rawTrailers#
<string[]>
The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end' event.
message.setTimeout(msecs[, callback])#
msecs <number>
callback <Function>
Returns: <http.IncomingMessage>
Calls message.socket.setTimeout(msecs, callback).
message.socket#
<stream.Duplex>
message.statusCode#
<number>
message.statusMessage#
<string>
message.trailers#
<Object>
message.url#
<string>
When request.url is '/status?name=ryan' and request.headers.host is 'localho
st:3000':
$ node
> new URL(request.url, `http://${request.headers.host}`)
URL {
href: 'http://localhost:3000/status?name=ryan',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
Class: http.OutgoingMessage#
Extends: <Stream>
Event: drain#
Event: finish#
Added in: v0.1.17
Event: prefinish#
outgoingMessage.addTrailers(headers)#
headers <Object>
Adds HTTP trailers (headers but at the end of the message) to the message.
outgoingMessage.connection#
Aliases of outgoingMessage.socket
outgoingMessage.cork()#
Added in: v14.0.0
See writable.cork().
outgoingMessage.destroy([error])#
Destroys the message. Once a socket is associated with the message and is
connected, that socket will be destroyed as well.
History
chunk <string> | <Buffer>
encoding <string> Optional, Default: utf-
8
callback <Function> Optional
Returns: <this>
Finishes the outgoing message. If any parts of the body are unsent, it will
flush them to the underlying system. If the message is chunked, it will send
the terminating chunk 0\r\n\r\n, and send the trailer (if any).
outgoingMessage.flushHeaders()#
It is usually desired (it saves a TCP round-trip), but not when the first data is
not sent until possibly much later. outgoingMessage.flushHeaders() bypasses
the optimization and kickstarts the request.
outgoingMessage.getHeader(name)#
name <string> Name of header
Returns <string> | <undefined>
Gets the value of HTTP header with the given name. If such a name doesn't
exist in message, it will be undefined.
outgoingMessage.getHeaderNames()#
Returns <string[]>
outgoingMessage.getHeaders()#
Returns: <Object>
Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related HTTP module methods. The keys of the returned object are
the header names and the values are the respective header values. All header
names are lowercase.
outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
outgoingMessage.hasHeader(name)#
name <string>
Returns <boolean>
outgoingMessage.headersSent#
<boolean>
outgoingMessage.pipe()#
outgoingMessage.removeHeader()#
outgoingMessage.removeHeader('Content-Encoding');
outgoingMessage.setHeader(name, value)#
name <string> Header name
value <string> Header value
Returns: <this>
outgoingMessage.setTimeout(msesc[, callback])#
msesc <number>
callback <Function> Optional function to
be called when a timeout
Returns: <this>
outgoingMessage.socket#
<stream.Duplex>
Reference to the underlying socket. Usually, users will not want to access
this property.
outgoingMessage.uncork()#
Added in: v14.0.0
See writable.uncork()
outgoingMessage.writableCorked#
<number>
outgoingMessage.writableEnded#
<boolean>
outgoingMessage.writableFinished#
<boolean>
outgoingMessage.writableHighWaterMark#
<number>
This outgoingMessage.writableHighWaterMark will be the highWaterMark of
underlying socket if socket exists. Else, it would be the default highWaterMark.
<number>
outgoingMessage.writableObjectMode#
<boolean>
History
chunk <string> | <Buffer>
encoding <string> Default: utf-8
callback <Function>
Returns <boolean>
If it is the first call to this method of a message, it will send the buffered
header first, then flush the chunk as described above.
The second and successive calls to this method will assume the data will be
streamed and send the new data separately. It means that the response is
buffered up to the first chunk of the body.
Returns true if the entire data was flushed successfully to the kernel buffer.
Returns false if all or part of the data was queued in the user memory.
Event drain will be emitted when the buffer is free again.
http.METHODS#
<string[]>
http.STATUS_CODES#
<Object>
A collection of all the standard HTTP response status codes, and the short
description of each. For example, http.STATUS_CODES[404] === 'Not Found'.
http.createServer([options][, requestListener]) #
History
options <Object>
o IncomingMessage <http.IncomingMess
age> Specifies
the IncomingMessage class to be
used. Useful for extending the
original IncomingMessage. Default: I
ncomingMessage.
o ServerResponse <http.ServerRespons
e> Specifies
the ServerResponse class to be
used. Useful for extending the
original ServerResponse. Default: Se
rverResponse.
o insecureHTTPParser <boolean> Use
an insecure HTTP parser that
accepts invalid HTTP headers
when true. Using the insecure
parser should be avoided. See --
insecure-http-parser for more
information. Default: false
o maxHeaderSize <number> Optionally
overrides the value of --max-http-
header-size for requests received
by this server, i.e. the maximum
length of request headers in
bytes. Default: 16384 (16KB).
requestListener <Function>
Returns: <http.Server>
http.get(options[, callback])#
History
url <string> | <URL>
options <Object> Accepts the
same options as http.request(), with
the method always set to GET. Properties
that are inherited from the prototype are
ignored.
callback <Function>
Returns: <http.ClientRequest>
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method
and http.request() is that it sets the method to GET and
calls req.end() automatically. The callback must take care to consume the
response data for reasons stated in http.ClientRequest section.
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!'
}));
});
server.listen(8000);
http.globalAgent#
<http.Agent>
Global instance of Agent which is used as the default for all HTTP client
requests.
http.maxHeaderSize#
<number>
http.request(options[, callback])#
History
url <string> | <URL>
options <Object>
o agent <http.Agent> | <boolean> Con
trols Agent behavior. Possible
values:
undefined (default):
use http.globalAgent for this
host and port.
Agent object: explicitly use
the passed in Agent.
false: causes a
new Agent with default
values to be used.
o auth <string> Basic authentication
i.e. 'user:password' to compute an
Authorization header.
o createConnection <Function> A
function that produces a
socket/stream to use for the
request when the agent option is
not used. This can be used to
avoid creating a
custom Agent class just to override
the
default createConnection function.
See agent.createConnection() for
more details. Any Duplex stream is
a valid return value.
o defaultPort <number> Default port
for the
protocol. Default: agent.defaultPor
t if an Agent is used,
else undefined.
o family <number> IP address family
to use when
resolving host or hostname. Valid
values are 4 or 6. When
unspecified, both IP v4 and v6 will
be used.
o headers <Object> An object
containing request headers.
o hints <number> Optional dns.looku
p() hints.
o host <string> A domain name or IP
address of the server to issue the
request to. Default: 'localhost'.
o hostname <string> Alias for host. To
support url.parse(), hostname will
be used if
both host and hostname are
specified.
o insecureHTTPParser <boolean> Use
an insecure HTTP parser that
accepts invalid HTTP headers
when true. Using the insecure
parser should be avoided. See --
insecure-http-parser for more
information. Default: false
o localAddress <string> Local
interface to bind for network
connections.
o localPort <number> Local port to
connect from.
o lookup <Function> Custom lookup
function. Default: dns.lookup().
o maxHeaderSize <number> Optionally
overrides the value of --max-http-
header-size for requests received
from the server, i.e. the maximum
length of response headers in
bytes. Default: 16384 (16KB).
o method <string> A string specifying
the HTTP request
method. Default: 'GET'.
o path <string> Request path.
Should include query string if any.
E.G. '/index.html?page=12'. An
exception is thrown when the
request path contains illegal
characters. Currently, only spaces
are rejected but that may change
in the future. Default: '/'.
o port <number> Port of remote
server. Default: defaultPort if set,
else 80.
o protocol <string> Protocol to
use. Default: 'http:'.
o setHost <boolean>: Specifies
whether or not to automatically
add the Host header. Defaults
to true.
o socketPath <string> Unix Domain
Socket (cannot be used if one
of host or port is specified, those
specify a TCP Socket).
o timeout <number>: A number
specifying the socket timeout in
milliseconds. This will set the
timeout before the socket is
connected.
o signal <AbortSignal>: An
AbortSignal that may be used to
abort an ongoing request.
callback <Function>
Returns: <http.ClientRequest>
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on
the returned request object. As with all 'error' events, if no listeners are
registered the error will be thrown.
There are a few special headers that should be noted.
'socket'
'response'
o 'data' any number of times, on
the res object ('data' will not be
emitted at all if the response body
is empty, for instance, in most
redirects)
o 'end' on the res object
'close'
'socket'
'error' with an error with
message 'Error: socket hang up' and
code 'ECONNRESET'
'close'
'socket'
'response'
o 'data' any number of times, on
the res object
(connection closed here)
'aborted' on the res object
'close'
'close' on the res object
(req.destroy() called here)
'error' with an error with
message 'Error: socket hang up' and
code 'ECONNRESET'
'close'
'socket'
(req.destroy() called here)
'error' with an error with
message 'Error: socket hang up' and
code 'ECONNRESET'
'close'
'socket'
'response'
o 'data' any number of times, on
the res object
(req.destroy() called here)
'aborted' on the res object
'close'
'close' on the res object
(req.abort() called here)
'abort'
'close'
'socket'
(req.abort() called here)
'abort'
'error' with an error with
message 'Error: socket hang up' and
code 'ECONNRESET'
'close'
'socket'
'response'
o 'data' any number of times, on
the res object
(req.abort() called here)
'abort'
'aborted' on the res object
'close'
'close' on the res object
http.validateHeaderName(name)#
name <string>
Example:
try {
validateHeaderName('');
} catch (err) {
err instanceof TypeError; // --> true
err.code; // --> 'ERR_INVALID_HTTP_TOKEN'
err.message; // --> 'Header name must be a valid HTTP token [""]'
}
http.validateHeaderValue(name, value)#
name <string>
value <any>
Examples:
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
err instanceof TypeError; // --> true
err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
err instanceof TypeError; // --> true
err.code === 'ERR_INVALID_CHAR'; // --> true
err.message; // --> 'Invalid character in header content ["x-my-header"]'
}