bare-http1
Native HTTP/1 library for JavaScript
v4.6.2bare-http1 — Native HTTP/1 library for JavaScript.
Mirrors the Node.js http module.
npm i bare-http1Usage
const http = require('bare-http1')
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Length', 10)
res.write('hello world!')
res.end()
})
server.listen(0, () => {
const { port } = server.address()
console.log('server is bound on', port)
const client = http.request({ port }, (res) => {
res.on('data', (data) => console.log(data.toString()))
})
client.end()
})API
constants
constants.HTTPMethod
type HTTPMethod = keyof typeof constants.methodA key of constants.method, that is one of the supported HTTP method names.
constants.HTTPStatusCode
type HTTPStatusCode = keyof typeof constants.status | (number & {})An HTTP status code. Any three digit code may be sent or received, so the codes named in
constants.status are only the ones that have a reason phrase of their own rather than the
whole of what is allowed.
constants.HTTPStatusMessage
type HTTPStatusMessage = (typeof constants.status)[keyof typeof constants.status] | (string & {})An HTTP reason phrase. Any field value may stand in for the reason phrase, so the phrases in
constants.status are only the ones a code is given by default rather than the whole of what
is allowed.
HTTPIncomingMessage
new HTTPIncomingMessage(socket?: TCPSocket, opts?: HTTPIncomingMessageOptions)
A readable stream representing an incoming HTTP request (on the server) or response (on the
client). Carries the parsed headers, method/url or statusCode/statusMessage, and the
underlying socket.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket? | TCPSocket | — | The socket the message is read from. |
opts? | HTTPIncomingMessageOptions | — | Initial values for headers, plus method and url (server side) or statusCode and statusMessage (client side). |
HTTPIncomingMessage._destroy(err: Error | null, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err | Error | null | — | — |
cb | StreamCallback | — | — |
HTTPIncomingMessage._open(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPIncomingMessage._predestroy(): void
_read(size: number): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
size | number | — | — |
HTTPIncomingMessage.closed: boolean
complete: boolean
Whether the whole of the message arrived, as against the peer having gone away part way through it. The stream closes either way, so this is what tells a consumer which of the two it was handed.
HTTPIncomingMessage.destroy(err?: Error | null): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err? | Error | null | — | — |
HTTPIncomingMessage.destroyed: boolean
HTTPIncomingMessage.destroying: boolean
HTTPIncomingMessage.errored: Error | null
getHeader(name: string): HTTPIncomingHeaderValue | undefined
Returns the value of header name (case-insensitive), or undefined if not set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
getHeaders(): Record<string, HTTPIncomingHeaderValue>
Returns a shallow copy of all headers.
HTTPIncomingMessage.hasHeader(name: string): boolean
Returns whether header name (case-insensitive) is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
headers: Record<string, HTTPIncomingHeaderValue>
The parsed headers, keyed by lowercase name. A field that appeared more than once and cannot be folded onto one line is given as a list.
httpVersion: HTTPVersion
The HTTP version the message arrived as.
HTTPIncomingMessage.method: HTTPMethod
The request method. Only meaningful on the server side.
pause(): this
pipe<S extends Writable>(dest: S, cb?: StreamCallback): S
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
dest | S | — | — |
cb? | StreamCallback | — | — |
push(data: unknown | null, encoding?: BufferEncoding): boolean
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | null | — | — |
encoding? | BufferEncoding | — | — |
read(): unknown | null
HTTPIncomingMessage.readable: boolean
resume(): this
setEncoding(encoding: BufferEncoding): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
encoding | BufferEncoding | — | — |
HTTPIncomingMessage.setTimeout(ms: number, ontimeout?: () => void): this
Sets the underlying socket's timeout to ms and, if given, adds ontimeout as a one-time
'timeout' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ms | number | — | The socket timeout in milliseconds. |
ontimeout? | () => void | — | Added as a one-time 'timeout' listener. |
HTTPIncomingMessage.socket: TCPSocket | null
The underlying TCPSocket the message was read from, or null once it has been given up.
HTTPIncomingMessage.statusCode: HTTPStatusCode
The response status code. Only meaningful on the client side.
statusMessage: HTTPStatusMessage
The response status reason phrase. Only meaningful on the client side.
unshift(data: unknown | null, encoding?: BufferEncoding): boolean
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | null | — | — |
encoding? | BufferEncoding | — | — |
HTTPIncomingMessage.upgrade: boolean
Whether the connection was upgraded (for example to a WebSocket) after this message.
url: string
The request URL path. Only meaningful on the server side.
HTTPIncomingMessage.writable: boolean
HTTPOutgoingMessage
new HTTPOutgoingMessage(socket?: TCPSocket)
A writable stream representing an outgoing HTTP request (on the client) or response (on the
server). Base class of HTTPClientRequest and HTTPServerResponse.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket? | TCPSocket | — | The socket the message is written to. |
HTTPOutgoingMessage._destroy(err: Error | null, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err | Error | null | — | — |
cb | StreamCallback | — | — |
HTTPOutgoingMessage._final(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPOutgoingMessage._open(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPOutgoingMessage._predestroy(): void
HTTPOutgoingMessage._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding | StreamEncoding | — | — |
cb | StreamCallback | — | — |
HTTPOutgoingMessage._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
batch | { chunk: unknown; encoding: StreamEncoding }[] | — | — |
cb | StreamCallback | — | — |
HTTPOutgoingMessage.appendHeader(name: string, value: HTTPHeaderValue): void
Adds value to header name (case-insensitive), keeping any value already set rather than
replacing it, so that the field is sent once per value. Cookie is the exception, whose values
are folded onto a single line separated by '; '.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__. |
value | HTTPHeaderValue | — | The header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_HEADER_NAME—nameis not a valid RFC 9110 token, or is__proto__.INVALID_HEADER_VALUE—valueisundefined, or contains a control character other than tab.
HTTPOutgoingMessage.closed: boolean
HTTPOutgoingMessage.cork(): void
HTTPOutgoingMessage.destroy(err?: Error | null): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err? | Error | null | — | — |
HTTPOutgoingMessage.destroyed: boolean
HTTPOutgoingMessage.destroying: boolean
HTTPOutgoingMessage.end(cb?: StreamCallback): this
Overloads:
end(cb?: StreamCallback): this
end(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): this
end(data: unknown, cb?: StreamCallback): thisParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb? | StreamCallback | — | — |
HTTPOutgoingMessage.errored: Error | null
HTTPOutgoingMessage.flushHeaders(): void
Sends the headers immediately, if they haven't already been sent, instead of waiting for the first write.
HTTPOutgoingMessage.getHeader(name: string): HTTPHeaderValue | undefined
Returns the value of header name (case-insensitive), or undefined if not set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPOutgoingMessage.getHeaders(): Record<string, HTTPHeaderValue>
Returns a shallow copy of all headers set so far.
HTTPOutgoingMessage.hasHeader(name: string): boolean
Returns whether header name (case-insensitive) is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPOutgoingMessage.headers: Record<string, HTTPHeaderValue>
The headers set so far, keyed by lowercase name. Assigning validates each header name and value.
HTTPOutgoingMessage.headersSent: boolean
Whether the headers have already been sent.
HTTPOutgoingMessage.readable: boolean
HTTPOutgoingMessage.setHeader(name: string, value: HTTPHeaderValue): void
Sets header name (case-insensitive) to value, replacing any value already set and
validating both.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 7230 token. |
value | HTTPHeaderValue | — | The header value; must not contain line-terminating characters. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_HEADER_NAME—nameis not a valid RFC 9110 token, or is__proto__.INVALID_HEADER_VALUE—valueisundefined, or contains a control character other than tab.
HTTPOutgoingMessage.setTimeout(ms: number, ontimeout?: () => void): this
Sets the underlying socket's timeout to ms and, if given, adds ontimeout as a one-time
'timeout' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ms | number | — | The socket timeout in milliseconds. |
ontimeout? | () => void | — | Added as a one-time 'timeout' listener. |
HTTPOutgoingMessage.socket: TCPSocket | null
The underlying TCPSocket the message is written to, or null until one is assigned.
HTTPOutgoingMessage.uncork(): void
HTTPOutgoingMessage.upgrade: boolean
Whether the connection was upgraded (for example to a WebSocket) after this message.
HTTPOutgoingMessage.writable: boolean
HTTPOutgoingMessage.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
Overloads:
write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
write(data: unknown, cb?: StreamCallback): booleanParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding? | BufferEncoding | — | — |
cb? | StreamCallback | — | — |
HTTPAgent
new HTTPAgent(opts?: HTTPAgentOptions & TCPSocketOptions & TCPSocketConnectOptions)
Manages a pool of TCPSocket connections shared across requests to the same origin, reusing
idle keep-alive sockets instead of opening a new connection per request.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPAgentOptions & TCPSocketOptions & TCPSocketConnectOptions | — | Agent options (keepAlive, keepAliveMsecs, defaultPort) plus TCP socket and connect options applied to each connection the agent creates. |
addRequest(req: HTTPClientRequest, opts: TCPSocketOptions & TCPSocketConnectOptions): void
Assigns a socket to req, reusing an idle keep-alive socket for the same origin if one is
available, creating a new one if there is room, and queueing the request until one comes free
otherwise.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
req | HTTPClientRequest | — | The request to assign a socket to. |
opts | TCPSocketOptions & TCPSocketConnectOptions | — | The socket and connection options, including the destination host and port. |
createConnection(opts?: TCPSocketOptions & TCPSocketConnectOptions): TCPSocket
Creates a new TCPSocket connection for a request. Throws if the agent is suspended.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | TCPSocketOptions & TCPSocketConnectOptions | — | The socket and connection options, including the destination host and port. |
Throws
AGENT_SUSPENDED— the agent is suspended.
defaultPort: number
The port used for a request that names none.
destroy(): void
Destroys all sockets currently held by the agent, both in-use and free.
freeSockets: IterableIterator<TCPSocket>
An iterator over the agent's idle, keep-alive sockets awaiting reuse.
getName(opts: TCPSocketConnectOptions): string
Returns the pool key used to group sockets by destination, derived from opts.host,
opts.port, opts.localAddress, opts.family, and opts.socketPath.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts | TCPSocketConnectOptions | — | The destination host and port to derive the pool key from. |
HTTPAgent.global: HTTPAgent
The agent's own default instance, used as bare-http1's globalAgent.
keepAlive: boolean
Whether the agent keeps sockets open for reuse once a request completes.
keepSocketAlive(socket: TCPSocket): boolean
Marks socket to be kept alive and unreferenced instead of closed once a request completes.
Returns whether the socket was kept alive.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket to keep alive for reuse. |
maxFreeSockets: number
How many sockets the agent may keep in its pool for a single origin once they are free.
maxSockets: number
How many sockets the agent may hold at once for a single origin.
maxTotalSockets: number
How many sockets the agent may hold at once across every origin it talks to.
resume(): void
Resumes an agent suspended with suspend(), allowing it to create connections again.
resumed: Promise<void> | null
A promise that resolves once a suspended agent is resumed, or null if the agent isn't
suspended.
reuseSocket(socket: TCPSocket, req?: HTTPClientRequest): void
Marks socket as back in active use, referencing it so it keeps the event loop alive.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket to mark as back in active use. |
req? | HTTPClientRequest | — | The request the socket is being reused for. |
sockets: IterableIterator<TCPSocket>
An iterator over all sockets currently held by the agent, both in-use and free.
suspend(): void
Suspends the agent, destroying all its sockets and preventing new connections until resume()
is called.
suspended: boolean
Whether the agent is currently suspended.
HTTPServer
HTTPServer
new HTTPServer(opts?: HTTPServerOptions, onrequest?: (req: HTTPIncomingMessage, res: HTTPServerResponse) => void)An HTTP/1.1 server, extending TCPServer. Emits 'request' with an HTTPIncomingMessage and
HTTPServerResponse for each request received.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPServerOptions | — | Options passed to each HTTPServerConnection, such as custom IncomingMessage and ServerResponse classes. |
onrequest? | (req: HTTPIncomingMessage, res: HTTPServerResponse) => void | — | Added as a listener for the 'request' event. |
addListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
addOnceListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
address(): TCPSocketAddress | null
Returns TCPSocketAddress | null — The bound address as { address, family, port }, or null if the server is not
listening.
close(onclose?: () => void): this
Close the server. No new connections will be accepted. The server emits close after all
existing connections have ended.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
onclose? | () => void | — | Called once when the server emits 'close', after all existing connections have ended. |
closeAllConnections(): void
Destroys every connection, in flight or not.
closeIdleConnections(): void
Destroys every connection that has no request in flight.
closing: boolean
Whether the server is closing.
connections: Set<TCPSocket>
A Set of active connections.
emit<E extends keyof M>(name: E, ...args: M[E]): boolean
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
args | M[E] | — | — |
eventNames(): (keyof M)[]
getMaxListeners(): number
headersTimeout: number
How long a connection may spend sending its request headers, in milliseconds, before it is
given up on. Defaults to 60000; zero disables it.
HTTPServer.keepAliveTimeout: number
How long a connection is kept once a request has been answered, in milliseconds, before it is
given up on. Defaults to 5000; zero disables it.
listen
listen(port?: number, host?: string, backlog?: number, opts?: TCPServerListenOptions, onlistening?: () => void): thisStart listening for connections on port and host. If port is 0, an available port is
assigned. If host is not provided, it defaults to 'localhost'. backlog defaults to 511.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
port? | number | — | The port to listen on; if 0 (the default), an available port is assigned. |
host? | string | — | The host to listen on; defaults to 'localhost'. |
backlog? | number | — | The maximum length of the queue of pending connections (default 511). |
opts? | TCPServerListenOptions | — | Listen options; the positional arguments may be given here instead, and lookup (default dns.lookup) resolves host when it is a hostname. |
onlistening? | () => void | — | Called once when the server emits 'listening'. |
Throws
SERVER_ALREADY_LISTENING— the server is already listening.SERVER_IS_CLOSED— the server has been closed.INVALID_PORT—portis not an integer between 0 and 65535.
listenerCount<E extends keyof M>(name: E): number
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
listeners<E extends keyof M>(name: E): EventHandler<M[E]>[]
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
listening: boolean
Whether the server is listening.
maxConnections: number
The maximum number of concurrent connections; connections beyond it are destroyed and reported
via the 'drop' event. Defaults to Infinity.
maxHeadersCount: number
The most headers a peer may send in a request. Defaults to 2000; zero disables it.
maxHeaderSize: number
The most a peer may send in a request line and headers before the request can be acted on.
Defaults to 16384; zero disables it.
maxUpgradeBodySize: number
The most of an upgrade request's body that may be held until the handover. Defaults to 65536;
zero disables it.
off<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
on<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
once<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
prependListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
prependOnceListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
rawListeners<E extends keyof M>(name: E): EventHandler<M[E]>[]
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
ref(): this
Ref the server, preventing the process from exiting.
removeAllListeners<E extends keyof M>(name?: E): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name? | E | — | — |
removeListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | E | — | — |
fn | EventHandler<M[E]> | — | — |
requestTimeout: number
How long a whole request may take, in milliseconds, before it is given up on. Defaults to
300000; zero disables it.
setMaxListeners(n: number): this
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
n | number | — | — |
HTTPServer.setTimeout(ms: number, ontimeout?: () => void): this
Sets the idle-socket timeout to ms (default 0, meaning no timeout) and, if given, adds
ontimeout as a 'timeout' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ms | number | — | The idle-socket timeout in milliseconds; 0 (the default) disables it. |
ontimeout? | () => void | — | Added as a 'timeout' listener. |
timeout: number
The idle-socket timeout in milliseconds. Defaults to 0, meaning no timeout.
unref(): this
Unref the server, allowing the process to exit.
HTTPServerResponse
HTTPServerResponse
new HTTPServerResponse(socket: TCPSocket, req: HTTPIncomingMessage, opts?: HTTPServerResponseOptions)An outgoing HTTP response, extending HTTPOutgoingMessage. Defaults to status 200 and
chunked transfer encoding unless a Content-Length header is set or the request was HTTP/1.0.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket the response is written to. |
req | HTTPIncomingMessage | — | The request this response answers. |
opts? | HTTPServerResponseOptions | — | The keepAliveTimeout to advertise to the peer. |
HTTPServerResponse._destroy(err: Error | null, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err | Error | null | — | — |
cb | StreamCallback | — | — |
HTTPServerResponse._final(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPServerResponse._open(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPServerResponse._predestroy(): void
HTTPServerResponse._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding | StreamEncoding | — | — |
cb | StreamCallback | — | — |
HTTPServerResponse._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
batch | { chunk: unknown; encoding: StreamEncoding }[] | — | — |
cb | StreamCallback | — | — |
HTTPServerResponse.appendHeader(name: string, value: HTTPHeaderValue): void
Adds value to header name (case-insensitive), keeping any value already set rather than
replacing it, so that the field is sent once per value. Cookie is the exception, whose values
are folded onto a single line separated by '; '.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__. |
value | HTTPHeaderValue | — | The header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_HEADER_NAME—nameis not a valid RFC 9110 token, or is__proto__.INVALID_HEADER_VALUE—valueisundefined, or contains a control character other than tab.
HTTPServerResponse.closed: boolean
HTTPServerResponse.cork(): void
HTTPServerResponse.destroy(err?: Error | null): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err? | Error | null | — | — |
HTTPServerResponse.destroyed: boolean
HTTPServerResponse.destroying: boolean
HTTPServerResponse.end(cb?: StreamCallback): this
Overloads:
end(cb?: StreamCallback): this
end(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): this
end(data: unknown, cb?: StreamCallback): thisParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb? | StreamCallback | — | — |
HTTPServerResponse.errored: Error | null
HTTPServerResponse.flushHeaders(): void
Sends the headers immediately, if they haven't already been sent, instead of waiting for the first write.
HTTPServerResponse.getHeader(name: string): HTTPHeaderValue | undefined
Returns the value of header name (case-insensitive), or undefined if not set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPServerResponse.getHeaders(): Record<string, HTTPHeaderValue>
Returns a shallow copy of all headers set so far.
HTTPServerResponse.hasHeader(name: string): boolean
Returns whether header name (case-insensitive) is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPServerResponse.headers: Record<string, HTTPHeaderValue>
The headers set so far, keyed by lowercase name. Assigning validates each header name and value.
HTTPServerResponse.headersSent: boolean
Whether the headers have already been sent.
HTTPServerResponse.readable: boolean
req: HTTPIncomingMessage
The HTTPIncomingMessage this response is answering.
HTTPServerResponse.setHeader(name: string, value: HTTPHeaderValue): void
Sets header name (case-insensitive) to value, replacing any value already set and
validating both.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__. |
value | HTTPHeaderValue | — | The header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_HEADER_NAME—nameis not a valid RFC 9110 token, or is__proto__.INVALID_HEADER_VALUE—valueisundefined, or contains a control character other than tab.
HTTPServerResponse.setTimeout(ms: number, ontimeout?: () => void): this
Sets the underlying socket's timeout to ms and, if given, adds ontimeout as a one-time
'timeout' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ms | number | — | The socket timeout in milliseconds. |
ontimeout? | () => void | — | Added as a one-time 'timeout' listener. |
HTTPServerResponse.socket: TCPSocket | null
The underlying TCPSocket the message is written to, or null until one is assigned.
HTTPServerResponse.statusCode: HTTPStatusCode
The response status code to send. Defaults to 200.
statusMessage: HTTPStatusMessage | null
The response status reason phrase to send, or null to use the standard phrase for
statusCode.
HTTPServerResponse.uncork(): void
HTTPServerResponse.upgrade: boolean
Whether the connection was upgraded (for example to a WebSocket) after this message.
HTTPServerResponse.writable: boolean
HTTPServerResponse.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
Overloads:
write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
write(data: unknown, cb?: StreamCallback): booleanParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding? | BufferEncoding | — | — |
cb? | StreamCallback | — | — |
writeContinue(): void
Sends a 100 Continue interim response, telling a client that announced Expect: 100-continue
to go ahead and send its body.
Throws
HEADERS_SENT— the headers have already been sent.
writeHead
writeHead(statusCode: HTTPStatusCode, statusMessage?: HTTPStatusMessage, headers?: HTTPHeaders): thisSets statusCode, and optionally statusMessage and additional headers, in one call.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
statusCode | HTTPStatusCode | — | The status code to send. |
statusMessage? | HTTPStatusMessage | — | The reason phrase to send; defaults to the standard phrase for statusCode. |
headers? | HTTPHeaders | — | Additional headers to merge into the response headers. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_STATUS_CODE—statusCodeis not a valid status code.INVALID_HEADER_NAME— a header name is not a valid token.INVALID_HEADER_VALUE—statusMessageor a header value contains an invalid character.
HTTPServerConnection
HTTPServerConnection
new HTTPServerConnection(server: HTTPServer, socket: TCPSocket, opts?: HTTPServerConnectionOptions)The per-socket state machine that parses incoming request data into
HTTPIncomingMessage/HTTPServerResponse pairs for an HTTPServer.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
server | HTTPServer | — | The server the connection belongs to. |
socket | TCPSocket | — | The connection socket. |
opts? | HTTPServerConnectionOptions | — | Custom IncomingMessage and ServerResponse classes to use for requests on the connection. |
HTTPServerConnection.for(socket: TCPSocket): HTTPServerConnection | null
Returns the HTTPServerConnection associated with socket, or null if none exists.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket to look up. |
HTTPServerConnection.idle: boolean
Whether the connection currently has no in-flight request.
req: HTTPIncomingMessage | null
The HTTPIncomingMessage currently being read on this connection, or null if none.
res: HTTPServerResponse | null
The HTTPServerResponse currently being written on this connection, or null if none.
server: HTTPServer
The HTTPServer this connection belongs to.
HTTPServerConnection.socket: TCPSocket | null
The underlying TCPSocket for this connection.
HTTPClientRequest
HTTPClientRequest
new HTTPClientRequest(opts?: HTTPClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void)An outgoing HTTP request, extending HTTPOutgoingMessage. Uses chunked transfer encoding
unless a Content-Length header is set or the method is GET/HEAD.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPClientRequestOptions | — | Request options; method defaults to 'GET', path to '/', host to 'localhost', and port to the agent's default port (80). Set agent to choose the pooling agent, or false for a fresh, unpooled one. |
onresponse? | (res: HTTPIncomingMessage) => void | — | Added as a one-time 'response' listener. |
Throws
INVALID_HEADER_NAME—methodor a header name is not a valid token.INVALID_HEADER_VALUE—hostis not a string, orpathor a header value contains an invalid character.
HTTPClientRequest._destroy(err: Error | null, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err | Error | null | — | — |
cb | StreamCallback | — | — |
HTTPClientRequest._final(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPClientRequest._open(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPClientRequest._predestroy(): void
HTTPClientRequest._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding | StreamEncoding | — | — |
cb | StreamCallback | — | — |
HTTPClientRequest._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
batch | { chunk: unknown; encoding: StreamEncoding }[] | — | — |
cb | StreamCallback | — | — |
abort(): void
Destroys the request. An alias of destroy(), for Node.js compatibility.
HTTPClientRequest.appendHeader(name: string, value: HTTPHeaderValue): void
Adds value to header name (case-insensitive), keeping any value already set rather than
replacing it, so that the field is sent once per value. Cookie is the exception, whose values
are folded onto a single line separated by '; '.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__. |
value | HTTPHeaderValue | — | The header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_HEADER_NAME—nameis not a valid RFC 9110 token, or is__proto__.INVALID_HEADER_VALUE—valueisundefined, or contains a control character other than tab.
HTTPClientRequest.closed: boolean
HTTPClientRequest.cork(): void
HTTPClientRequest.destroy(err?: Error | null): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err? | Error | null | — | — |
HTTPClientRequest.destroyed: boolean
HTTPClientRequest.destroying: boolean
HTTPClientRequest.end(cb?: StreamCallback): this
Overloads:
end(cb?: StreamCallback): this
end(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): this
end(data: unknown, cb?: StreamCallback): thisParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb? | StreamCallback | — | — |
HTTPClientRequest.errored: Error | null
HTTPClientRequest.flushHeaders(): void
Sends the headers immediately, if they haven't already been sent, instead of waiting for the first write.
HTTPClientRequest.getHeader(name: string): HTTPHeaderValue | undefined
Returns the value of header name (case-insensitive), or undefined if not set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPClientRequest.getHeaders(): Record<string, HTTPHeaderValue>
Returns a shallow copy of all headers set so far.
HTTPClientRequest.hasHeader(name: string): boolean
Returns whether header name (case-insensitive) is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPClientRequest.headers: Record<string, HTTPHeaderValue>
The headers to send with the request, keyed by lowercase name, including an auto-generated
host header.
HTTPClientRequest.headersSent: boolean
Whether the headers have already been sent.
HTTPClientRequest.method: HTTPMethod
The request method. Defaults to 'GET'.
path: string
The request path. Defaults to '/'.
HTTPClientRequest.readable: boolean
HTTPClientRequest.setHeader(name: string, value: HTTPHeaderValue): void
Sets header name (case-insensitive) to value, replacing any value already set and
validating both.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__. |
value | HTTPHeaderValue | — | The header value; must not contain a control character other than tab. Every element of an array value is checked in turn, and null is allowed. |
Throws
HEADERS_SENT— the headers have already been sent.INVALID_HEADER_NAME—nameis not a valid RFC 9110 token, or is__proto__.INVALID_HEADER_VALUE—valueisundefined, or contains a control character other than tab.
HTTPClientRequest.setTimeout(ms: number, ontimeout?: () => void): this
Sets the underlying socket's timeout to ms and, if given, adds ontimeout as a one-time
'timeout' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ms | number | — | The socket timeout in milliseconds. |
ontimeout? | () => void | — | Added as a one-time 'timeout' listener. |
HTTPClientRequest.socket: TCPSocket | null
The underlying TCPSocket the message is written to, or null until one is assigned.
HTTPClientRequest.uncork(): void
HTTPClientRequest.upgrade: boolean
Whether the connection was upgraded (for example to a WebSocket) after this message.
HTTPClientRequest.writable: boolean
HTTPClientRequest.write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
Overloads:
write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
write(data: unknown, cb?: StreamCallback): booleanParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding? | BufferEncoding | — | — |
cb? | StreamCallback | — | — |
HTTPClientConnection
new HTTPClientConnection(socket: TCPSocket, opts?: HTTPClientConnectionOptions)
The per-socket state machine that parses response data for an HTTPClientRequest, and drives
its 'response' event.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The connection socket. |
opts? | HTTPClientConnectionOptions | — | A custom IncomingMessage class to use for the response. |
HTTPClientConnection.for(socket: TCPSocket): HTTPClientConnection | null
Returns the HTTPClientConnection associated with socket, or null if none exists.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket to look up. |
HTTPClientConnection.from
HTTPClientConnection.from(socket: TCPSocket, opts?: HTTPClientConnectionOptions): HTTPClientConnectionReturns the existing HTTPClientConnection for socket, creating one with opts if none
exists yet.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket to look up or create a connection for. |
opts? | HTTPClientConnectionOptions | — | Options used if a new connection is created. |
HTTPClientConnection.idle: boolean
Whether the connection currently has no in-flight request.
HTTPClientConnection.keepAliveTimeout: number
How long the peer said it holds the connection open for, in milliseconds, or -1 when it said
nothing.
req: HTTPClientRequest | null
The HTTPClientRequest currently in flight on this connection, or null if none.
res: HTTPIncomingMessage | null
The HTTPIncomingMessage currently being read on this connection, or null if none.
HTTPClientConnection.socket: TCPSocket | null
The underlying TCPSocket for this connection.
Functions
createServer
createServer(opts?: HTTPServerOptions, onrequest?: (req: HTTPIncomingMessage, res: HTTPServerResponse) => void): HTTPServerCreates an HTTPServer. If onrequest is given, it's added as a 'request' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPServerOptions | — | Options passed to each HTTPServerConnection, such as custom IncomingMessage and ServerResponse classes. |
onrequest? | (req: HTTPIncomingMessage, res: HTTPServerResponse) => void | — | Added as a listener for the 'request' event. |
request
request(url: URL | string, opts?: HTTPClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void): HTTPClientRequestCreates an HTTPClientRequest to url (a URL or a URL string) or to the destination named by
opts. The request is not ended, so a body can be written before calling end(). If
onresponse is given, it's added as a one-time 'response' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
url | URL | string | — | The URL to request, as a URL object or string; its host, port, and path populate the request options. |
opts? | HTTPClientRequestOptions | — | Request options, merged over the values derived from url. |
onresponse? | (res: HTTPIncomingMessage) => void | — | Added as a one-time 'response' listener. |
Throws
INVALID_PROTOCOL— a protocol is given and is neither'http:'nor'ws:'.
get
get(url: URL | string, opts?: HTTPClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void): HTTPClientRequestLike request(), but ends the request immediately, since GET requests have no body.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
url | URL | string | — | The URL to request, as a URL object or string; its host, port, and path populate the request options. |
opts? | HTTPClientRequestOptions | — | Request options, merged over the values derived from url. |
onresponse? | (res: HTTPIncomingMessage) => void | — | Added as a one-time 'response' listener. |
Throws
INVALID_PROTOCOL— a protocol is given and is neither'http:'nor'ws:'.
Constants and variables
METHODS: HTTPMethod[]
The list of all supported HTTP method names.
STATUS_CODES: typeof constants.status
An alias for constants.status, mapping status codes to their reason phrases.
globalAgent: HTTPAgent
The default HTTPAgent used by request() and get() when no agent option is given.
Types
HTTPMethod
type HTTPMethod = keyof typeof constants.methodA key of constants.method, that is one of the supported HTTP method names.
HTTPStatusCode
type HTTPStatusCode = keyof typeof constants.status | (number & {})An HTTP status code. Any three digit code may be sent or received, so the codes named in
constants.status are only the ones that have a reason phrase of their own rather than the
whole of what is allowed.
HTTPStatusMessage
type HTTPStatusMessage = (typeof constants.status)[keyof typeof constants.status] | (string & {})An HTTP reason phrase. Any field value may stand in for the reason phrase, so the phrases in
constants.status are only the ones a code is given by default rather than the whole of what
is allowed.
HTTPVersion
type HTTPVersion = '1.0' | '1.1'The HTTP version of a message, either '1.0' or '1.1'.
HTTPIncomingHeaderValue
type HTTPIncomingHeaderValue = string | string[]The value of a header as it arrived, which is only ever a list where the field may appear more than once and cannot be folded onto one line.
HTTPInformationalResponse
interface HTTPInformationalResponse {
httpVersion: HTTPVersion
statusCode: HTTPStatusCode
statusMessage: HTTPStatusMessage
headers: Record<string, HTTPIncomingHeaderValue>
}An interim 1xx response received ahead of the final one, carried by the 'information' event of
an HTTPClientRequest.
HTTPIncomingMessageEvents
interface HTTPIncomingMessageEvents {
timeout: []
data: [data: unknown]
end: []
readable: []
piping: [dest: Writable]
close: []
error: [err: Error]
}The events an HTTPIncomingMessage emits in addition to the underlying readable stream's events:
timeout, when the socket times out.
HTTPIncomingMessageOptions
interface HTTPIncomingMessageOptions {
headers?: Record<string, HTTPIncomingHeaderValue>
httpVersion?: HTTPVersion
method?: HTTPMethod
url?: string
statusCode?: HTTPStatusCode
statusMessage?: HTTPStatusMessage
}Options for constructing an HTTPIncomingMessage directly: initial headers, the httpVersion
it arrived as, method and url (server-side), and statusCode/statusMessage (client-side).
HTTPHeaderValue
type HTTPHeaderValue = string | number | null | (string | number | null)[]The value of a header to send. A field whose value is a list may be given as an array, in which
case it is sent as one field per element rather than folded onto a single line. Cookie is the
exception, whose elements are folded onto a single line separated by '; '. A value of null is
sent as the string it coerces to, as Node.js sends it.
HTTPHeaders
type HTTPHeaders = Record<string, HTTPHeaderValue> | (string | HTTPHeaderValue)[] | [string, HTTPHeaderValue][]A set of headers to send, given as a bag, as a flat list of alternating names and values, or as a list of pairs.
HTTPOutgoingMessageEvents
interface HTTPOutgoingMessageEvents {
timeout: []
drain: []
finish: []
pipe: [src: Readable]
close: []
error: [err: Error]
}The events an HTTPOutgoingMessage emits in addition to the underlying writable stream's events:
timeout, when the socket times out.
HTTPAgentOptions
interface HTTPAgentOptions {
keepAlive?: boolean | number
keepAliveMsecs?: number
defaultPort?: number
maxSockets?: number
maxTotalSockets?: number
maxFreeSockets?: number
}Options for HTTPAgent.
HTTPServerEvents
interface HTTPServerEvents {
request: [req: HTTPIncomingMessage, res: HTTPServerResponse]
checkContinue: [req: HTTPIncomingMessage, res: HTTPServerResponse]
checkExpectation: [req: HTTPIncomingMessage, res: HTTPServerResponse]
upgrade: [req: HTTPIncomingMessage, socket: TCPSocket, head: Buffer]
connect: [req: HTTPIncomingMessage, socket: TCPSocket, head: Buffer]
clientError: [err: HTTPError, socket: TCPSocket]
timeout: [socket: TCPSocket]
close: []
connection: [socket: TCPSocket]
drop: [info: TCPServerDropInfo]
error: [err: Error]
listening: []
lookup: [err: Error | null, address: string | null, family: IPFamily | 0, host: string]
}The events an HTTPServer emits in addition to the underlying TCP server's events: request,
for each incoming request; checkContinue and checkExpectation, for a request that announced
an expectation; upgrade and connect, when a connection is handed over; clientError, when a
connection fails; timeout, when a connection's socket times out.
HTTPServerResponseOptions
interface HTTPServerResponseOptions {
keepAliveTimeout?: number
}Options for HTTPServerResponse.
HTTPServerConnectionOptions
interface HTTPServerConnectionOptions {
IncomingMessage?: typeof HTTPIncomingMessage
ServerResponse?: typeof HTTPServerResponse
}Options for HTTPServerConnection, letting custom IncomingMessage and ServerResponse
subclasses be used for requests handled on the connection.
HTTPServerOptions
interface HTTPServerOptions {
headersTimeout?: number
requestTimeout?: number
keepAliveTimeout?: number
maxHeaderSize?: number
maxHeadersCount?: number
maxUpgradeBodySize?: number
IncomingMessage?: typeof HTTPIncomingMessage
ServerResponse?: typeof HTTPServerResponse
allowHalfOpen?: boolean
keepAlive?: boolean | number
keepAliveInitialDelay?: number
maxConnections?: number
noDelay?: boolean
pauseOnConnect?: boolean
readBufferSize?: number
}Options for HTTPServer, extending the HTTPServerConnection and TCPServer options with the
timeouts and limits applied to each connection.
HTTPClientRequestEvents
interface HTTPClientRequestEvents {
response: [res: HTTPIncomingMessage]
continue: []
information: [info: HTTPInformationalResponse]
upgrade: [res: HTTPIncomingMessage, socket: TCPSocket, head: Buffer]
connect: [res: HTTPIncomingMessage, socket: TCPSocket, head: Buffer]
timeout: []
drain: []
finish: []
pipe: [src: Readable]
close: []
error: [err: Error]
}The events an HTTPClientRequest emits in addition to the underlying writable stream's events:
response, with the HTTPIncomingMessage reply; continue and information, for an interim
1xx response; upgrade and connect, when the connection is handed over.
HTTPClientRequestOptions
interface HTTPClientRequestOptions {
agent?: HTTPAgent | false
auth?: string
headers?: Record<string, HTTPHeaderValue>
method?: HTTPMethod
path?: string
protocol?: string
defaultPort?: number
lookup?: DNSLookup
host?: string
keepAlive?: boolean | number
keepAliveInitialDelay?: number
noDelay?: boolean
port?: number
timeout?: number
family?: `IPv${IPFamily}` | IPFamily | 0
hints?: number
all?: boolean
}Options for HTTPClientRequest, extending the TCP connect options with the request itself.
HTTPClientConnectionOptions
interface HTTPClientConnectionOptions {
IncomingMessage?: typeof HTTPIncomingMessage
}Options for HTTPClientConnection, letting a custom IncomingMessage subclass be used for the
response.
Classes
HTTPError
class HTTPError {
code: string
}An error thrown by bare-http1 for protocol-level failures, such as an unimplemented method, a
lost connection, a suspended agent, or an invalid header. Carries a code identifying the
specific failure.
bare-http1/constants
constants
constants.HTTPMethod
type HTTPMethod = keyof typeof constants.methodA key of constants.method, that is one of the supported HTTP method names.
constants.HTTPStatusCode
type HTTPStatusCode = keyof typeof constants.status | (number & {})An HTTP status code. Any three digit code may be sent or received, so the codes named in
constants.status are only the ones that have a reason phrase of their own rather than the
whole of what is allowed.
constants.HTTPStatusMessage
type HTTPStatusMessage = (typeof constants.status)[keyof typeof constants.status] | (string & {})An HTTP reason phrase. Any field value may stand in for the reason phrase, so the phrases in
constants.status are only the ones a code is given by default rather than the whole of what
is allowed.
bare-http1/errors
Classes
errors.HTTPError
An error thrown by bare-http1 for protocol-level failures, such as an unimplemented method, a
lost connection, a suspended agent, or an invalid header. Carries a code identifying the
specific failure.
See also
- Builds on
bare-events,bare-hrtime,bare-http-parser,bare-stream, andbare-tcp. - Bare modules — the full
bare-*catalog. - Bare runtime API — the runtime these modules extend.
Last updated on