LogoPear Docs
ReferencesBareModules

bare-tcp

Native TCP sockets for JavaScript

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)

Source

Create a new TCP socket.

Parameters

ParameterTypeDefaultDescription
opts?TCPSocketOptionsOptions; readBufferSize defaults to 65536, and allowHalfOpen and eagerOpen to true.

connect

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

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
portnumberThe port to connect to.
host?stringThe host to connect to; defaults to 'localhost'.
opts?TCPSocketConnectOptionsConnection options; if host is a hostname it is resolved with opts.lookup, which defaults to dns.lookup from bare-dns.
onconnect?() => voidCalled when the connection is established.

Throws

  • SOCKET_ALREADY_CONNECTED — the socket is already connecting or connected.
  • INVALID_PORTport is not an integer between 0 and 65535.

connecting: boolean

Source

Whether the socket is currently connecting.

localAddress: string

Source

The local IP address of the socket, if connected.

localFamily: string

Source

The local IP family ('IPv4' or 'IPv6'), if connected.

localPort: number

Source

The local port of the socket, if connected.

open(fd: number, opts?: { fd?: number }, onconnect?: () => void): this

Source

Open the socket on the file descriptor of an existing TCP connection, emitting 'connect' once open.

Overloads:

open(fd: number, opts?: { fd?: number }, onconnect?: () => void): this
open(fd: number, onconnect: () => void): this
open(opts: { fd: number }, onconnect?: () => void): this

Parameters

ParameterTypeDefaultDescription
fdnumberThe file descriptor of an existing TCP connection to open the socket on.
opts?{ fd?: number }fd may be given here instead of as the first argument.
onconnect?() => voidCalled once when the socket emits 'connect'.

pending: boolean

Source

Whether the socket has not yet connected.

readyState: 'open' | 'opening'

Source

The current state of the socket. Either 'open' or 'opening'.

TCPSocket.ref(): this

Source

Ref the socket, preventing the process from exiting.

remoteAddress: string

Source

The remote IP address of the socket, if connected.

remoteFamily: string

Source

The remote IP family ('IPv4' or 'IPv6'), if connected.

remotePort: number

Source

The remote port of the socket, if connected.

setKeepAlive(enable?: boolean, delay?: number): this

Source

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?booleanWhether to enable keep-alive.
delay?numberThe initial delay in milliseconds before the first keep-alive probe is sent.

setNoDelay(enable?: boolean): this

Source

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

Parameters

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

setTimeout(ms: number, ontimeout?: () => void): this

Source

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
msnumberThe inactivity timeout in milliseconds; pass 0 to disable the timeout.
ontimeout?() => voidCalled once when the socket emits 'timeout'.

timeout: number

Source

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

TCPSocket.unref(): this

Source

Unref the socket, allowing the process to exit.

TCPServer

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

Source

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?: () => void)
new TCPServer(onconnection: () => void)

Parameters

ParameterTypeDefaultDescription
opts?TCPServerOptionsOptions applied to each incoming socket; readBufferSize defaults to 65536, allowHalfOpen to true, and keepAlive, noDelay, and pauseOnConnect to false.
onconnection?() => voidCalled on each 'connection' event.

address(): TCPSocketAddress

Source

Returns TCPSocketAddress — The bound address as { address, family, port }, or null if the server is not listening.

close(onclose?: (err?: Error) => void): this

Source

Close the server. No new connections will be accepted. The server emits close after all existing connections have ended.

Parameters

ParameterTypeDefaultDescription
onclose?(err?: Error) => voidCalled once when the server emits 'close', after all existing connections have ended.

closing: boolean

Source

Whether the server is closing.

connections: Set<TCPSocket>

Source

A Set of active connections.

listen

listen(port?: number, host?: string, backlog?: number, opts?: TCPServerListenOptions, onlistening?: () => void): this
Source

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?numberThe port to listen on; if 0 (the default), an available port is assigned.
host?stringThe host to listen on; defaults to 'localhost'.
backlog?numberThe maximum length of the queue of pending connections (default 511).
opts?TCPServerListenOptionsListen options; the positional arguments may be given here instead, and lookup (default dns.lookup) resolves host when it is a hostname.
onlistening?() => voidCalled once when the server emits 'listening'.

Throws

  • SERVER_ALREADY_LISTENING — the server is already listening.
  • SERVER_IS_CLOSED — the server has been closed.
  • INVALID_PORTport is not an integer between 0 and 65535.

listening: boolean

Source

Whether the server is listening.

maxConnections: number

Source

The maximum number of concurrent connections; connections beyond it are destroyed and reported via the 'drop' event. Defaults to Infinity.

TCPServer.ref(): this

Source

Ref the server, preventing the process from exiting.

TCPServer.unref(): this

Source

Unref the server, allowing the process to exit.

Functions

createConnection

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

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

Parameters

ParameterTypeDefaultDescription
portnumberThe port to connect to.
host?stringThe host to connect to; defaults to 'localhost'.
opts?TCPSocketOptions & TCPSocketConnectOptionsOptions passed to both the TCPSocket constructor and connect().
onconnect?() => voidCalled when the connection is established.

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

Source

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

Overloads:

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

Parameters

ParameterTypeDefaultDescription
opts?TCPServerOptionsOptions applied to each incoming socket; readBufferSize defaults to 65536, allowHalfOpen to true, and keepAlive, noDelay, and pauseOnConnect to false.
onconnection?() => voidCalled on each 'connection' event.

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

Source

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

Source

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

Parameters

ParameterTypeDefaultDescription
hoststringThe string to check.

isIPv4(host: string): boolean

Source

Returns true if host is an IPv4 address.

Parameters

ParameterTypeDefaultDescription
hoststringThe string to check.

isIPv6(host: string): boolean

Source

Returns true if host is an IPv6 address.

Parameters

ParameterTypeDefaultDescription
hoststringThe string to check.

Constants and variables

constants

constants: {
  state: {
    CONNECTING: number
    CONNECTED: number
    BINDING: number
    BOUND: number
    READING: number
    CLOSING: number
    UNREFED: number
  }
}
Source

Object containing internal state constants.

Types

TCPSocketAddress

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

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

TCPSocketEvents

interface TCPSocketEvents extends DuplexEvents {
  connect: []
  lookup: [err: Error | null, address: string | null, family: IPFamily | 0, host: string]
  timeout: [ms: number]
}
Source

Events emitted by a TCPSocket.

TCPSocketOptions

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

Options for a TCPSocket.

TCPSocketConnectOptions

interface TCPSocketConnectOptions extends LookupOptions {
  lookup?: DNSLookup
  host?: string
  keepAlive?: boolean
  keepAliveInitialDelay?: boolean
  noDelay?: boolean
  port?: number
  timeout?: number
}
Source

Options for connect().

TCPServerDropInfo

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

Details of a connection dropped because maxConnections was exceeded.

TCPServerEvents

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

Events emitted by a TCPServer.

TCPServerOptions

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

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

TCPServerListenOptions

interface TCPServerListenOptions extends LookupOptions {
  lookup?: DNSLookup
  backlog?: number
  host?: string
  port?: number
}
Source

Options for listen().

Classes

TCPError

Source
class TCPError {
  code: string
}

See also

On this page