Bare Docs
ReferenceBareModules

bare-tcp

Native TCP sockets for JavaScript

Documented against v2.6.1
stable

bare-tcp — Native TCP sockets for JavaScript. It is a native addon and requires Bare >=1.16.0.

Mirrors the Node.js net module.

npm i bare-tcp

Usage

const tcp = require('bare-tcp')

const server = tcp.createServer()
server.on('connection', (socket) => socket.on('data', console.log))
server.listen(() => console.log('server is up'))

const { port } = server.address()
const socket = tcp.createConnection(port)
socket.write('hello world')

API

TCPSocket

new TCPSocket(opts?: TCPSocketOptions)

Create a new TCP socket.

Parameters

ParameterTypeDefaultDescription
opts?TCPSocketOptions—Options; readBufferSize defaults to 65536, and allowHalfOpen and eagerOpen to true.

_destroy(err: Error | null, cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
errError | null——
cbStreamCallback——

_final(cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
cbStreamCallback——

_open(cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
cbStreamCallback——

_predestroy(): void

_read(size: number): void

Parameters

ParameterTypeDefaultDescription
sizenumber——

_write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
dataunknown——
encodingStreamEncoding——
cbStreamCallback——

_writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void

Parameters

ParameterTypeDefaultDescription
batch{ chunk: unknown; encoding: StreamEncoding }[]——
cbStreamCallback——

TCPSocket.address(): TCPSocketAddress | null

closed: boolean

connect

connect(port: number, host?: string, opts?: TCPSocketConnectOptions, onconnect?: () => void): this

Connect the socket to port on host. If host is not provided, it defaults to 'localhost'. onconnect is called when the connection is established.

Parameters

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

connecting: boolean

Whether the socket is currently connecting.

cork(): void

destroy(err?: Error | null): void

Parameters

ParameterTypeDefaultDescription
err?Error | null——

destroyed: boolean

destroying: boolean

end(cb?: StreamCallback): this

Overloads:

end(cb?: StreamCallback): this
end(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): this
end(data: unknown, cb?: StreamCallback): this

Parameters

ParameterTypeDefaultDescription
cb?StreamCallback——

errored: Error | null

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

Parameters

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

ParameterTypeDefaultDescription
destS——
cb?StreamCallback——

push(data: unknown | null, encoding?: BufferEncoding): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown | null——
encoding?BufferEncoding——

read(): unknown | null

readable: boolean

readyState: 'open' | 'opening' | 'readOnly' | 'writeOnly' | 'closed'

The current state of the socket.

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

ParameterTypeDefaultDescription
encodingBufferEncoding——

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

Parameters

ParameterTypeDefaultDescription
enable?boolean—Whether to enable keep-alive.
delay?number—The initial delay in milliseconds before the first keep-alive probe is sent.

setNoDelay(enable?: boolean): this

Enable or disable Nagle's algorithm. When enable is true (the default), data is sent immediately without buffering.

Parameters

ParameterTypeDefaultDescription
enable?boolean—When true (the default), data is sent immediately without buffering.

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

ParameterTypeDefaultDescription
msnumber—The inactivity timeout in milliseconds; pass 0 to disable the timeout.
ontimeout?() => void—Called once when the socket emits 'timeout'.

timeout: number

The timeout in milliseconds, or undefined if no timeout is set.

uncork(): void

TCPSocket.unref(): this

Unref the socket, allowing the process to exit.

unshift(data: unknown | null, encoding?: BufferEncoding): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown | null——
encoding?BufferEncoding——

writable: boolean

write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean

Overloads:

write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
write(data: unknown, cb?: StreamCallback): boolean

Parameters

ParameterTypeDefaultDescription
dataunknown——
encoding?BufferEncoding——
cb?StreamCallback——

TCPServer

new TCPServer(opts?: TCPServerOptions, onconnection?: (socket: TCPSocket) => void)

Create a new TCP server. If onconnection is provided, it is added as a listener for the connection event.

Overloads:

new TCPServer(opts?: TCPServerOptions, onconnection?: (socket: TCPSocket) => void)
new TCPServer(onconnection: (socket: TCPSocket) => void)

Parameters

ParameterTypeDefaultDescription
opts?TCPServerOptions—Options applied to each incoming socket; readBufferSize defaults to 65536, allowHalfOpen to true, and keepAlive, noDelay, and pauseOnConnect to false.
onconnection?(socket: TCPSocket) => void—Called on each 'connection' event.

addListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

addOnceListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

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

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

ParameterTypeDefaultDescription
nameE——
argsM[E]——

eventNames(): (keyof M)[]

getMaxListeners(): number

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.

listenerCount<E extends keyof M>(name: E): number

Parameters

ParameterTypeDefaultDescription
nameE——

listeners<E extends keyof M>(name: E): EventHandler<M[E]>[]

Parameters

ParameterTypeDefaultDescription
nameE——

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.

off<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

on<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

once<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

prependListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

prependOnceListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

rawListeners<E extends keyof M>(name: E): EventHandler<M[E]>[]

Parameters

ParameterTypeDefaultDescription
nameE——

TCPServer.ref(): this

Ref the server, preventing the process from exiting.

removeAllListeners<E extends keyof M>(name?: E): this

Parameters

ParameterTypeDefaultDescription
name?E——

removeListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this

Parameters

ParameterTypeDefaultDescription
nameE——
fnEventHandler<M[E]>——

setMaxListeners(n: number): this

Parameters

ParameterTypeDefaultDescription
nnumber——

TCPServer.unref(): this

Unref the server, allowing the process to exit.

Functions

createConnection

createConnection(port: number, host?: string, opts?: TCPSocketOptions & TCPSocketConnectOptions, onconnect?: () => void): TCPSocket

Create a new socket and connect it to port on host. Shorthand for new tcp.Socket(options).connect(port, host, options, onconnect).

Parameters

ParameterTypeDefaultDescription
portnumber—The port to connect to.
host?string—The host to connect to; defaults to 'localhost'.
opts?TCPSocketOptions & TCPSocketConnectOptions—Options passed to both the TCPSocket constructor and connect().
onconnect?() => void—Called when the connection is established.

createServer(opts?: TCPServerOptions, onconnection?: (socket: TCPSocket) => void): TCPServer

Create a new TCP server. server extends <https://github.com/holepunchto/bare-events>.

Overloads:

createServer(opts?: TCPServerOptions, onconnection?: (socket: TCPSocket) => void): TCPServer
createServer(onconnection: (socket: TCPSocket) => void): TCPServer

Parameters

ParameterTypeDefaultDescription
opts?TCPServerOptions—Options applied to each incoming socket; readBufferSize defaults to 65536, allowHalfOpen to true, and keepAlive, noDelay, and pauseOnConnect to false.
onconnection?(socket: TCPSocket) => void—Called on each 'connection' event.

socketpair(): [first: number, second: number]

Create a pair of connected sockets, returning their file descriptors.

Returns [first: number, second: number] — The file descriptors of the two connected sockets.

isIP(host: string): IPFamily | 0

Returns 4 if host is an IPv4 address, 6 if it is an IPv6 address, or 0 otherwise.

Parameters

ParameterTypeDefaultDescription
hoststring—The string to check.

isIPv4(host: string): boolean

Returns true if host is an IPv4 address.

Parameters

ParameterTypeDefaultDescription
hoststring—The string to check.

isIPv6(host: string): boolean

Returns true if host is an IPv6 address.

Parameters

ParameterTypeDefaultDescription
hoststring—The string to check.

Constants and variables

constants

constants: {
  state: {
    CONNECTING: number
    CONNECTED: number
    BINDING: number
    BOUND: number
    READING: number
    CLOSING: number
    CLOSED: number
    UNREFED: number
  }
  address: {
    MAX_LENGTH: number
  }
}

Object containing internal state constants.

Types

IPFamily

type IPFamily = 4 | 6

The IP address family: 4 for IPv4 or 6 for IPv6.

TCPServerDropInfo

interface TCPServerDropInfo {
  localAddress?: string
  localPort?: number
  localFamily?: string
  remoteAddress?: string
  remotePort?: number
  remoteFamily?: string
}

Details of a connection dropped because maxConnections was exceeded.

TCPServerEvents

interface TCPServerEvents {
  close: []
  connection: [socket: TCPSocket]
  drop: [info: TCPServerDropInfo]
  error: [err: Error]
  listening: []
  lookup: [err: Error | null, address: string | null, family: IPFamily | 0, host: string]
}

Events emitted by a TCPServer.

TCPServerListenOptions

interface TCPServerListenOptions {
  lookup?: DNSLookup
  backlog?: number
  host?: string
  port?: number
  family?: `IPv${IPFamily}` | IPFamily | 0
  hints?: number
  all?: boolean
}

Options for listen().

TCPServerOptions

interface TCPServerOptions {
  allowHalfOpen?: boolean
  keepAlive?: boolean | number
  keepAliveInitialDelay?: number
  maxConnections?: number
  noDelay?: boolean
  pauseOnConnect?: boolean
  readBufferSize?: number
}

Options for a TCP server, applied to each incoming socket.

TCPSocketAddress

interface TCPSocketAddress {
  address: string
  family: `IPv${IPFamily}`
  port: number
}

The address of a TCP socket, as { address, family, port }.

TCPSocketConnectOptions

interface TCPSocketConnectOptions {
  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 connect().

TCPSocketEvents

interface TCPSocketEvents {
  connect: []
  lookup: [err: Error | null, address: string | null, family: IPFamily | 0, host: string]
  timeout: []
  data: [data: unknown]
  end: []
  readable: []
  piping: [dest: Writable]
  close: []
  error: [err: Error]
  drain: []
  finish: []
  pipe: [src: Readable]
}

Events emitted by a TCPSocket.

TCPSocketOpenOptions

interface TCPSocketOpenOptions {
  fd?: number
  keepAlive?: boolean | number
  keepAliveInitialDelay?: number
  noDelay?: boolean
  timeout?: number
}

TCPSocketOptions

interface TCPSocketOptions {
  allowHalfOpen?: boolean
  eagerOpen?: boolean
  readBufferSize?: number
}

Options for a TCPSocket.

Classes

TCPError

class TCPError {
  code: string
}

An error produced by bare-tcp; code identifies the failure.

bare-tcp/constants

Constants and variables

constants

constants: {
  state: {
    CONNECTING: number
    CONNECTED: number
    BINDING: number
    BOUND: number
    READING: number
    CLOSING: number
    CLOSED: number
    UNREFED: number
  }
  address: {
    MAX_LENGTH: number
  }
}

Object containing internal state constants.

bare-tcp/errors

Classes

errors.TCPError

An error produced by bare-tcp; code identifies the failure.

See also

Last updated on

Was this helpful?

On this page

Usage
API
TCPSocket
new TCPSocket(opts?: TCPSocketOptions)
_destroy(err: Error | null, cb: StreamCallback): void
_final(cb: StreamCallback): void
_open(cb: StreamCallback): void
_predestroy(): void
_read(size: number): void
_write(data: unknown, encoding: StreamEncoding, cb: StreamCallback): void
_writev(batch: { chunk: unknown; encoding: StreamEncoding }[], cb: StreamCallback): void
TCPSocket.address(): TCPSocketAddress | null
closed: boolean
connect
connecting: boolean
cork(): void
destroy(err?: Error | null): void
destroyed: boolean
destroying: boolean
end(cb?: StreamCallback): this
errored: Error | null
keepAlive: boolean
keepAliveInitialDelay: number
localAddress: string
localFamily: string
localPort: number
noDelay: boolean
open(fd: number, opts?: TCPSocketOpenOptions, onconnect?: () => void): this
pause(): this
pending: boolean
pipe<S extends Writable>(dest: S, cb?: StreamCallback): S
push(data: unknown | null, encoding?: BufferEncoding): boolean
read(): unknown | null
readable: boolean
readyState: 'open' | 'opening' | 'readOnly' | 'writeOnly' | 'closed'
TCPSocket.ref(): this
remoteAddress: string
remoteFamily: string
remotePort: number
resume(): this
setEncoding(encoding: BufferEncoding): void
setKeepAlive(enable?: boolean, delay?: number): this
setNoDelay(enable?: boolean): this
setTimeout(ms: number, ontimeout?: () => void): this
timeout: number
uncork(): void
TCPSocket.unref(): this
unshift(data: unknown | null, encoding?: BufferEncoding): boolean
writable: boolean
write(data: unknown, encoding?: BufferEncoding, cb?: StreamCallback): boolean
TCPServer
new TCPServer(opts?: TCPServerOptions, onconnection?: (socket: TCPSocket) => void)
addListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
addOnceListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
TCPServer.address(): TCPSocketAddress | null
close(onclose?: () => void): this
closing: boolean
connections: Set<TCPSocket>
emit<E extends keyof M>(name: E, ...args: M[E]): boolean
eventNames(): (keyof M)[]
getMaxListeners(): number
listen
listenerCount<E extends keyof M>(name: E): number
listeners<E extends keyof M>(name: E): EventHandler<M[E]>[]
listening: boolean
maxConnections: number
off<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
on<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
once<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
prependListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
prependOnceListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
rawListeners<E extends keyof M>(name: E): EventHandler<M[E]>[]
TCPServer.ref(): this
removeAllListeners<E extends keyof M>(name?: E): this
removeListener<E extends keyof M>(name: E, fn: EventHandler<M[E]>): this
setMaxListeners(n: number): this
TCPServer.unref(): this
Functions
createConnection
createServer(opts?: TCPServerOptions, onconnection?: (socket: TCPSocket) => void): TCPServer
socketpair(): [first: number, second: number]
isIP(host: string): IPFamily | 0
isIPv4(host: string): boolean
isIPv6(host: string): boolean
Constants and variables
constants
Types
IPFamily
TCPServerDropInfo
TCPServerEvents
TCPServerListenOptions
TCPServerOptions
TCPSocketAddress
TCPSocketConnectOptions
TCPSocketEvents
TCPSocketOpenOptions
TCPSocketOptions
Classes
TCPError
bare-tcp/constants
Constants and variables
constants
bare-tcp/errors
Classes
errors.TCPError
See also