Use the MQTT.js library with Node.js or in the browser to publish and subscribe using MQTT.
// require npm package
const mqtt = require("mqtt");
// declare client
const client = mqtt.connect("mqtt://public:public@public.cloud.shiftr.io", {
clientId: "javascript",
});
// register "connect" callback
client.on("connect", function () {
console.log("connected!");
// subscribe to topic
client.subscribe("hello");
// publish message every second
setInterval(function () {
client.publish("hello", "world");
}, 1000);
});
// register "message" callback
client.on("message", function (topic, message) {
console.log(topic + ": " + message.toString());
});
For more information see the JavaScript manual in the documentation.