Bare Docs

bare-http1

Native HTTP/1 library for JavaScript

Documented against v4.6.3
stable

bare-http1 — Native HTTP/1 library for JavaScript.

Mirrors the Node.js http module.

npm i bare-http1

Usage

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.method

A 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

ParameterTypeDefaultDescription
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).

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.

getHeader(name: string): HTTPIncomingHeaderValue | undefined

Returns the value of header name (case-insensitive), or undefined if not set.

Parameters

ParameterTypeDefaultDescription
namestring—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

ParameterTypeDefaultDescription
namestring—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.

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

ParameterTypeDefaultDescription
msnumber—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.

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.

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

ParameterTypeDefaultDescription
socket?TCPSocket—The socket the message is written to.

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

ParameterTypeDefaultDescription
namestring—The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValue—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 — name is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUE — value is undefined, or contains a control character other than tab.

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

ParameterTypeDefaultDescription
namestring—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

ParameterTypeDefaultDescription
namestring—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.setHeader(name: string, value: HTTPHeaderValue): void

Sets header name (case-insensitive) to value, replacing any value already set and validating both.

Parameters

ParameterTypeDefaultDescription
namestring—The header name (case-insensitive); must be a valid RFC 7230 token.
valueHTTPHeaderValue—The header value; must not contain line-terminating characters.

Throws

  • HEADERS_SENT — the headers have already been sent.
  • INVALID_HEADER_NAME — name is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUE — value is undefined, 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

ParameterTypeDefaultDescription
msnumber—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.upgrade: boolean

Whether the connection was upgraded (for example to a WebSocket) after this message.

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

ParameterTypeDefaultDescription
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

ParameterTypeDefaultDescription
reqHTTPClientRequest—The request to assign a socket to.
optsTCPSocketOptions & 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

ParameterTypeDefaultDescription
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

ParameterTypeDefaultDescription
optsTCPSocketConnectOptions—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

ParameterTypeDefaultDescription
socketTCPSocket—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

ParameterTypeDefaultDescription
socketTCPSocket—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

ParameterTypeDefaultDescription
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.

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

ParameterTypeDefaultDescription
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.

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): this

Start 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

ParameterTypeDefaultDescription
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 — port is not an integer between 0 and 65535.

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.

ref(): this

Ref the server, preventing the process from exiting.

requestTimeout: number

How long a whole request may take, in milliseconds, before it is given up on. Defaults to 300000; zero disables it.

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

ParameterTypeDefaultDescription
msnumber—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

ParameterTypeDefaultDescription
socketTCPSocket—The socket the response is written to.
reqHTTPIncomingMessage—The request this response answers.
opts?HTTPServerResponseOptions—The keepAliveTimeout to advertise to the peer.

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

ParameterTypeDefaultDescription
namestring—The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValue—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 — name is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUE — value is undefined, or contains a control character other than tab.

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

ParameterTypeDefaultDescription
namestring—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

ParameterTypeDefaultDescription
namestring—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.

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

ParameterTypeDefaultDescription
namestring—The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValue—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 — name is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUE — value is undefined, 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

ParameterTypeDefaultDescription
msnumber—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.upgrade: boolean

Whether the connection was upgraded (for example to a WebSocket) after this message.

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): this

Sets statusCode, and optionally statusMessage and additional headers, in one call.

Parameters

ParameterTypeDefaultDescription
statusCodeHTTPStatusCode—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 — statusCode is not a valid status code.
  • INVALID_HEADER_NAME — a header name is not a valid token.
  • INVALID_HEADER_VALUE — statusMessage or 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

ParameterTypeDefaultDescription
serverHTTPServer—The server the connection belongs to.
socketTCPSocket—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

ParameterTypeDefaultDescription
socketTCPSocket—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

ParameterTypeDefaultDescription
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 — method or a header name is not a valid token.
  • INVALID_HEADER_VALUE — host is not a string, or path or a header value contains an invalid character.

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

ParameterTypeDefaultDescription
namestring—The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValue—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 — name is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUE — value is undefined, or contains a control character other than tab.

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

ParameterTypeDefaultDescription
namestring—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

ParameterTypeDefaultDescription
namestring—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.setHeader(name: string, value: HTTPHeaderValue): void

Sets header name (case-insensitive) to value, replacing any value already set and validating both.

Parameters

ParameterTypeDefaultDescription
namestring—The header name (case-insensitive); must be a valid RFC 9110 token, and must not be __proto__.
valueHTTPHeaderValue—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 — name is not a valid RFC 9110 token, or is __proto__.
  • INVALID_HEADER_VALUE — value is undefined, 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

ParameterTypeDefaultDescription
msnumber—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.upgrade: boolean

Whether the connection was upgraded (for example to a WebSocket) after this message.

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

ParameterTypeDefaultDescription
socketTCPSocket—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

ParameterTypeDefaultDescription
socketTCPSocket—The socket to look up.

HTTPClientConnection.from

HTTPClientConnection.from(socket: TCPSocket, opts?: HTTPClientConnectionOptions): HTTPClientConnection

Returns the existing HTTPClientConnection for socket, creating one with opts if none exists yet.

Parameters

ParameterTypeDefaultDescription
socketTCPSocket—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): HTTPServer

Creates an HTTPServer. If onrequest is given, it's added as a 'request' listener.

Parameters

ParameterTypeDefaultDescription
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): HTTPClientRequest

Creates 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

ParameterTypeDefaultDescription
urlURL | 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): HTTPClientRequest

Like request(), but ends the request immediately, since GET requests have no body.

Parameters

ParameterTypeDefaultDescription
urlURL | 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.method

A 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.method

A 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, and bare-tcp.
  • Bare modules — the full bare-* catalog.
  • Bare runtime API — the runtime these modules extend.

Last updated on

Was this helpful?

On this page

UsageAPIconstantsconstants.HTTPMethodconstants.HTTPStatusCodeconstants.HTTPStatusMessageHTTPIncomingMessagenew HTTPIncomingMessage(socket?: TCPSocket, opts?: HTTPIncomingMessageOptions)complete: booleangetHeader(name: string): HTTPIncomingHeaderValue | undefinedgetHeaders(): Record<string, HTTPIncomingHeaderValue>HTTPIncomingMessage.hasHeader(name: string): booleanheaders: Record<string, HTTPIncomingHeaderValue>httpVersion: HTTPVersionHTTPIncomingMessage.method: HTTPMethodHTTPIncomingMessage.setTimeout(ms: number, ontimeout?: () => void): thisHTTPIncomingMessage.socket: TCPSocket | nullHTTPIncomingMessage.statusCode: HTTPStatusCodestatusMessage: HTTPStatusMessageHTTPIncomingMessage.upgrade: booleanurl: stringHTTPOutgoingMessagenew HTTPOutgoingMessage(socket?: TCPSocket)HTTPOutgoingMessage.appendHeader(name: string, value: HTTPHeaderValue): voidHTTPOutgoingMessage.flushHeaders(): voidHTTPOutgoingMessage.getHeader(name: string): HTTPHeaderValue | undefinedHTTPOutgoingMessage.getHeaders(): Record<string, HTTPHeaderValue>HTTPOutgoingMessage.hasHeader(name: string): booleanHTTPOutgoingMessage.headers: Record<string, HTTPHeaderValue>HTTPOutgoingMessage.headersSent: booleanHTTPOutgoingMessage.setHeader(name: string, value: HTTPHeaderValue): voidHTTPOutgoingMessage.setTimeout(ms: number, ontimeout?: () => void): thisHTTPOutgoingMessage.socket: TCPSocket | nullHTTPOutgoingMessage.upgrade: booleanHTTPAgentnew HTTPAgent(opts?: HTTPAgentOptions & TCPSocketOptions & TCPSocketConnectOptions)addRequest(req: HTTPClientRequest, opts: TCPSocketOptions & TCPSocketConnectOptions): voidcreateConnection(opts?: TCPSocketOptions & TCPSocketConnectOptions): TCPSocketdefaultPort: numberdestroy(): voidfreeSockets: IterableIterator<TCPSocket>getName(opts: TCPSocketConnectOptions): stringHTTPAgent.global: HTTPAgentkeepAlive: booleankeepSocketAlive(socket: TCPSocket): booleanmaxFreeSockets: numbermaxSockets: numbermaxTotalSockets: numberresume(): voidresumed: Promise<void> | nullreuseSocket(socket: TCPSocket, req?: HTTPClientRequest): voidsockets: IterableIterator<TCPSocket>suspend(): voidsuspended: booleanHTTPServerHTTPServeraddress(): TCPSocketAddress | nullclose(onclose?: () => void): thiscloseAllConnections(): voidcloseIdleConnections(): voidclosing: booleanconnections: Set<TCPSocket>headersTimeout: numberHTTPServer.keepAliveTimeout: numberlistenlistening: booleanmaxConnections: numbermaxHeadersCount: numbermaxHeaderSize: numbermaxUpgradeBodySize: numberref(): thisrequestTimeout: numberHTTPServer.setTimeout(ms: number, ontimeout?: () => void): thistimeout: numberunref(): thisHTTPServerResponseHTTPServerResponseHTTPServerResponse.appendHeader(name: string, value: HTTPHeaderValue): voidHTTPServerResponse.flushHeaders(): voidHTTPServerResponse.getHeader(name: string): HTTPHeaderValue | undefinedHTTPServerResponse.getHeaders(): Record<string, HTTPHeaderValue>HTTPServerResponse.hasHeader(name: string): booleanHTTPServerResponse.headers: Record<string, HTTPHeaderValue>HTTPServerResponse.headersSent: booleanreq: HTTPIncomingMessageHTTPServerResponse.setHeader(name: string, value: HTTPHeaderValue): voidHTTPServerResponse.setTimeout(ms: number, ontimeout?: () => void): thisHTTPServerResponse.socket: TCPSocket | nullHTTPServerResponse.statusCode: HTTPStatusCodestatusMessage: HTTPStatusMessage | nullHTTPServerResponse.upgrade: booleanwriteContinue(): voidwriteHeadHTTPServerConnectionHTTPServerConnectionHTTPServerConnection.for(socket: TCPSocket): HTTPServerConnection | nullHTTPServerConnection.idle: booleanreq: HTTPIncomingMessage | nullres: HTTPServerResponse | nullserver: HTTPServerHTTPServerConnection.socket: TCPSocket | nullHTTPClientRequestHTTPClientRequestabort(): voidHTTPClientRequest.appendHeader(name: string, value: HTTPHeaderValue): voidHTTPClientRequest.flushHeaders(): voidHTTPClientRequest.getHeader(name: string): HTTPHeaderValue | undefinedHTTPClientRequest.getHeaders(): Record<string, HTTPHeaderValue>HTTPClientRequest.hasHeader(name: string): booleanHTTPClientRequest.headers: Record<string, HTTPHeaderValue>HTTPClientRequest.headersSent: booleanHTTPClientRequest.method: HTTPMethodpath: stringHTTPClientRequest.setHeader(name: string, value: HTTPHeaderValue): voidHTTPClientRequest.setTimeout(ms: number, ontimeout?: () => void): thisHTTPClientRequest.socket: TCPSocket | nullHTTPClientRequest.upgrade: booleanHTTPClientConnectionnew HTTPClientConnection(socket: TCPSocket, opts?: HTTPClientConnectionOptions)HTTPClientConnection.for(socket: TCPSocket): HTTPClientConnection | nullHTTPClientConnection.fromHTTPClientConnection.idle: booleanHTTPClientConnection.keepAliveTimeout: numberreq: HTTPClientRequest | nullres: HTTPIncomingMessage | nullHTTPClientConnection.socket: TCPSocket | nullFunctionscreateServerrequestgetConstants and variablesMETHODS: HTTPMethod[]STATUS_CODES: typeof constants.statusglobalAgent: HTTPAgentTypesHTTPMethodHTTPStatusCodeHTTPStatusMessageHTTPVersionHTTPIncomingHeaderValueHTTPInformationalResponseHTTPIncomingMessageEventsHTTPIncomingMessageOptionsHTTPHeaderValueHTTPHeadersHTTPOutgoingMessageEventsHTTPAgentOptionsHTTPServerEventsHTTPServerResponseOptionsHTTPServerConnectionOptionsHTTPServerOptionsHTTPClientRequestEventsHTTPClientRequestOptionsHTTPClientConnectionOptionsClassesHTTPErrorbare-http1/constantsconstantsconstants.HTTPMethodconstants.HTTPStatusCodeconstants.HTTPStatusMessagebare-http1/errorsClasseserrors.HTTPErrorSee also