Mwrite
Bun

method

Socket.write

data: string | BufferSource,
byteOffset?: number,
byteLength?: number
): number;

Writes data to the socket. This method is unbuffered and non-blocking. This uses the sendto(2) syscall internally.

For optimal performance with multiple small writes, consider batching multiple writes together into a single socket.write() call.

@param data

The data to write. Can be a string (encoded as UTF-8), ArrayBuffer, TypedArray, or DataView.

@param byteOffset

The offset in bytes within the buffer to start writing from. Defaults to 0. Ignored for strings.

@param byteLength

The number of bytes to write from the buffer. Defaults to the remaining length of the buffer from the offset. Ignored for strings.

@returns

The number of bytes written. Returns -1 if the socket is closed or shutting down. Can return less than the input size if the socket's buffer is full (backpressure).

// Send a string
const bytesWritten = socket.write("Hello, world!\n");

// Send binary data
const buffer = new Uint8Array([0x01, 0x02, 0x03]);
socket.write(buffer);

// Send part of a buffer
const largeBuffer = new Uint8Array(1024);
// ... fill largeBuffer ...
socket.write(largeBuffer, 100, 50); // Write 50 bytes starting from index 100

Referenced types

type BufferSource = NodeJS.TypedArray | DataView | ArrayBufferLike