bare-http1
Native HTTP/1 library for JavaScript
bare-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.methodconstants.HTTPStatusCode
type HTTPStatusCode = keyof typeof constants.statusconstants.HTTPStatusMessage
type HTTPStatusMessage = (typeof constants.status)[HTTPStatusCode]HTTPIncomingMessage
new HTTPIncomingMessage(socket?: TCPSocket, opts?: HTTPIncomingMessageOptions)
Source
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.getHeader(name: string): string | number | undefined
Source
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). |
HTTPIncomingMessage.getHeaders(): Record<string, string | number>
Source
Returns a shallow copy of all headers.
HTTPIncomingMessage.hasHeader(name: string): boolean
Source
Returns whether header name (case-insensitive) is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPIncomingMessage.headers: Record<string, string | number>
Source
The parsed headers, keyed by lowercase name.
httpVersion: '1.1'
Source
The HTTP version of the message. Always '1.1'.
HTTPIncomingMessage.method: HTTPMethod
Source
The request method. Only meaningful on the server side.
HTTPIncomingMessage.setTimeout(ms: number, ontimeout?: () => void): this
Source
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
Source
The underlying TCPSocket the message was read from.
HTTPIncomingMessage.statusCode: HTTPStatusCode
Source
The response status code. Only meaningful on the client side.
statusMessage: HTTPStatusMessage
Source
The response status reason phrase. Only meaningful on the client side.
HTTPIncomingMessage.upgrade: boolean
Source
Whether the connection was upgraded (e.g. to a WebSocket) after this message.
url: string
Source
The request URL path. Only meaningful on the server side.
HTTPOutgoingMessage
new HTTPOutgoingMessage(socket?: TCPSocket)
Source
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. |
flushHeaders(): void
Source
Sends the headers immediately, if they haven't already been sent, instead of waiting for the first write.
HTTPOutgoingMessage.getHeader(name: string): string | number | undefined
Source
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, string | number>
Source
Returns a shallow copy of all headers set so far.
HTTPOutgoingMessage.hasHeader(name: string): boolean
Source
Returns whether header name (case-insensitive) is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive). |
HTTPOutgoingMessage.headers: Record<string, string | number>
Source
The headers set so far, keyed by lowercase name. Assigning validates each header name and value.
headersSent: boolean
Source
Whether the headers have already been sent.
setHeader(name: string, value: string | number): void
Source
Sets header name (case-insensitive) to value, validating both.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | — | The header name (case-insensitive); must be a valid RFC 7230 token. |
value | string | number | — | The header value; must not contain line-terminating characters. |
Throws
INVALID_HEADER_NAME—nameis not a valid RFC 7230 token.INVALID_HEADER_VALUE—valuecontains a line-terminating character.
HTTPOutgoingMessage.setTimeout(ms: number, ontimeout?: () => void): this
Source
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
Source
The underlying TCPSocket the message is written to.
HTTPOutgoingMessage.upgrade: boolean
Source
Whether the connection was upgraded (e.g. to a WebSocket) after this message.
HTTPAgent
new HTTPAgent(opts?: HTTPAgentOptions & TCPSocketOptions & TCPSocketConnectOptions)
Source
Manages a pool of TCPSocket connections shared across requests to the same host and port, 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
Source
Assigns a socket to req, reusing an idle keep-alive socket for the same host and port if one is available, or creating a new one 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
Source
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.
destroy(): void
Source
Destroys all sockets currently held by the agent, both in-use and free.
freeSockets: IterableIterator<TCPSocket>
Source
An iterator over the agent's idle, keep-alive sockets awaiting reuse.
getName(opts: { host: string; port: number }): string
Source
Returns the pool key used to group sockets by destination, derived from opts.host and opts.port.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts | { host: string; port: number } | — | The destination host and port to derive the pool key from. |
HTTPAgent.global: HTTPAgent
Source
The agent's own default instance, used as bare-http1's globalAgent.
keepSocketAlive(socket: TCPSocket): boolean
Source
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. |
resume(): void
Source
Resumes an agent suspended with suspend(), allowing it to create connections again.
resumed: Promise<void> | null
Source
A promise that resolves once a suspended agent is resumed, or null if the agent isn't suspended.
reuseSocket(socket: TCPSocket, req?: HTTPClientRequest): void
Source
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>
Source
An iterator over all sockets currently held by the agent, both in-use and free.
suspend(): void
Source
Suspends the agent, destroying all its sockets and preventing new connections until resume() is called.
suspended: boolean
Source
Whether the agent is currently suspended.
HTTPServer
HTTPServer
new HTTPServer(opts?: HTTPServerConnectionOptions, 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? | HTTPServerConnectionOptions | — | 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. |
HTTPServer.setTimeout(ms: number, ontimeout?: () => void): this
Source
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 | undefined
Source
The idle-socket timeout in milliseconds, or undefined if none is set.
HTTPServerResponse
new HTTPServerResponse(socket: TCPSocket, req: HTTPIncomingMessage)
Source
An outgoing HTTP response, extending HTTPOutgoingMessage. Defaults to status 200 and chunked transfer encoding unless a Content-Length header is set.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
socket | TCPSocket | — | The socket the response is written to. |
req | HTTPIncomingMessage | — | The request this response answers. |
req: HTTPIncomingMessage
Source
The HTTPIncomingMessage this response is answering.
HTTPServerResponse.statusCode: HTTPStatusCode
Source
The response status code to send. Defaults to 200.
statusMessage: HTTPStatusMessage | null
Source
The response status reason phrase to send. Defaults to the standard phrase for statusCode.
writeHead
writeHead(statusCode: HTTPStatusCode, statusMessage?: HTTPStatusMessage, headers?: Record<string, string | number>): voidSets 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? | Record<string, string | number> | — | Additional headers to merge into the response headers. |
Throws
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
Source
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
Source
Whether the connection currently has no in-flight request.
req: HTTPIncomingMessage | null
Source
The HTTPIncomingMessage currently being read on this connection, or null if none.
res: HTTPServerResponse | null
Source
The HTTPServerResponse currently being written on this connection, or null if none.
server: HTTPServer
Source
The HTTPServer this connection belongs to.
HTTPServerConnection.socket: TCPSocket | null
Source
The underlying TCPSocket for this connection.
HTTPClientRequest
new HTTPClientRequest(opts?: HTTPClientRequestOptions, onresponse?: () => void)
Source
An outgoing HTTP request, extending HTTPOutgoingMessage. Uses chunked transfer encoding unless a Content-Length header is set or the method is GET/HEAD.
Overloads:
new HTTPClientRequest(opts?: HTTPClientRequestOptions, onresponse?: () => void)
new HTTPClientRequest(onresponse: () => void)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? | () => void | — | Added as a one-time 'response' listener. |
Throws
INVALID_HEADER_NAME—methodor a header name is not a valid token.INVALID_HEADER_VALUE—pathor a header value contains an invalid character.
HTTPClientRequest.headers: Record<string, string | number>
Source
The headers to send with the request, keyed by lowercase name, including an auto-generated host header.
HTTPClientRequest.method: HTTPMethod
Source
The request method. Defaults to 'GET'.
path: string
Source
The request path. Defaults to '/'.
HTTPClientConnection
new HTTPClientConnection(socket: TCPSocket, opts?: HTTPClientConnectionOptions)
Source
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
Source
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
Source
Whether the connection currently has no in-flight request.
req: HTTPClientRequest | null
Source
The HTTPClientRequest currently in flight on this connection, or null if none.
res: HTTPIncomingMessage | null
Source
The HTTPIncomingMessage currently being read on this connection, or null if none.
HTTPClientConnection.socket: TCPSocket | null
Source
The underlying TCPSocket for this connection.
Functions
createServer
createServer(opts?: HTTPServerConnectionOptions, 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? | HTTPServerConnectionOptions | — | 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). If onresponse is given, it's added as a one-time 'response' listener. Does not send the request until it's ended.
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. |
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. |
Constants and variables
METHODS: HTTPMethod[]
Source
The list of all supported HTTP method names.
STATUS_CODES: typeof constants.status
Source
An alias for constants.status, mapping status codes to their reason phrases.
globalAgent: HTTPAgent
Source
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, i.e. one of the supported HTTP method names.
HTTPStatusCode
type HTTPStatusCode = keyof typeof constants.statusA key of constants.status, i.e. a supported HTTP status code.
HTTPStatusMessage
type HTTPStatusMessage = (typeof constants.status)[HTTPStatusCode]The reason phrase for a given HTTPStatusCode, as found in constants.status.
HTTPIncomingMessageEvents
interface HTTPIncomingMessageEvents extends ReadableEvents {
timeout: []
}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, string | number>
method?: HTTPMethod
url?: string
statusCode?: HTTPStatusCode
statusMessage?: HTTPStatusMessage
}Options for constructing an HTTPIncomingMessage directly: initial headers, method, url (server-side), and statusCode/statusMessage (client-side).
HTTPOutgoingMessageEvents
interface HTTPOutgoingMessageEvents extends WritableEvents {
timeout: []
}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
keepAliveMsecs?: number
}Options for HTTPAgent. keepAlive keeps sockets open for reuse after a request completes, either true (using keepAliveMsecs) or a number of milliseconds. keepAliveMsecs is the keep-alive duration when keepAlive is true, defaulting to 1000.
HTTPServerEvents
interface HTTPServerEvents extends TCPServerEvents {
request: [req: HTTPIncomingMessage, res: HTTPServerResponse]
upgrade: [req: HTTPIncomingMessage, socket: TCPSocket, head: Buffer]
timeout: [socket: TCPSocket]
}The events an HTTPServer emits in addition to the underlying TCP server's events: request, for each incoming request; timeout, when a connection's socket times out; upgrade, when a connection is upgraded (e.g. to a WebSocket).
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.
HTTPClientRequestEvents
interface HTTPClientRequestEvents extends HTTPOutgoingMessageEvents {
response: [res: HTTPIncomingMessage]
upgrade: [res: HTTPIncomingMessage, socket: TCPSocket, head: Buffer]
}The events an HTTPClientRequest emits in addition to the underlying writable stream's events: response, with the HTTPIncomingMessage reply; upgrade, when the connection is upgraded (e.g. to a WebSocket).
HTTPClientRequestOptions
interface HTTPClientRequestOptions extends TCPSocketConnectOptions {
agent?: HTTPAgent | false
headers?: Record<string, string | number>
method?: HTTPMethod
path?: string
}Options for HTTPClientRequest: the agent to use (or false for a fresh, unpooled one), request headers, method (default 'GET'), and path (default '/').
HTTPClientConnectionOptions
interface HTTPClientConnectionOptions {
IncomingMessage?: typeof HTTPIncomingMessage
}Options for HTTPClientConnection, letting a custom IncomingMessage subclass be used for the response.
Classes
HTTPError
Source
class HTTPError {
code: string
}bare-http1/constants
constants
constants.constants.HTTPMethod
type HTTPMethod = keyof typeof constants.methodconstants.constants.HTTPStatusCode
type HTTPStatusCode = keyof typeof constants.statusconstants.constants.HTTPStatusMessage
type HTTPStatusMessage = (typeof constants.status)[HTTPStatusCode]bare-http1/errors
Classes
errors.HTTPError
Source
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
- Bare modules — the full
bare-*catalog. - Bare runtime API — the runtime these modules extend.