Node: Subscribe and publish to subject
Install
npm install nats.ws
npm install websocket
Demo Implementation
-
For node, you need to shim the websocket library. Otherwise, you will get ReferenceError: WebSocket is not defined.
-
Execute:
node wss-subscribe-publish.mjs
// RUN: node wss-subscribe-publish.mjs // Shim is only required if you run this script using node command. // Shim is neither need if this script is called from Nextjs api framework. // Shim the websocket. Otherwise, it will complain ReferenceError: WebSocket is not defined. import w3c from "websocket"; globalThis.WebSocket = w3c.w3cwebsocket; import { connect } from "nats.ws"; async function main() { try { const nc = await connect({ servers: ["wss://rollingweddingpictures.com"] }); console.log(`Connected to ${nc.getServer()}`); const subjectId = "chat.room"; // Example: Subscribe(listen) to a subject const sub = nc.subscribe(subjectId); (async () => { console.log(`Subscribe to ${subjectId}`) for await (const m of sub) { console.log(`Received message: ${m.string()}`); } })(); // Example: Publish(Post) to a subject const dateTime = new Date().toLocaleTimeString(); const message = `${dateTime}: ${subjectId}: Client WSS says: Hello NATS!`; nc.publish(subjectId, message); console.log(`Published to ${subjectId}`); // Clean up: Close everything. await nc.drain(); } catch (_err) { console.log(`error connecting to ${JSON.stringify(_err)}`); } } await main();