Examples

Once you have Splunk® up and running, you've set up the requirements and installed the SDK, you're ready to get your feet wet with the Splunk SDK for JavaScript examples.

  • Client-side examples run in a web browser against your own instance of Splunk. They range in complexity from simple "Hello, world" examples, to UI examples that use UI controls and visualizations, to a complex example that mimics the core functionality of Splunk.
  • Server-side examples run at the command line. There are simple "Hello, world" examples that use hard-coded parameters, and more complex examples that tackle working with searches, jobs, and configuration files.

 

Example client-side script

The following sample HTML uses the Splunk SDK for JavaScript:

<script type="text/javascript" src="splunk.js"></script>

<script type="text/javascript" charset="utf-8">
    var service = new splunkjs.Service({username: "admin", password: "changeme"});
    service.login(function(err, success) {
        if (err) {
            throw err;
        }
        console.log("Login was successful: " + success);
        service.jobs().fetch(function(err, jobs) {
            var list = jobs.list();
            for(var i = 0; i < list.length; i++) {
                console.log("Job " + i + ": " + list[i].sid);
            } 
        });
    });
</script>

If you want to run multiple instances of the SDK on the same page, or your code is on a page that you don't control, you can use the noConflict() method:

var MySplunk = Splunk.noConflict();

This method returns control of the global Splunk variable to the previous owner, and returns an instance of the SDK to you.

 

Example server-side script

The following shows an example of a script that uses the Splunk SDK for JavaScript:

var splunkjs = require('splunk-sdk');

var service = new splunkjs.Service({username: "admin", password: "changeme"});

service.login(function(err, success) {
    if (err) {
        throw err;
    }
    console.log("Login was successful: " + success);
    service.jobs().fetch(function(err, jobs) {
        var list = jobs.list();
        for(var i = 0; i < list.length; i++) {
            console.log("Job " + i + ": " + list[i].sid);
        } 
    });
});