Diffusion JavaScript Client
The Diffusion JavaScript Client is a comprehensive library for interacting with Diffusion servers (on-premise or Diffusion Cloud) from both browser and Node.js environments. It enables real-time data streaming, pub/sub messaging, and management of topic trees over WebSockets or HTTP. Currently stable at version 6.12.1, the library typically sees regular updates, with minor versions being backward-compatible, while major versions (e.g., v5 to v6) often introduce breaking changes that require client application updates. Key differentiators include its robust support for diverse topic types, built-in TypeScript definitions, and modular bundles for optimized loading, alongside its use of Promises for asynchronous operations. It is designed for applications requiring high-performance, secure, and scalable real-time data distribution infrastructure.
Common errors
-
Failed to connect
cause Incorrect host, port, principal, or credentials provided during `diffusion.connect()`, or the Diffusion server is not running or accessible.fixVerify the `host`, `port`, `principal`, and `credentials` parameters in your `diffusion.connect()` call. Ensure the Diffusion server is running and network accessible. Check server logs for connection attempts and authentication failures. -
Error being thrown (when accessing feature after using modular/diffusion-core.js)
cause Attempting to use a Diffusion client feature (e.g., advanced topic management) that has not been loaded when using the `modular/diffusion-core.js` bundle, which provides only core features like value streams and topic subscription.fixWhen using modular bundles, ensure that all required feature bundles are dynamically loaded *after* the `diffusion-core.js` bundle if you need features beyond basic subscription and value streams. Alternatively, use the full `diffusion.js` bundle if bundle size is not a critical concern. -
SessionError: <error message>
cause A generic error reported asynchronously from a service call, indicating an unexpected server-side condition that the application typically cannot directly recover from.fixLog the `SessionError` details, including the message and any `cause` property. Consult the Diffusion server logs for more information about the underlying issue. It is often appropriate to close the current session and attempt to reconnect.
Warnings
- breaking Upgrading from Diffusion JavaScript client v5.x to v6.x involves significant breaking changes. The 'Classic API' has been entirely removed; applications must migrate to the 'Unified API'. Additionally, several legacy topic types (e.g., Paged string, Paged record, Protocol buffer, Service topics) are no longer supported. Server-side components compiled against older versions may also require recompilation.
- gotcha Client-side message compression via zlib is not included by default in browser bundles to reduce size. If compression is desired in a browser environment, you must explicitly include `browserify-zlib-0.2.0.js` or polyfill zlib (e.g., via `vite-plugin-node-polyfills` in frameworks like Vue/Vite). Node.js environments do not require this, as zlib is a standard module.
- gotcha Topic selectors, which can include regular expressions, may behave differently on the Diffusion client and server due to different underlying regular expression engines. This can lead to unexpected subscription or topic selection behavior.
- gotcha Restarting a Diffusion Cloud service (e.g., for updates or maintenance) results in the loss of all transient topic information (tree structure, topic state) and subscription data. All connected clients are disconnected. While security and authentication information persists, clients must reconnect, re-register handlers, re-create topics, and resubscribe.
- deprecated The `ServerStatisticsConfig` API and related elements in `Statistics.xml` are deprecated and no longer have any function as of Diffusion v6.0.
Install
-
npm install diffusion -
yarn add diffusion -
pnpm add diffusion
Imports
- diffusion
const diffusion = require('diffusion');import * as diffusion from 'diffusion';
- connect
import connect from 'diffusion';
import { connect } from 'diffusion'; - Session
import { Session } from 'diffusion';
Quickstart
import * as diffusion from 'diffusion';
async function runDiffusionClient() {
const host = process.env.DIFFUSION_HOST ?? 'ws://localhost:8080';
const principal = process.env.DIFFUSION_PRINCIPAL ?? 'admin';
const credentials = process.env.DIFFUSION_CREDENTIALS ?? 'password';
const topicPath = 'my/topic/path';
let session: diffusion.Session | undefined;
try {
session = await diffusion.connect({
host: host,
principal: principal,
credentials: credentials,
// secure: true // Uncomment for WSS connections
});
console.log(`Connected to Diffusion server: ${session.sessionId}`);
// Create a value stream for a JSON topic
session.addStream(topicPath, diffusion.datatypes.json()).on(
'value',
(topic, spec, newValue, oldValue) => {
console.log(`Update for ${topic}: ${JSON.stringify(newValue?.get())}`);
}
);
// Subscribe to the topic
await session.select(topicPath);
console.log(`Subscribed to topic: ${topicPath}`);
// Example: Publish a JSON value (requires appropriate permissions on the Diffusion server)
const topicControl = session.topicUpdate.createUpdateContext();
await topicControl.set(
topicPath,
diffusion.datatypes.json(),
diffusion.datatypes.json().newValue({ message: 'Hello, Diffusion!', timestamp: Date.now() })
);
console.log('Published a message to the topic.');
// Keep the session open for a bit to receive updates
await new Promise(resolve => setTimeout(resolve, 10000));
} catch (error: any) {
console.error('Diffusion connection or operation failed:', error.message || error);
} finally {
if (session) {
await session.close();
console.log('Diffusion session closed.');
}
}
}
runDiffusionClient();