Table of Contents
Just a second...

Start publishing with JavaScript

Create a Node.js™ client that publishes data through topics on the Diffusion™ server.

To complete this example, you need a Diffusion server and a development system with Node.js and npm installed on it.

You also require either a named user that has a role with the modify_topic and update_topic permissions. For example, the "ADMINISTRATOR" role. For more information about roles and permissions, see Role-based authorization.

This example steps through the lines of code required to subscribe to a topic. The full code example is provided after the steps.
  1. Install the Diffusion JavaScript® library on your development system.
    npm install diffusion
  2. Create the JavaScript file that will be your publisher.
    For example, publisher.js
    1. Require the Diffusion library.
      var diffusion = require('diffusion');
    2. Connect to the Diffusion server.
      diffusion.connect({
          host : 'host-name',
          principal : 'control-user',
          credentials : 'password'
      }).then(function(session) {
          console.log('Connected!');
      });

      Where host-name is the name of the system that hosts your Diffusion server, control-user is the name of a user with the permissions required to create and update topics, and password is the user's password.

    3. Create a topic called foo/counter and set its initial value to 0.
      session.topics.add('foo/counter', 0);
    4. Every second update the value of the topic with the value of the counter.
          setInterval(function() {
              session.topics.update('foo/counter', ++count);
          }, 1000);
  3. Use Node.js to run your publishing client from the command line.
    node publisher.js
The publisher updates the value of the foo/counter topic every second. You can watch the topic value being updated by subscribing to the topic.
The completed publisher.js file contains the following code:
var diffusion = require('diffusion');

diffusion.connect({
    host : 'hostname',
    principal : 'control-user',
    credentials : 'password'
}).then(function(session) {
    console.log('Connected!');

    var count = 0;
        
    // Create a topic with a default value of 0. 
    session.topics.add('foo/counter', count);
  
    // Start updating the topic every second
    setInterval(function() {
        session.topics.update('foo/counter', ++count);
    }, 1000);
});
Now that you have the outline of a publisher, you can use it to publish your own data instead of a counter.