UNPKG

node-osc

Version:

pyOSC inspired library for sending and receiving OSC messages

478 lines (329 loc) 11.3 kB
<!-- Generated by JSDoc. Update this documentation by updating the source code. --> # API Reference > **⚠️ This file is auto-generated from JSDoc comments in the source code.** > To update this documentation, edit the JSDoc comments in the source files and run `npm run docs`. This document provides detailed API reference for all classes, methods, and functions in node-osc. For usage guides, best practices, and troubleshooting, see the **[Guide](./GUIDE.md)**. ## Table of Contents - [Server](#server) - [Constructor](#server-constructor) - [close()](#server-close) - [Client](#client) - [Constructor](#client-constructor) - [close()](#client-close) - [send()](#client-send) - [Message](#message) - [Constructor](#message-constructor) - [append()](#message-append) - [Bundle](#bundle) - [Constructor](#bundle-constructor) - [append()](#bundle-append) - [Low Level Functions](#low-level-functions) - [encode()](#encode) - [decode()](#decode) --- ## Server **Extends:** EventEmitter OSC Server for receiving messages and bundles over UDP. Emits the following events: - 'listening': Emitted when the server starts listening - 'message': Emitted when an OSC message is received (receives msg array and rinfo object) - 'bundle': Emitted when an OSC bundle is received (receives bundle object and rinfo object) - 'error': Emitted when a socket error or decoding error occurs (receives error and rinfo) - Address-specific events: Emitted for each message address (e.g., '/test') ### Server Constructor Creates a new Server instance. **Parameters:** - `port` *{number}* - The port to listen on. - `host` *{string}* (optional) - Default: `'127.0.0.1'` - The host address to bind to. Use '0.0.0.0' to listen on all interfaces. - `cb` *{function}* (optional) - Optional callback function called when server starts listening. **Examples:** ```javascript // Create and listen for messages const server = new Server(3333, '0.0.0.0', () => { console.log('Server is listening'); }); server.on('message', (msg, rinfo) => { console.log('Message:', msg); console.log('From:', rinfo.address, rinfo.port); }); ``` ```javascript // Using async/await with events.once import { once } from 'node:events'; const server = new Server(3333, '0.0.0.0'); await once(server, 'listening'); server.on('message', (msg) => { console.log('Message:', msg); }); ``` ```javascript // Listen for specific OSC addresses server.on('/note', (msg) => { const [address, pitch, velocity] = msg; console.log(`Note: ${pitch}, Velocity: ${velocity}`); }); ``` ### Server.close() Close the server socket. This method can be used with either a callback or as a Promise. **Parameters:** - `cb` *{function}* (optional) - Optional callback function called when socket is closed. **Returns:** *{Promise.<void> | undefined}* - Returns a Promise if no callback is provided. **Examples:** ```javascript // With callback server.close((err) => { if (err) console.error(err); }); ``` ```javascript // With async/await await server.close(); ``` --- ## Client **Extends:** EventEmitter OSC Client for sending messages and bundles over UDP. Extends EventEmitter and emits the following events: - 'error': Emitted when a socket error occurs ### Client Constructor Creates a new Client instance. **Parameters:** - `host` *{string}* - The hostname or IP address of the OSC server. - `port` *{number}* - The port number of the OSC server. **Examples:** ```javascript // Create a client const client = new Client('127.0.0.1', 3333); // Send a message with callback client.send('/oscAddress', 200, (err) => { if (err) console.error(err); client.close(); }); ``` ```javascript // Send a message with async/await const client = new Client('127.0.0.1', 3333); await client.send('/oscAddress', 200); await client.close(); ``` ### Client.close() Close the client socket. This method can be used with either a callback or as a Promise. **Parameters:** - `cb` *{function}* (optional) - Optional callback function called when socket is closed. **Returns:** *{Promise.<void> | undefined}* - Returns a Promise if no callback is provided. **Examples:** ```javascript // With callback client.close((err) => { if (err) console.error(err); }); ``` ```javascript // With async/await await client.close(); ``` ### Client.send() Send an OSC message or bundle to the server. This method can be used with either a callback or as a Promise. Messages can be sent in several formats: - As separate arguments: address followed by values - As a Message or Bundle object - As an array: [address, ...values] **Parameters:** - `args` *{*}* - The message to send. Can be: - (address: string, ...values: any[], callback?: Function) - (message: Message|Bundle, callback?: Function) - (array: Array, callback?: Function) **Returns:** *{Promise.<void> | undefined}* - Returns a Promise if no callback is provided. **Throws:** - *{TypeError}* - If the message format is invalid. - *{ReferenceError}* - If attempting to send on a closed socket. **Examples:** ```javascript // Send with address and arguments client.send('/oscAddress', 200, 'hello', (err) => { if (err) console.error(err); }); ``` ```javascript // Send with async/await await client.send('/oscAddress', 200, 'hello'); ``` ```javascript // Send a Message object const msg = new Message('/test', 1, 2, 3); await client.send(msg); ``` ```javascript // Send a Bundle object const bundle = new Bundle(['/one', 1], ['/two', 2]); await client.send(bundle); ``` --- ## Message Represents an OSC message with an address and arguments. OSC messages consist of an address pattern (string starting with '/') and zero or more arguments of various types. ### Message Constructor Creates a new Message instance. **Parameters:** - `address` *{string}* - The OSC address pattern (e.g., '/oscillator/frequency'). - `args` *{*}* - Optional arguments to include in the message. **Examples:** ```javascript // Create a message with constructor arguments const msg = new Message('/test', 1, 2, 'hello'); ``` ```javascript // Create a message and append arguments const msg = new Message('/test'); msg.append(1); msg.append('hello'); msg.append(3.14); ``` ### Message.append() Append an argument to the message. Automatically detects the type based on the JavaScript type: - Integers are encoded as OSC integers - Floats are encoded as OSC floats - Strings are encoded as OSC strings - Booleans are encoded as OSC booleans - Buffers are encoded as OSC blobs - Arrays are recursively appended - Objects with a 'type' property are used as-is **Parameters:** - `arg` *{*}* - The argument to append. Can be: - A primitive value (number, string, boolean) - A Buffer (encoded as blob) - An array of values (will be recursively appended) - An object with 'type' and 'value' properties for explicit type control **Throws:** - *{Error}* - If the argument type cannot be encoded. **Examples:** ```javascript const msg = new Message('/test'); msg.append(42); // Integer msg.append(3.14); // Float msg.append('hello'); // String msg.append(true); // Boolean ``` ```javascript // Append multiple values at once msg.append([1, 2, 3]); ``` ```javascript // Explicitly specify type msg.append({ type: 'float', value: 42 }); msg.append({ type: 'blob', value: Buffer.from('data') }); ``` ```javascript // MIDI messages (4 bytes: port, status, data1, data2) msg.append({ type: 'midi', value: { port: 0, status: 144, data1: 60, data2: 127 } }); msg.append({ type: 'm', value: Buffer.from([0, 144, 60, 127]) }); ``` --- ## Bundle Represents an OSC bundle containing multiple messages or nested bundles. OSC bundles allow multiple messages to be sent together, optionally with a timetag indicating when the bundle should be processed. ### Bundle Constructor Creates a new Bundle instance. **Parameters:** - `timetagOrElement` *{number | Message | Bundle | Array}* (optional) - Timetag, or if not a number, the first element and timetag will default to 0. - `elements` *{Message | Bundle | Array}* - Messages or bundles to include. Arrays will be automatically converted to Message objects. **Examples:** ```javascript // Create a bundle without a timetag const bundle = new Bundle(['/one', 1], ['/two', 2]); ``` ```javascript // Create a bundle with a timetag const bundle = new Bundle(10, ['/one', 1], ['/two', 2]); ``` ```javascript // Nest bundles const bundle1 = new Bundle(['/one', 1]); const bundle2 = new Bundle(['/two', 2]); bundle1.append(bundle2); ``` ### Bundle.append() Append a message or bundle to this bundle. **Parameters:** - `element` *{Message | Bundle | Array}* - The message or bundle to append. Arrays will be automatically converted to Message objects. **Examples:** ```javascript const bundle = new Bundle(); bundle.append(['/test', 1]); bundle.append(new Message('/test2', 2)); ``` ```javascript // Append a nested bundle const bundle1 = new Bundle(['/one', 1]); const bundle2 = new Bundle(['/two', 2]); bundle1.append(bundle2); ``` --- ## Low Level Functions These functions provide low-level access to OSC encoding and decoding for advanced use cases. ### encode() Encode an OSC message or bundle to a Buffer. This low-level function converts OSC messages and bundles into binary format for transmission or storage. Useful for sending OSC over custom transports (WebSocket, TCP, HTTP), storing to files, or implementing custom OSC routers. **Parameters:** - `message` *{Object}* - OSC message or bundle object with oscType property **Returns:** *{Buffer}* - The encoded OSC data ready for transmission **Examples:** ```javascript // Encode a message import { Message, encode } from 'node-osc'; const message = new Message('/oscillator/frequency', 440); const buffer = encode(message); console.log('Encoded bytes:', buffer.length); ``` ```javascript // Encode a bundle import { Bundle, encode } from 'node-osc'; const bundle = new Bundle(['/one', 1], ['/two', 2]); const buffer = encode(bundle); ``` ```javascript // Send over WebSocket const buffer = encode(message); websocket.send(buffer); ``` ### decode() Decode a Buffer containing OSC data into a message or bundle object. This low-level function parses binary OSC data back into JavaScript objects. Useful for receiving OSC over custom transports, reading from files, or implementing custom OSC routers. **Parameters:** - `buffer` *{Buffer}* - The Buffer containing OSC data **Returns:** *{Object}* - The decoded OSC message or bundle. Messages have {oscType: 'message', address: string, args: Array}, bundles have {oscType: 'bundle', timetag: number, elements: Array} **Throws:** - *{Error}* - If the buffer contains malformed OSC data **Examples:** ```javascript // Decode received data import { decode } from 'node-osc'; const decoded = decode(buffer); if (decoded.oscType === 'message') { console.log('Address:', decoded.address); console.log('Arguments:', decoded.args); } ``` ```javascript // Round-trip encode/decode import { Message, encode, decode } from 'node-osc'; const original = new Message('/test', 42, 'hello'); const buffer = encode(original); const decoded = decode(buffer); console.log(decoded.address); // '/test' ```