Get SpatialOS

Sites

Menu

The JavaScript worker SDK is currently experimental. We're very open to feedback --- don't hesitate to get in touch on the forums.

Using the JavaScript worker SDK

Initial setup

To add a JavaScript worker to your project:

  1. Create a directory under workers/ in your SpatialOS project (for example workers/javascript).

  2. Create a new worker configuration file in this directory named spatialos.<your_worker_type>.worker.json - replacing <your_worker_type> with a name of your choice, such as js_worker - and add the following contents:

    {
      "build": {
        "tasks_filename": "spatialos.javascript.build.json",
        "generated_build_scripts_type": "javascript"
      },
      "bridge": {
        "worker_attribute_set": {
          "attributes": [
            "new_worker_attribute"
          ]
        },
        "entity_interest": {
          "range_entity_interest": {
            "radius": 2
          }
        },
        "streaming_query": [],
        "component_delivery": {
          "default": "RELIABLE_ORDERED",
          "checkout_all_initially": true
        }
      }
    }
    

    Note: The provided file uses default build scripts. If you need to customize it further, you can turn off automatic build script generation.

  3. Create an HTML page in the root of your worker directory named index.html containing a <script> tag in the <head> pointing to /worker/<your_directory_name>/resources/build/demo.js, which is the absolute path to the built JavaScript code. For example:

    <html>
    <head>
      <script type="text/javascript" src="/worker/<your_directory_name>/resources/build/demo.js"></script>
    </head>
    <body>
      ...
    </body>
    </html>
    

    Note: Other resources in addition to index.html inside your worker folder need to be accessed with the resources/ endpoint. This is detailed below under Accessing the worker. An absolute path is recommended because a relative path can point to different places depending on the end point used to access index.html.

  4. Create a src directory. This is where you’ll put the source code for the JavaScript worker.

  5. Create a new file in the src directory named index.js (which will act as your entry point). Add a small amount of code which connects to a deployment. Insert the following code to index.js, substituting <your_worker_type> as appropriate in the connection parameters:

    const sdk = require("spatialos_worker_sdk");
    
    
    let locatorParameters = new sdk.LocatorParameters();
    locatorParameters.projectName = "my_project";
    locatorParameters.credentialsType = sdk.LocatorCredentialsType.LOGIN_TOKEN;
    locatorParameters.loginToken = {
      token: sdk.DefaultConfiguration.LOCAL_DEVELOPMENT_LOGIN_TOKEN
    };
    
    
    let workerType = "<your_worker_type>";
    const connectionParameters = new sdk.ConnectionParameters();
    connectionParameters.workerType = workerType;
    
    
    const locator = sdk.Locator.create(sdk.DefaultConfiguration.LOCAL_DEVELOPMENT_LOCATOR_URL, locatorParameters);
    locator.getDeploymentList((err, deploymentList) => {
      locator.connect("my_deployment", connectionParameters, (err, queueStatus) => {
          return true;
        },
        (err, connection) => {
          if (err) {
            console.log("Error when connecting", err);
            return;
          }
          connection.sendLogMessage(sdk.LogLevel.WARN, workerType, "Hello from JavaScript!");
    
    
          let dispatcher = sdk.Dispatcher.create();
          dispatcher.onDisconnect(op => {
            console.log("---> Disconnected", op);
          });
          connection.attachDispatcher(dispatcher);
        });
    });
    
    
    document.addEventListener("DOMContentLoaded", function (event) {
      // Code which depends on the HTML DOM content.
      console.log("Hello World!");
    });
    

    This starter code makes use of the local locator, which currently ignores locatorParameters.projectName and the deployment name in locator.connect(...). After these steps are complete, your directory tree should now look like the following:

    +-- workers/<your_directory_name>
        +-- src
        |   \-- index.js
        |-- index.html
        \-- spatialos.<your_worker_type>.worker.json
    
  6. With the above files in place, run spatial worker build <your_worker_type>. This will create a number of files including a npm package.json and webpack.config.js. These will then be used to create the build/demo.js file as directed by webpack.config.js. More information can be found under Project structure.

  7. Launch a local deployment by running spatial local launch. You can run your worker by visiting localhost:21000/worker/<worker_folder> in the browser. For example, if your worker is inside the workers/js_worker folder in your SpatialOS project, you can run it by visiting localhost:21000/worker/js_worker. More information can be found under Accessing the worker.

Project structure

When using generated build scripts, the following project structure will be generated:

+-- workers/<your_directory_name>
    +-- build               // The directory containing the webpacked script loaded by the HTML page.
    +-- dependencies        // A set of dependencies used by the build (e.g. javascript_sdk and protoc).
    +-- node_modules        // Libraries downloaded by npm, specified in package.json.
    +-- src                 // The source code for your worker.
    |   |-- generated       // Schema-generated code.
    |   \-- index.js        // The script file containing your worker's source code.
    |-- index.html          // The page which loads the webpacked script.
    |-- package.json        // Auto-generated npm configuration.
    |-- spatialos.javascript.build.json // Auto-generated build script used by "spatial worker build"
    |-- spatialos.<your_worker_type>.worker.json
    |-- spatialos_worker_packages.json
    \-- webpack.config.js   // Auto-generated webpack configuration.

Here, npm is configured to use webpack, which will package all your source code into a single JS file called demo.js inside the folder named build.

Running spatial worker build will invoke npm run build inside the worker directory. This will download and install webpack, then will invoke webpack to “compile” the JavaScript code specified in src into the final build/demo.js file, which is loaded by the web page.

Accessing the worker

When a local deployment is launched, a web server is started at localhost:21000. This usually hosts the inspector at localhost:21000/inspector, but also hosts our JavaScript client. There are two endpoints available, which are:

  • localhost:21000/worker/<your_directory_name> - The index.html inside your worker folder. A / can optionally be added to the end of this URL, which will also redirect to index.html.
  • localhost:21000/worker/<your_directory_name>/resources/<path> - This will redirect to any path <path> inside your worker folder. For example: localhost:21000/worker/<your_directory_name>/resources/build/demo.js will serve build/demo.js from your worker folder.

Was this page helpful?

Thanks for letting us know!

Thanks for your feedback

Need more help? Ask on the forums