Skip to content

Scope

In long-running applications, managing resources efficiently is essential, particularly when building large-scale systems. If resources like socket connections, database connections, or file descriptors are not properly managed, it can lead to resource leaks, which degrade application performance and reliability. Effect provides constructs that help ensure resources are properly managed and released, even in cases where exceptions occur.

By ensuring that every time a resource is acquired, there is a corresponding mechanism to release it, Effect simplifies the process of resource management in your application.

The Scope data type is a core construct in Effect for managing resources in a safe and composable way.

A scope represents the lifetime of one or more resources. When the scope is closed, all the resources within it are released, ensuring that no resources are leaked. Scopes also allow the addition of finalizers, which define how to release resources.

With the Scope data type, you can:

  • Add finalizers: A finalizer specifies the cleanup logic for a resource.
  • Close the scope: When the scope is closed, all resources are released, and the finalizers are executed.

Example (Managing a Scope)

1
import {
import Scope
Scope
,
import Effect
Effect
,
import Console
Console
,
import Exit
Exit
} from "effect"
2
3
const
const program: Effect.Effect<void, never, never>
program
=
4
// create a new scope
5
import Scope
Scope
.
const make: (executionStrategy?: ExecutionStrategy) => Effect.Effect<Scope.CloseableScope>

Creates a new closeable scope where finalizers will run according to the specified `ExecutionStrategy`. If no execution strategy is provided, `sequential` will be used by default.

make
().
(method) Pipeable.pipe<Effect.Effect<Scope.CloseableScope, never, never>, Effect.Effect<Scope.CloseableScope, never, never>, Effect.Effect<Scope.CloseableScope, never, never>, Effect.Effect<...>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>, cd: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
6
// add finalizer 1
7
import Effect
Effect
.
const tap: <Scope.CloseableScope, Effect.Effect<void, never, never>>(f: (a: Scope.CloseableScope) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+7 overloads)
tap
((
(parameter) scope: Scope.CloseableScope
scope
) =>
8
import Scope
Scope
.
const addFinalizer: (self: Scope.Scope, finalizer: Effect.Effect<unknown>) => Effect.Effect<void>

Adds a finalizer to this scope. The finalizer is guaranteed to be run when the scope is closed. Use this when the finalizer does not need to know the `Exit` value that the scope is closed with.

addFinalizer
(
(parameter) scope: Scope.CloseableScope
scope
,
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("finalizer 1"))
9
),
10
// add finalizer 2
11
import Effect
Effect
.
const tap: <Scope.CloseableScope, Effect.Effect<void, never, never>>(f: (a: Scope.CloseableScope) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+7 overloads)
tap
((
(parameter) scope: Scope.CloseableScope
scope
) =>
12
import Scope
Scope
.
const addFinalizer: (self: Scope.Scope, finalizer: Effect.Effect<unknown>) => Effect.Effect<void>

Adds a finalizer to this scope. The finalizer is guaranteed to be run when the scope is closed. Use this when the finalizer does not need to know the `Exit` value that the scope is closed with.

addFinalizer
(
(parameter) scope: Scope.CloseableScope
scope
,
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("finalizer 2"))
13
),
14
// close the scope
15
import Effect
Effect
.
const andThen: <Scope.CloseableScope, Effect.Effect<void, never, never>>(f: (a: Scope.CloseableScope) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action. The `that` action can take various forms: - a value - a function returning a value - a promise - a function returning a promise - an effect - a function returning an effect

andThen
((
(parameter) scope: Scope.CloseableScope
scope
) =>
16
import Scope
Scope
.
const close: (self: Scope.CloseableScope, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>

Closes this scope with the specified exit value, running all finalizers that have been added to the scope.

close
(
(parameter) scope: Scope.CloseableScope
scope
,
import Exit
Exit
.
const succeed: <string>(value: string) => Exit.Exit<string, never>

Constructs a new `Exit.Success` containing the specified value of type `A`.

succeed
("scope closed successfully"))
17
)
18
)
19
20
import Effect
Effect
.
const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<void>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an error.

runPromise
(
const program: Effect.Effect<void, never, never>
program
)
21
/*
22
Output:
23
finalizer 2 <-- finalizers are closed in reverse order
24
finalizer 1
25
*/

In the above example, finalizers are added to the scope, and when the scope is closed, the finalizers are executed in the reverse order.

This reverse order is important because it ensures that resources are released in the correct sequence.

For instance, if you acquire a network connection and then access a file on a remote server, the file must be closed before the network connection to avoid errors.

The Effect.addFinalizer function is a high-level API that allows you to add finalizers to the scope of an effect. A finalizer is a piece of code that is guaranteed to run when the associated scope is closed. The behavior of the finalizer can vary based on the Exit value, which represents how the scope was closed—whether successfully or with an error.

Example (Adding a Finalizer on Success)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Effect<number, never, Scope>
4
const
const program: Effect.Effect<number, never, Scope>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope>>, number>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope>>, number, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
5
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
((
(parameter) exit: Exit<unknown, unknown>
exit
) =>
6
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`Finalizer executed. Exit status: ${
(parameter) exit: Exit<unknown, unknown>
exit
.
(property) _tag: "Success" | "Failure"
_tag
}`)
7
)
8
return 1
9
})
10
11
// Wrapping the effect in a scope
12
const
const runnable: Effect.Effect<number, never, never>
runnable
=
import Effect
Effect
.
const scoped: <number, never, Scope>(effect: Effect.Effect<number, never, Scope>) => Effect.Effect<number, never, never>

Scopes all resources used in this workflow to the lifetime of the workflow, ensuring that their finalizers are run as soon as this workflow completes execution, whether by success, failure, or interruption.

scoped
(
const program: Effect.Effect<number, never, Scope>
program
)
13
// ^? const runnable: Effect<number, never, never>
14
15
Effect.runPromiseExit(runnable).then(console.log)
16
/*
17
Output:
18
Finalizer executed. Exit status: Success
19
{ _id: 'Exit', _tag: 'Success', value: 1 }
20
*/

In this example, we use Effect.addFinalizer to add a finalizer that logs the exit state after the scope is closed. The finalizer will execute when the effect finishes, and it will log whether the effect completed successfully or failed.

The type signature:

const program: Effect<number, never, Scope>

shows that the workflow requires a Scope to run. You can provide this Scope using the Effect.scoped function, which creates a new scope, runs the effect within it, and ensures the finalizers are executed when the scope is closed.

Example (Adding a Finalizer on Failure)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Effect<never, string, Scope>
4
const
const program: Effect.Effect<never, string, Scope>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<never, string, never>> | YieldWrap<Effect.Effect<void, never, Scope>>, never>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
5
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
((
(parameter) exit: Exit<unknown, unknown>
exit
) =>
6
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`Finalizer executed. Exit status: ${
(parameter) exit: Exit<unknown, unknown>
exit
.
(property) _tag: "Success" | "Failure"
_tag
}`)
7
)
8
return yield*
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>
fail
("Uh oh!")
9
})
10
11
// Wrapping the effect in a scope
12
const
const runnable: Effect.Effect<never, string, never>
runnable
=
import Effect
Effect
.
const scoped: <never, string, Scope>(effect: Effect.Effect<never, string, Scope>) => Effect.Effect<never, string, never>

Scopes all resources used in this workflow to the lifetime of the workflow, ensuring that their finalizers are run as soon as this workflow completes execution, whether by success, failure, or interruption.

scoped
(
const program: Effect.Effect<never, string, Scope>
program
)
13
// ^? const runnable: Effect<never, string, never>
14
15
Effect.runPromiseExit(runnable).then(console.log)
16
/*
17
Output:
18
Finalizer executed. Exit status: Failure
19
{
20
_id: 'Exit',
21
_tag: 'Failure',
22
cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' }
23
}
24
*/

In this case, the finalizer is executed even when the effect fails. The log output reflects that the finalizer runs after the failure, and it logs the failure details.

Example (Adding a Finalizer on Interruption)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Effect<never, never, Scope>
4
const
const program: Effect.Effect<never, never, Scope>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope>>, never>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope>>, never, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
5
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
((
(parameter) exit: Exit<unknown, unknown>
exit
) =>
6
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`Finalizer executed. Exit status: ${
(parameter) exit: Exit<unknown, unknown>
exit
.
(property) _tag: "Success" | "Failure"
_tag
}`)
7
)
8
return yield*
import Effect
Effect
.
const interrupt: Effect.Effect<never, never, never>
interrupt
9
})
10
11
// Wrapping the effect in a scope
12
const
const runnable: Effect.Effect<never, never, never>
runnable
=
import Effect
Effect
.
const scoped: <never, never, Scope>(effect: Effect.Effect<never, never, Scope>) => Effect.Effect<never, never, never>

Scopes all resources used in this workflow to the lifetime of the workflow, ensuring that their finalizers are run as soon as this workflow completes execution, whether by success, failure, or interruption.

scoped
(
const program: Effect.Effect<never, never, Scope>
program
)
13
// ^? const runnable: Effect<never, never, never>
14
15
Effect.runPromiseExit(runnable).then(console.log)
16
/*
17
Output:
18
Finalizer executed. Exit status: Failure
19
{
20
_id: 'Exit',
21
_tag: 'Failure',
22
cause: {
23
_id: 'Cause',
24
_tag: 'Interrupt',
25
fiberId: {
26
_id: 'FiberId',
27
_tag: 'Runtime',
28
id: 0,
29
startTimeMillis: ...
30
}
31
}
32
}
33
*/

This example shows how a finalizer behaves when the effect is interrupted. The finalizer runs after the interruption, and the exit status reflects that the effect was stopped mid-execution.

When you’re working with multiple scoped resources within a single operation, it’s important to understand how their scopes interact. By default, these scopes are merged into one, but you can have more fine-grained control over when each scope is closed by manually creating and closing them.

Let’s start by looking at how scopes are merged by default:

Example (Merging Scopes)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
const
const task1: Effect.Effect<void, never, Scope>
task1
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
4
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("task 1")
5
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
(() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("finalizer after task 1"))
6
})
7
8
const
const task2: Effect.Effect<void, never, Scope>
task2
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
9
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("task 2")
10
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
(() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("finalizer after task 2"))
11
})
12
13
const
const program: Effect.Effect<void, never, Scope>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
14
// The scopes of both tasks are merged into one
15
yield*
const task1: Effect.Effect<void, never, Scope>
task1
16
yield*
const task2: Effect.Effect<void, never, Scope>
task2
17
})
18
19
import Effect
Effect
.
const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<void>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an error.

runPromise
(
import Effect
Effect
.
const scoped: <void, never, Scope>(effect: Effect.Effect<void, never, Scope>) => Effect.Effect<void, never, never>

Scopes all resources used in this workflow to the lifetime of the workflow, ensuring that their finalizers are run as soon as this workflow completes execution, whether by success, failure, or interruption.

scoped
(
const program: Effect.Effect<void, never, Scope>
program
))
20
/*
21
Output:
22
task 1
23
task 2
24
finalizer after task 2
25
finalizer after task 1
26
*/

In this case, the scopes of task1 and task2 are merged into a single scope, and when the program is run, it outputs the tasks and their finalizers in a specific order.

If you want more control over when each scope is closed, you can manually create and close them:

Example (Manually Creating and Closing Scopes)

1
import {
import Console
Console
,
import Effect
Effect
,
import Exit
Exit
,
import Scope
Scope
} from "effect"
2
3
const
const task1: Effect.Effect<void, never, Scope.Scope>
task1
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope.Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope.Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
4
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("task 1")
5
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope.Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
(() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("finalizer after task 1"))
6
})
7
8
const
const task2: Effect.Effect<void, never, Scope.Scope>
task2
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope.Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope.Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
9
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("task 2")
10
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope.Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
(() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("finalizer after task 2"))
11
})
12
13
const
const program: Effect.Effect<void, never, never>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
14
const
const scope1: Scope.CloseableScope
scope1
= yield*
import Scope
Scope
.
const make: (executionStrategy?: ExecutionStrategy) => Effect.Effect<Scope.CloseableScope>

Creates a new closeable scope where finalizers will run according to the specified `ExecutionStrategy`. If no execution strategy is provided, `sequential` will be used by default.

make
()
15
const
const scope2: Scope.CloseableScope
scope2
= yield*
import Scope
Scope
.
const make: (executionStrategy?: ExecutionStrategy) => Effect.Effect<Scope.CloseableScope>

Creates a new closeable scope where finalizers will run according to the specified `ExecutionStrategy`. If no execution strategy is provided, `sequential` will be used by default.

make
()
16
17
// Extend the scope of task1 into scope1
18
yield*
const task1: Effect.Effect<void, never, Scope.Scope>
task1
.
(method) Pipeable.pipe<Effect.Effect<void, never, Scope.Scope>, Effect.Effect<void, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, Scope.Scope>) => Effect.Effect<void, never, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Scope
Scope
.
const extend: (scope: Scope.Scope) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope.Scope>> (+1 overload)

Extends the scope of an `Effect` that requires a scope into this scope. It provides this scope to the effect but does not close the scope when the effect completes execution. This allows extending a scoped value into a larger scope.

extend
(
const scope1: Scope.CloseableScope
scope1
))
19
20
// Extend the scope of task2 into scope2
21
yield*
const task2: Effect.Effect<void, never, Scope.Scope>
task2
.
(method) Pipeable.pipe<Effect.Effect<void, never, Scope.Scope>, Effect.Effect<void, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, Scope.Scope>) => Effect.Effect<void, never, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Scope
Scope
.
const extend: (scope: Scope.Scope) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope.Scope>> (+1 overload)

Extends the scope of an `Effect` that requires a scope into this scope. It provides this scope to the effect but does not close the scope when the effect completes execution. This allows extending a scoped value into a larger scope.

extend
(
const scope2: Scope.CloseableScope
scope2
))
22
23
// Manually close scope1 and scope2
24
yield*
import Scope
Scope
.
const close: (self: Scope.CloseableScope, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>

Closes this scope with the specified exit value, running all finalizers that have been added to the scope.

close
(
const scope1: Scope.CloseableScope
scope1
,
import Exit
Exit
.
(alias) const void: Exit.Exit<void, never> export void

Represents an `Exit` which succeeds with `undefined`.

void
)
25
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("doing something else")
26
yield*
import Scope
Scope
.
const close: (self: Scope.CloseableScope, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>

Closes this scope with the specified exit value, running all finalizers that have been added to the scope.

close
(
const scope2: Scope.CloseableScope
scope2
,
import Exit
Exit
.
(alias) const void: Exit.Exit<void, never> export void

Represents an `Exit` which succeeds with `undefined`.

void
)
27
})
28
29
import Effect
Effect
.
const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<void>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an error.

runPromise
(
const program: Effect.Effect<void, never, never>
program
)
30
/*
31
Output:
32
task 1
33
task 2
34
finalizer after task 1
35
finalizer after scope 1
36
doing something else
37
finalizer after task 2
38
*/

In this example, we create two separate scopes, scope1 and scope2, and extend the scope of each task into its respective scope. When you run the program, it outputs the tasks and their finalizers in a different order.

You might wonder what happens when a scope is closed, but a task within that scope hasn’t completed yet. The key point to note is that the scope closing doesn’t force the task to be interrupted.

Example (Closing a Scope with Pending Tasks)

1
import {
import Console
Console
,
import Effect
Effect
,
import Exit
Exit
,
import Scope
Scope
} from "effect"
2
3
const
const task: Effect.Effect<void, never, Scope.Scope>
task
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, Scope.Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, Scope.Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
4
yield*
import Effect
Effect
.
const sleep: (duration: DurationInput) => Effect.Effect<void>

Returns an effect that suspends for the specified duration. This method is asynchronous, and does not actually block the fiber executing the effect.

sleep
("1 second")
5
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Executed")
6
yield*
import Effect
Effect
.
const addFinalizer: <void, never>(finalizer: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, Scope.Scope>

This function adds a finalizer to the scope of the calling `Effect` value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the `Exit` value that the scope is closed with.

addFinalizer
(() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("Task Finalizer"))
7
})
8
9
const
const program: Effect.Effect<void, never, never>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
10
const
const scope: Scope.CloseableScope
scope
= yield*
import Scope
Scope
.
const make: (executionStrategy?: ExecutionStrategy) => Effect.Effect<Scope.CloseableScope>

Creates a new closeable scope where finalizers will run according to the specified `ExecutionStrategy`. If no execution strategy is provided, `sequential` will be used by default.

make
()
11
12
// Close the scope immediately
13
yield*
import Scope
Scope
.
const close: (self: Scope.CloseableScope, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>

Closes this scope with the specified exit value, running all finalizers that have been added to the scope.

close
(
const scope: Scope.CloseableScope
scope
,
import Exit
Exit
.
(alias) const void: Exit.Exit<void, never> export void

Represents an `Exit` which succeeds with `undefined`.

void
)
14
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Scope closed")
15
16
// This task will be executed even if the scope is closed
17
yield*
const task: Effect.Effect<void, never, Scope.Scope>
task
.
(method) Pipeable.pipe<Effect.Effect<void, never, Scope.Scope>, Effect.Effect<void, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, Scope.Scope>) => Effect.Effect<void, never, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Scope
Scope
.
const extend: (scope: Scope.Scope) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope.Scope>> (+1 overload)

Extends the scope of an `Effect` that requires a scope into this scope. It provides this scope to the effect but does not close the scope when the effect completes execution. This allows extending a scoped value into a larger scope.

extend
(
const scope: Scope.CloseableScope
scope
))
18
})
19
20
import Effect
Effect
.
const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<void>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an error.

runPromise
(
const program: Effect.Effect<void, never, never>
program
)
21
/*
22
Output:
23
Scope closed
24
Executed <-- after 1 second
25
Task Finalizer
26
*/

The Effect.acquireRelease(acquire, release) function allows you to define resources that are acquired and safely released when they are no longer needed. This is useful for managing resources such as file handles, database connections, or network sockets.

To use Effect.acquireRelease, you need to define three actions:

  1. Acquiring the Resource: An effect describing the acquisition of the resource, e.g., opening a file or establishing a database connection.
  2. Using the Resource: An effect describing the actual process to produce a result, e.g., reading from the file or querying the database.
  3. Releasing the Resource: The clean-up effect that ensures the resource is properly released, e.g., closing the file or the connection.

The acquisition process is uninterruptible to ensure that partial resource acquisition doesn’t leave your system in an inconsistent state.

The Effect.acquireRelease function guarantees that once a resource is successfully acquired, its release step is always executed when the Scope is closed.

Example (Defining a Simple Resource)

1
import {
import Effect
Effect
} from "effect"
2
3
// Define an interface for a resource
4
interface
interface MyResource
MyResource
{
5
readonly
(property) MyResource.contents: string
contents
: string
6
readonly
(property) MyResource.close: () => Promise<void>
close
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void>
7
}
8
9
// Simulate resource acquisition
10
const
const getMyResource: () => Promise<MyResource>
getMyResource
= ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface MyResource
MyResource
> =>
11
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<{ contents: string; close: () => Promise<void>; }>(value: { contents: string; close: () => Promise<void>; }): Promise<{ contents: string; close: () => Promise<void>; }> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
({
12
(property) contents: string
contents
: "lorem ipsum",
13
(property) close: () => Promise<void>
close
: () =>
14
new
var Promise: PromiseConstructor new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>

Creates a new Promise.

Promise
((
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
) => {
15
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource released")
16
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
()
17
})
18
})
19
20
// Define how the resource is acquired
21
const
const acquire: Effect.Effect<MyResource, Error, never>
acquire
=
import Effect
Effect
.
const tryPromise: <MyResource, Error>(options: { readonly try: (signal: AbortSignal) => PromiseLike<MyResource>; readonly catch: (error: unknown) => Error; }) => Effect.Effect<...> (+1 overload)

Create an `Effect` that when executed will construct `promise` and wait for its result, errors will produce failure as `unknown`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

tryPromise
({
22
(property) try: (signal: AbortSignal) => PromiseLike<MyResource>
try
: () =>
23
const getMyResource: () => Promise<MyResource>
getMyResource
().
(method) Promise<MyResource>.then<MyResource, never>(onfulfilled?: ((value: MyResource) => MyResource | PromiseLike<MyResource>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
((
(parameter) res: MyResource
res
) => {
24
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource acquired")
25
return
(parameter) res: MyResource
res
26
}),
27
(property) catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor new (message?: string) => Error
Error
("getMyResourceError")
28
})
29
30
// Define how the resource is released
31
const
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
= (
(parameter) res: MyResource
res
:
interface MyResource
MyResource
) =>
import Effect
Effect
.
const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

promise
(() =>
(parameter) res: MyResource
res
.
(property) MyResource.close: () => Promise<void>
close
())
32
33
// Create the resource management workflow
34
const
const resource: Effect.Effect<MyResource, Error, Scope>
resource
=
import Effect
Effect
.
const acquireRelease: <MyResource, Error, never, void, never>(acquire: Effect.Effect<MyResource, Error, never>, release: (a: MyResource, exit: Exit<unknown, unknown>) => Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

This function constructs a scoped resource from an `acquire` and `release` `Effect` value. If the `acquire` `Effect` value successfully completes execution, then the `release` `Effect` value will be added to the finalizers associated with the scope of this `Effect` value, and it is guaranteed to be run when the scope is closed. The `acquire` and `release` `Effect` values will be run uninterruptibly. Additionally, the `release` `Effect` value may depend on the `Exit` value specified when the scope is closed.

acquireRelease
(
const acquire: Effect.Effect<MyResource, Error, never>
acquire
,
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
)
35
// ^? const resource: Effect<MyResource, Error, Scope>

In the code above, the Effect.acquireRelease function creates a resource workflow that requires a Scope:

const resource: Effect<MyResource, Error, Scope>

This means that the workflow needs a Scope to run, and the resource will automatically be released when the scope is closed.

You can now use the resource by chaining operations using Effect.andThen or similar functions.

We can continue working with the resource for as long as we want by using Effect.andThen or other Effect operators. For example, here’s how we can read the contents:

Example (Using the Resource)

1
import {
import Effect
Effect
} from "effect"
2
32 collapsed lines
3
// Define an interface for a resource
4
interface
interface MyResource
MyResource
{
5
readonly
(property) MyResource.contents: string
contents
: string
6
readonly
(property) MyResource.close: () => Promise<void>
close
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void>
7
}
8
9
// Simulate resource acquisition
10
const
const getMyResource: () => Promise<MyResource>
getMyResource
= ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface MyResource
MyResource
> =>
11
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<{ contents: string; close: () => Promise<void>; }>(value: { contents: string; close: () => Promise<void>; }): Promise<{ contents: string; close: () => Promise<void>; }> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
({
12
(property) contents: string
contents
: "lorem ipsum",
13
(property) close: () => Promise<void>
close
: () =>
14
new
var Promise: PromiseConstructor new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>

Creates a new Promise.

Promise
((
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
) => {
15
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource released")
16
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
()
17
})
18
})
19
20
// Define how the resource is acquired
21
const
const acquire: Effect.Effect<MyResource, Error, never>
acquire
=
import Effect
Effect
.
const tryPromise: <MyResource, Error>(options: { readonly try: (signal: AbortSignal) => PromiseLike<MyResource>; readonly catch: (error: unknown) => Error; }) => Effect.Effect<...> (+1 overload)

Create an `Effect` that when executed will construct `promise` and wait for its result, errors will produce failure as `unknown`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

tryPromise
({
22
(property) try: (signal: AbortSignal) => PromiseLike<MyResource>
try
: () =>
23
const getMyResource: () => Promise<MyResource>
getMyResource
().
(method) Promise<MyResource>.then<MyResource, never>(onfulfilled?: ((value: MyResource) => MyResource | PromiseLike<MyResource>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
((
(parameter) res: MyResource
res
) => {
24
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource acquired")
25
return
(parameter) res: MyResource
res
26
}),
27
(property) catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor new (message?: string) => Error
Error
("getMyResourceError")
28
})
29
30
// Define how the resource is released
31
const
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
= (
(parameter) res: MyResource
res
:
interface MyResource
MyResource
) =>
import Effect
Effect
.
const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

promise
(() =>
(parameter) res: MyResource
res
.
(property) MyResource.close: () => Promise<void>
close
())
32
33
// Create the resource management workflow
34
const
const resource: Effect.Effect<MyResource, Error, Scope>
resource
=
import Effect
Effect
.
const acquireRelease: <MyResource, Error, never, void, never>(acquire: Effect.Effect<MyResource, Error, never>, release: (a: MyResource, exit: Exit<unknown, unknown>) => Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

This function constructs a scoped resource from an `acquire` and `release` `Effect` value. If the `acquire` `Effect` value successfully completes execution, then the `release` `Effect` value will be added to the finalizers associated with the scope of this `Effect` value, and it is guaranteed to be run when the scope is closed. The `acquire` and `release` `Effect` values will be run uninterruptibly. Additionally, the `release` `Effect` value may depend on the `Exit` value specified when the scope is closed.

acquireRelease
(
const acquire: Effect.Effect<MyResource, Error, never>
acquire
,
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
)
35
36
// Effect<void, Error, Scope>
37
const
const program: Effect.Effect<void, Error, Scope>
program
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<MyResource, Error, Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<MyResource, Error, Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
38
const
const res: MyResource
res
= yield*
const resource: Effect.Effect<MyResource, Error, Scope>
resource
39
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(`content is ${
const res: MyResource
res
.
(property) MyResource.contents: string
contents
}`)
40
})

To ensure proper resource management, the Scope should be closed when you’re done with the resource. The Effect.scoped function handles this for you by creating a Scope, running the effect, and then closing the Scope when the effect finishes.

Example (Providing the Scope with Effect.scoped)

1
import {
import Effect
Effect
} from "effect"
2
32 collapsed lines
3
// Define an interface for a resource
4
interface
interface MyResource
MyResource
{
5
readonly
(property) MyResource.contents: string
contents
: string
6
readonly
(property) MyResource.close: () => Promise<void>
close
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void>
7
}
8
9
// Simulate resource acquisition
10
const
const getMyResource: () => Promise<MyResource>
getMyResource
= ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface MyResource
MyResource
> =>
11
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<{ contents: string; close: () => Promise<void>; }>(value: { contents: string; close: () => Promise<void>; }): Promise<{ contents: string; close: () => Promise<void>; }> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
({
12
(property) contents: string
contents
: "lorem ipsum",
13
(property) close: () => Promise<void>
close
: () =>
14
new
var Promise: PromiseConstructor new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>

Creates a new Promise.

Promise
((
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
) => {
15
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource released")
16
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
()
17
})
18
})
19
20
// Define how the resource is acquired
21
const
const acquire: Effect.Effect<MyResource, Error, never>
acquire
=
import Effect
Effect
.
const tryPromise: <MyResource, Error>(options: { readonly try: (signal: AbortSignal) => PromiseLike<MyResource>; readonly catch: (error: unknown) => Error; }) => Effect.Effect<...> (+1 overload)

Create an `Effect` that when executed will construct `promise` and wait for its result, errors will produce failure as `unknown`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

tryPromise
({
22
(property) try: (signal: AbortSignal) => PromiseLike<MyResource>
try
: () =>
23
const getMyResource: () => Promise<MyResource>
getMyResource
().
(method) Promise<MyResource>.then<MyResource, never>(onfulfilled?: ((value: MyResource) => MyResource | PromiseLike<MyResource>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
((
(parameter) res: MyResource
res
) => {
24
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource acquired")
25
return
(parameter) res: MyResource
res
26
}),
27
(property) catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor new (message?: string) => Error
Error
("getMyResourceError")
28
})
29
30
// Define how the resource is released
31
const
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
= (
(parameter) res: MyResource
res
:
interface MyResource
MyResource
) =>
import Effect
Effect
.
const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

promise
(() =>
(parameter) res: MyResource
res
.
(property) MyResource.close: () => Promise<void>
close
())
32
33
// Create the resource management workflow
34
const
const resource: Effect.Effect<MyResource, Error, Scope>
resource
=
import Effect
Effect
.
const acquireRelease: <MyResource, Error, never, void, never>(acquire: Effect.Effect<MyResource, Error, never>, release: (a: MyResource, exit: Exit<unknown, unknown>) => Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

This function constructs a scoped resource from an `acquire` and `release` `Effect` value. If the `acquire` `Effect` value successfully completes execution, then the `release` `Effect` value will be added to the finalizers associated with the scope of this `Effect` value, and it is guaranteed to be run when the scope is closed. The `acquire` and `release` `Effect` values will be run uninterruptibly. Additionally, the `release` `Effect` value may depend on the `Exit` value specified when the scope is closed.

acquireRelease
(
const acquire: Effect.Effect<MyResource, Error, never>
acquire
,
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
)
35
36
// Effect<void, Error, never>
37
const
const program: Effect.Effect<void, Error, never>
program
=
import Effect
Effect
.
const scoped: <void, Error, Scope>(effect: Effect.Effect<void, Error, Scope>) => Effect.Effect<void, Error, never>

Scopes all resources used in this workflow to the lifetime of the workflow, ensuring that their finalizers are run as soon as this workflow completes execution, whether by success, failure, or interruption.

scoped
(
38
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<MyResource, Error, Scope>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<MyResource, Error, Scope>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
39
const
const res: MyResource
res
= yield*
const resource: Effect.Effect<MyResource, Error, Scope>
resource
40
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(`content is ${
const res: MyResource
res
.
(property) MyResource.contents: string
contents
}`)
41
})
42
)
43
44
// We now have a workflow that is ready to run
45
import Effect
Effect
.
const runPromise: <void, Error>(effect: Effect.Effect<void, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<void>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an error.

runPromise
(
const program: Effect.Effect<void, Error, never>
program
)
46
/*
47
Resource acquired
48
content is lorem ipsum
49
Resource released
50
*/

The Effect.acquireUseRelease function is a specialized version of the Effect.acquireRelease function that simplifies resource management by automatically handling the scoping of resources.

Effect.acquireUseRelease(acquire, use, release)

The main difference is that Effect.acquireUseRelease eliminates the need to manually call Effect.scoped to manage the resource’s scope. It has additional knowledge about when you are done using the resource created with the acquire step. This is achieved by providing a use argument, which represents the function that operates on the acquired resource. As a result, Effect.acquireUseRelease can automatically determine when it should execute the release step.

Example

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
29 collapsed lines
3
// Define an interface for a resource
4
interface
interface MyResource
MyResource
{
5
readonly
(property) MyResource.contents: string
contents
: string
6
readonly
(property) MyResource.close: () => Promise<void>
close
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void>
7
}
8
9
// Simulate resource acquisition
10
const
const getMyResource: () => Promise<MyResource>
getMyResource
= ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface MyResource
MyResource
> =>
11
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<{ contents: string; close: () => Promise<void>; }>(value: { contents: string; close: () => Promise<void>; }): Promise<{ contents: string; close: () => Promise<void>; }> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
({
12
(property) contents: string
contents
: "lorem ipsum",
13
(property) close: () => Promise<void>
close
: () =>
14
new
var Promise: PromiseConstructor new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>

Creates a new Promise.

Promise
((
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
) => {
15
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource released")
16
(parameter) resolve: (value: void | PromiseLike<void>) => void
resolve
()
17
})
18
})
19
20
// Define how the resource is acquired
21
const
const acquire: Effect.Effect<MyResource, Error, never>
acquire
=
import Effect
Effect
.
const tryPromise: <MyResource, Error>(options: { readonly try: (signal: AbortSignal) => PromiseLike<MyResource>; readonly catch: (error: unknown) => Error; }) => Effect.Effect<...> (+1 overload)

Create an `Effect` that when executed will construct `promise` and wait for its result, errors will produce failure as `unknown`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

tryPromise
({
22
(property) try: (signal: AbortSignal) => PromiseLike<MyResource>
try
: () =>
23
const getMyResource: () => Promise<MyResource>
getMyResource
().
(method) Promise<MyResource>.then<MyResource, never>(onfulfilled?: ((value: MyResource) => MyResource | PromiseLike<MyResource>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
((
(parameter) res: MyResource
res
) => {
24
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
("Resource acquired")
25
return
(parameter) res: MyResource
res
26
}),
27
(property) catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor new (message?: string) => Error
Error
("getMyResourceError")
28
})
29
30
// Define how the resource is released
31
const
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
= (
(parameter) res: MyResource
res
:
interface MyResource
MyResource
) =>
import Effect
Effect
.
const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

promise
(() =>
(parameter) res: MyResource
res
.
(property) MyResource.close: () => Promise<void>
close
())
32
33
const
const use: (res: MyResource) => Effect.Effect<void, never, never>
use
= (
(parameter) res: MyResource
res
:
interface MyResource
MyResource
) =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`content is ${
(parameter) res: MyResource
res
.
(property) MyResource.contents: string
contents
}`)
34
35
const
const program: Effect.Effect<void, Error, never>
program
=
import Effect
Effect
.
const acquireUseRelease: <MyResource, Error, never, void, never, never, void, never>(acquire: Effect.Effect<MyResource, Error, never>, use: (a: MyResource) => Effect.Effect<...>, release: (a: MyResource, exit: Exit<...>) => Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

This function is used to ensure that an `Effect` value that represents the acquisition of a resource (for example, opening a file, launching a thread, etc.) will not be interrupted, and that the resource will always be released when the `Effect` value completes execution. `acquireUseRelease` does the following: 1. Ensures that the `Effect` value that acquires the resource will not be interrupted. Note that acquisition may still fail due to internal reasons (such as an uncaught exception). 2. Ensures that the `release` `Effect` value will not be interrupted, and will be executed as long as the acquisition `Effect` value successfully acquires the resource. During the time period between the acquisition and release of the resource, the `use` `Effect` value will be executed. If the `release` `Effect` value fails, then the entire `Effect` value will fail, even if the `use` `Effect` value succeeds. If this fail-fast behavior is not desired, errors produced by the `release` `Effect` value can be caught and ignored.

acquireUseRelease
(
const acquire: Effect.Effect<MyResource, Error, never>
acquire
,
const use: (res: MyResource) => Effect.Effect<void, never, never>
use
,
const release: (res: MyResource) => Effect.Effect<void, never, never>
release
)
36
37
import Effect
Effect
.
const runPromise: <void, Error>(effect: Effect.Effect<void, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<void>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an error.

runPromise
(
const program: Effect.Effect<void, Error, never>
program
)
38
/*
39
Output:
40
Resource acquired
41
content is lorem ipsum
42
Resource released
43
*/