Example

JS Task API Examples: working with events

Introduction

This example will show you available event types and how to subscribe the certain types of events and extract their details.

Prerequisites

Yagna service is installed and running with the try_golem app-key configured.

How to run examples

Create a project folder, initialize a Node.js project, and install the @golem-sdk/task-executor library.

mkdir golem-example
cd golem-example
npm init
npm i @golem-sdk/task-executor

Copy the code into the index.mjs file in the project folder and run:

node index.mjs

Working with events

You can use events to react to specific actions. The following example shows how to subscribe to different types of events and extract their details.

In the Task Executor context, you can have two types of events:

  • golemEvents that are common for all libraries using golem-js and
  • Task Executor specific events like: taskStarted or taskCompleted.
import { TaskExecutor, pinoPrettyLogger } from "@golem-sdk/task-executor";

(async function main() {
  const executor = await TaskExecutor.create({
    package: "golem/alpine:latest",
    logger: pinoPrettyLogger(),
    taskTimeout: 20 * 60 * 1000, // 20 MIN
    yagnaOptions: { apiKey: "try_golem" },
  });

  // Golem-js core events
  executor.events.on("golemEvents", (event) => {
    console.log(event.name, event.detail);
  });

  // TaskExecutor specific events
  executor.events.on("taskStarted", (event) => {
    console.log("Task started:", event);
  });
  executor.events.on("taskCompleted", (event) => {
    console.log("Task completed:", event);
  });

  console.log("Executor is created");
  try {
    await executor.run(async (ctx) => {
      console.log("Will run the command");
      console.log((await ctx.run("ls -l")).stdout);
    });
    console.log("Finished");
  } catch (err) {
    console.error("This error broke the computations", err);
  } finally {
    console.log("Will shutdown the executor.");
    await executor.shutdown();
  }
})();

The complete list of golemEvents and their documentation is available here.

Was this helpful?