Skip to main content

Hello World Walkthrough in Node

In this tutorial, we'll go over the different components that make up a Temporal project. All of the code on this page is included in our package initializer skeleton, which we set up in Getting started.

The SDK steers developers to write their Workflows and Activities in TypeScript but vanilla JS is also supported.

Activities#

API reference

Activities are called from Workflows in order to run non-deterministic code.

Any async function can be used as an Activity as long as its parameters and return value can be (de)serialized using a DataConverter. Activities run in the Node.js execution environment, they can be cancelled and report heartbeats.

src/activities.ts

export async function greet(name: string): Promise<string> {  return `Hello, ${name}!`;}

Workflows#

API reference

In the Node.js SDK, each Workflow execution is run in a separate V8 isolate context in order to provide a deterministic runtime.

Implementation#

A Workflow implementation exposes handlers for executing the Workflow, processing Signals and responding to Queries.

The snippet below uses createActivityHandle to create functions that, when called, schedule Activities in the system.

src/workflows.ts

import { createActivityHandle } from '@temporalio/workflow';import { Example } from './interfaces';// Only import the activity typesimport type * as activities from './activities';
const { greet } = createActivityHandle<typeof activities>({  startToCloseTimeout: '1 minute',});
/** A workflow that simply calls an activity */export const example: Example = (name: string) => {  return {    async execute(): Promise<string> {      return await greet(name);    },  };};

Type definitions#

Workflow type definitions are optional, they provide type safety in situations where the implementation cannot directly be referenced by a client such as cross service or cross language calls.

src/interfaces.ts

// Define our Example Workflow type (this step is optional).// Workflow types are useful for generating type safe workflow clients// in environments where the Workflow implemetations are unavailable.export type Example = (name: string) => {  execute(): Promise<string>;};

Worker#

API reference

The Worker connects to Temporal Server and runs Workflows and Activities. See the list of WorkerOptions for customizing Worker creation.

src/worker.ts

import { Worker } from '@temporalio/worker';
run().catch((err) => console.log(err));
async function run() {  // Step 1: Automatically locate and register Activities and Workflows relative to __dirname.  const worker = await Worker.create({    workDir: __dirname,    taskQueue: 'tutorial',  });  // // Worker connects to localhost by default and uses console.error for logging.  // // Customize the Worker by passing more options to create():  // // https://nodejs.temporal.io/api/classes/worker.Worker    // // If you need to configure server connection parameters, see the mTLS example:  // // https://github.com/temporalio/samples-node/tree/main/hello-world-mtls      // Step 2: Start accepting tasks on the `tutorial` queue  await worker.run();    // You may create multiple Workers in a single process in order to poll on multiple task queues.}

Client#

API reference

The WorkflowClient class is used to interact with existing Workflows or to start new ones.

It can be used in any Node.js process (for example, an Express web server) and is separate from the Worker.

src/exec-workflow.ts

import { Connection, WorkflowClient } from '@temporalio/client';import { example } from '../workflows';
async function run() {  // Connect to localhost with default ConnectionOptions,  // pass options to the Connection constructor to configure TLS and other settings.  const connection = new Connection();  // Workflows will be started in the "default" namespace unless specified otherwise  // via options passed the WorkflowClient constructor.  const client = new WorkflowClient(connection.service);  // Create a typed handle for the example Workflow.  const handle = client.createWorkflowHandle(example, { taskQueue: 'tutorial' });  const result = await handle.execute('Temporal');  console.log(result); // Hello, Temporal!}
run().catch((err) => {  console.error(err);  process.exit(1);});

Testing#

There is no official test suite for Workflows and Activities yet.

  • Since Activities are async functions, they should be testable as long as you avoid using Context or are able to mock it.
  • You can test Workflows by running them with a WorkflowClient.
  • Check the SDK's own tests for more examples.