bare-https
HTTPS library for JavaScript
v3.1.0bare-https — HTTPS library for JavaScript.
Mirrors the Node.js https module.
npm i bare-httpsUsage
const https = require('bare-https')
const options = {
cert: fs.readFileSync('test/fixtures/cert.crt'),
key: fs.readFileSync('test/fixtures/cert.key')
}
const server = https.createServer(options, (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 = https.request({ port }, (res) => {
res.on('data', (data) => console.log(data.toString()))
})
client.end()
})API
HTTPSSocket
HTTPSSocket._destroy(err: Error | null, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err | Error | null | — | — |
cb | StreamCallback | — | — |
HTTPSSocket._final(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPSSocket._open(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPSSocket._predestroy(): void
_read(size: number): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
size | number | — | — |
HTTPSSocket._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding | StreamEncoding | — | — |
cb | StreamCallback | — | — |
HTTPSSocket._writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
batch | { chunk: unknown; encoding: StreamEncoding }[] | — | — |
cb | StreamCallback | — | — |
address(): TCPSocketAddress | null
alpnProtocol: string | null
HTTPSSocket.closed: boolean
connect
connect(port: number, host?: string, opts?: TCPSocketConnectOptions, onconnect?: () => void): thisConnect the socket to port on host. If host is not provided, it defaults to
'localhost'. onconnect is called when the connection is established.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
port | number | — | The port to connect to. |
host? | string | — | The host to connect to; defaults to 'localhost'. |
opts? | TCPSocketConnectOptions | — | Connection options; if host is a hostname it is resolved with opts.lookup, which defaults to dns.lookup from bare-dns. |
onconnect? | () => void | — | Called when the connection is established. |
Throws
SOCKET_ALREADY_CONNECTED— the socket is already connecting or connected.INVALID_PORT—portis not an integer between 0 and 65535.
connecting: boolean
Whether the socket is currently connecting.
HTTPSSocket.cork(): void
HTTPSSocket.destroy(err?: Error | null): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err? | Error | null | — | — |
HTTPSSocket.destroyed: boolean
HTTPSSocket.destroying: boolean
encrypted: true
HTTPSSocket.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 | — | — |
HTTPSSocket.errored: Error | null
HTTPSSocket.keepAlive: boolean
keepAliveInitialDelay: number
localAddress: string
The local IP address of the socket, if connected.
localFamily: string
The local IP family ('IPv4' or 'IPv6'), if connected.
localPort: number
The local port of the socket, if connected.
noDelay: boolean
open(fd: number, opts?: TCPSocketOpenOptions, onconnect?: () => void): this
Open the socket on the file descriptor of an existing TCP connection, emitting 'connect' once
open.
Overloads:
open(fd: number, opts?: TCPSocketOpenOptions, onconnect?: () => void): this
open(fd: number, onconnect: () => void): this
open(opts: TCPSocketOpenOptions & { fd: number }, onconnect?: () => void): thisParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
fd | number | — | The file descriptor of an existing TCP connection to open the socket on. |
opts? | TCPSocketOpenOptions | — | fd may be given here instead of as the first argument. |
onconnect? | () => void | — | Called once when the socket emits 'connect'. |
pause(): this
pending: boolean
Whether the socket has not yet connected.
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
HTTPSSocket.readable: boolean
readyState: 'open' | 'opening' | 'readOnly' | 'writeOnly' | 'closed'
The current state of the socket.
ref(): this
Ref the socket, preventing the process from exiting.
remoteAddress: string
The remote IP address of the socket, if connected.
remoteFamily: string
The remote IP family ('IPv4' or 'IPv6'), if connected.
remotePort: number
The remote port of the socket, if connected.
resume(): this
setEncoding(encoding: BufferEncoding): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
encoding | BufferEncoding | — | — |
setKeepAlive(enable?: boolean, delay?: number): this
Enable or disable keep-alive. delay is the initial delay in milliseconds before the first
keep-alive probe is sent.
Overloads:
setKeepAlive(enable?: boolean, delay?: number): this
setKeepAlive(delay: number): thisParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enable? | boolean | — | — |
delay? | number | — | — |
setNoDelay(enable?: boolean): this
Enable or disable Nagle's algorithm. When enable is true (the default), data is sent
immediately without buffering.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enable? | boolean | — | — |
HTTPSSocket.setTimeout(ms: number, ontimeout?: () => void): this
Set a timeout in milliseconds. When the socket is idle for ms milliseconds, a timeout event
is emitted. Pass 0 to disable the timeout.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
ms | number | — | — |
ontimeout? | () => void | — | — |
socket: Duplex
timeout: number
The timeout in milliseconds, or undefined if no timeout is set.
HTTPSSocket.uncork(): void
unref(): this
Unref the socket, allowing the process to exit.
unshift(data: unknown | null, encoding?: BufferEncoding): boolean
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | null | — | — |
encoding? | BufferEncoding | — | — |
HTTPSSocket.writable: boolean
HTTPSSocket.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 | — | — |
HTTPSAgent
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?: HTTPSSocketOptions): HTTPSSocket
Creates a new HTTPSSocket connection wrapping a plain TCP connection in TLS.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPSSocketOptions | — | Options for the underlying TCP connection and its TLS wrapper. |
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 connection options to derive the pool key from. |
HTTPSAgent.global: HTTPSAgent
The agent's own default instance (created with keepAlive: 1000 and timeout: 5000), used as bare-https's globalAgent.
HTTPSAgent.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.
HTTPSServer
HTTPSServer
new HTTPSServer(opts?: HTTPSServerOptions, onrequest?: (req: HTTPIncomingMessage, res: HTTPServerResponse) => void)An HTTPS server, reusing bare-http1's request parsing and response handling over HTTPSSocket connections instead of plain TCPSocket connections.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPSServerOptions | — | Server options: TLS socket options (for example cert, key) plus bare-http1 server connection options. |
onrequest? | (req: HTTPIncomingMessage, res: HTTPServerResponse) => void | — | Added as a 'request' listener. |
HTTPSClientRequest
new HTTPSClientRequest(opts?: HTTPSClientRequestOptions, onresponse?: () => void)
An outgoing HTTPS request, extending bare-http1's HTTPClientRequest but defaulting to an HTTPSAgent instead of an HTTPAgent.
Overloads:
new HTTPSClientRequest(opts?: HTTPSClientRequestOptions, onresponse?: () => void)
new HTTPSClientRequest(onresponse: () => void)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPSClientRequestOptions | — | bare-http1 client request options; agent defaults to HTTPSAgent.global, or pass agent: false to use a fresh HTTPSAgent. |
onresponse? | () => void | — | Added as a one-time 'response' listener. |
HTTPSClientRequest._destroy(err: Error | null, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err | Error | null | — | — |
cb | StreamCallback | — | — |
HTTPSClientRequest._final(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPSClientRequest._open(cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
cb | StreamCallback | — | — |
HTTPSClientRequest._predestroy(): void
HTTPSClientRequest._write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
data | unknown | — | — |
encoding | StreamEncoding | — | — |
cb | StreamCallback | — | — |
HTTPSClientRequest._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.
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.
HTTPSClientRequest.closed: boolean
HTTPSClientRequest.cork(): void
HTTPSClientRequest.destroy(err?: Error | null): void
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
err? | Error | null | — | — |
HTTPSClientRequest.destroyed: boolean
HTTPSClientRequest.destroying: boolean
HTTPSClientRequest.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 | — | — |
HTTPSClientRequest.errored: Error | null
flushHeaders(): void
Sends the headers immediately, if they haven't already been sent, instead of waiting for the first write.
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). |
getHeaders(): Record<string, HTTPHeaderValue>
Returns a shallow copy of all headers set so far.
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, HTTPHeaderValue>
The headers to send with the request, keyed by lowercase name, including an auto-generated
host header.
headersSent: boolean
Whether the headers have already been sent.
method: HTTPMethod
The request method. Defaults to 'GET'.
path: string
The request path. Defaults to '/'.
HTTPSClientRequest.readable: boolean
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.
HTTPSClientRequest.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. |
socket: TCPSocket | null
The underlying TCPSocket the message is written to, or null until one is assigned.
HTTPSClientRequest.uncork(): void
upgrade: boolean
Whether the connection was upgraded (for example to a WebSocket) after this message.
HTTPSClientRequest.writable: boolean
HTTPSClientRequest.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 | — | — |
Functions
createServer
createServer(opts?: HTTPSServerOptions, onrequest?: (req: HTTPIncomingMessage, res: HTTPServerResponse) => void): HTTPSServerCreates an HTTPSServer. If onrequest is given, it's added as a 'request' listener.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
opts? | HTTPSServerOptions | — | Server options: TLS socket options (for example cert, key) plus bare-http1 server connection options. |
onrequest? | (req: HTTPIncomingMessage, res: HTTPServerResponse) => void | — | Added as a 'request' listener. |
request
request(url: URL | string, opts?: HTTPSClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void): HTTPSClientRequestCreates an HTTPSClientRequest to url (a URL or a URL string), using TLS. 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 a URL string. |
opts? | HTTPSClientRequestOptions | — | bare-http1 client request options; agent defaults to globalAgent, or pass agent: false to use a fresh HTTPSAgent. |
onresponse? | (res: HTTPIncomingMessage) => void | — | Added as a one-time 'response' listener. |
get
get(url: URL | string, opts?: HTTPSClientRequestOptions, onresponse?: (res: HTTPIncomingMessage) => void): HTTPSClientRequestParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
url | URL | string | — | — |
opts? | HTTPSClientRequestOptions | — | — |
onresponse? | (res: HTTPIncomingMessage) => void | — | — |
Constants and variables
globalAgent: HTTPSAgent
The default HTTPSAgent used by request() when no agent option is given.
Types
HTTPSSocketEvents
interface HTTPSSocketEvents {
connect: []
data: [data: unknown]
end: []
readable: []
piping: [dest: Writable]
close: []
error: [err: Error]
drain: []
finish: []
pipe: [src: Readable]
lookup: [err: Error | null, address: string | null, family: IPFamily | 0, host: string]
timeout: []
}The events an HTTPSSocket emits: those of both TLSSocket and TCPSocket.
HTTPSSocketOptions
interface HTTPSSocketOptions {
isServer?: boolean
cert?: ArrayBufferView
key?: ArrayBufferView
host?: string
rejectUnauthorized?: boolean
ca?: ArrayBufferView
alpnProtocols?: string[]
eagerOpen?: boolean
allowHalfOpen?: boolean
readBufferSize?: number
lookup?: DNSLookup
keepAlive?: boolean | number
keepAliveInitialDelay?: number
noDelay?: boolean
port?: number
timeout?: number
family?: `IPv${IPFamily}` | IPFamily | 0
hints?: number
all?: boolean
}Options for HTTPSSocket: those of TLSSocket combined with TCPSocket's connection options.
See also
- Builds on
bare-http1,bare-tcp, andbare-tls. - Bare modules — the full
bare-*catalog. - Bare runtime API — the runtime these modules extend.