Skip to content

Creating Streams

In this section, we’ll explore various methods for creating Effect Streams. These methods will help you generate streams tailored to your needs.

You can create a pure stream by using the Stream.make constructor. This constructor accepts a variable list of values as its arguments.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>

Creates a stream from an sequence of values.

make
(1, 2, 3)
4
5
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
6
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

Sometimes, you may require a stream that doesn’t produce any values. In such cases, you can use Stream.empty. This constructor creates a stream that remains empty.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const stream: Stream.Stream<never, never, never>
stream
=
import Stream
Stream
.
const empty: Stream.Stream<never, never, never>

The empty stream.

empty
4
5
import Effect
Effect
.
const runPromise: <Chunk<never>, never>(effect: Effect.Effect<Chunk<never>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<never>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <never, never, never>(self: Stream.Stream<never, never, never>) => Effect.Effect<Chunk<never>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<never, never, never>
stream
)).
(method) Promise<Chunk<never>>.then<void, never>(onfulfilled?: ((value: Chunk<never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
6
// { _id: 'Chunk', values: [] }

If you need a stream that contains a single void value, you can use Stream.void. This constructor is handy when you want to represent a stream with a single event or signal.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
(alias) const void: Stream.Stream<void, never, never> export void

A stream that contains a single `void` value.

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

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
)).
(method) Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<void>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
6
// { _id: 'Chunk', values: [ undefined ] }

To create a stream of integers within a specified range [min, max] (including both endpoints, min and max), you can use Stream.range. This is particularly useful for generating a stream of sequential numbers.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
// Creating a stream of numbers from 1 to 5
4
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const range: (min: number, max: number, chunkSize?: number) => Stream.Stream<number>

Constructs a stream from a range of integers, including both endpoints.

range
(1, 5)
5
6
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
7
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

With Stream.iterate, you can generate a stream by applying a function iteratively to an initial value. The initial value becomes the first element produced by the stream, followed by subsequent values produced by f(init), f(f(init)), and so on.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
// Creating a stream of incrementing numbers
4
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const iterate: <number>(value: number, next: (value: number) => number) => Stream.Stream<number, never, never>

The infinite stream of iterative function application: a, f(a), f(f(a)), f(f(f(a))), ...

iterate
(1, (
(parameter) n: number
n
) =>
(parameter) n: number
n
+ 1) // Produces 1, 2, 3, ...
5
6
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
7
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
8
)
9
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

Stream.scoped is used to create a single-valued stream from a scoped resource. It can be handy when dealing with resources that require explicit acquisition, usage, and release.

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Creating a single-valued stream from a scoped resource
4
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
const scoped: <void, never, never>(effect: Effect.Effect<void, never, never>) => Stream.Stream<void, never, never>

Creates a single-valued stream from a scoped resource.

scoped
(
5
import Effect
Effect
.
const acquireUseRelease: <void, never, never, void, never, never, void, never>(acquire: Effect.Effect<void, never, never>, use: (a: void) => Effect.Effect<void, never, never>, release: (a: void, exit: Exit<void, never>) => 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
(
6
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("acquire"),
7
() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("use"),
8
() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("release")
9
)
10
)
11
12
import Effect
Effect
.
const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<void>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
)).
(method) Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<void>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
13
/*
14
Output:
15
acquire
16
use
17
release
18
{ _id: 'Chunk', values: [ undefined ] }
19
*/

Much like the Effect data type, you can generate a Stream using the fail and succeed functions:

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
// Creating a stream that can emit errors
4
const
const streamWithError: Stream.Stream<never, string, never>
streamWithError
:
import Stream
Stream
.
interface Stream<out A, out E = never, out R = never> namespace Stream

A `Stream<A, E, R>` is a description of a program that, when evaluated, may emit zero or more values of type `A`, may fail with errors of type `E`, and uses an context of type `R`. One way to think of `Stream` is as a `Effect` program that could emit multiple values. `Stream` is a purely functional *pull* based stream. Pull based streams offer inherent laziness and backpressure, relieving users of the need to manage buffers between operators. As an optimization, `Stream` does not emit single values, but rather an array of values. This allows the cost of effect evaluation to be amortized. `Stream` forms a monad on its `A` type parameter, and has error management facilities for its `E` type parameter, modeled similarly to `Effect` (with some adjustments for the multiple-valued nature of `Stream`). These aspects allow for rich and expressive composition of streams.

Stream
<never, string> =
5
import Stream
Stream
.
const fail: <string>(error: string) => Stream.Stream<never, string, never>

Terminates with the specified error.

fail
("Uh oh!")
6
7
import Effect
Effect
.
const runPromise: <Chunk<never>, string>(effect: Effect.Effect<Chunk<never>, string, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<never>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <never, string, never>(self: Stream.Stream<never, string, never>) => Effect.Effect<Chunk<never>, string, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const streamWithError: Stream.Stream<never, string, never>
streamWithError
))
8
// throws Error: Uh oh!
9
10
// Creating a stream that emits a numeric value
11
const
const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber
:
import Stream
Stream
.
interface Stream<out A, out E = never, out R = never> namespace Stream

A `Stream<A, E, R>` is a description of a program that, when evaluated, may emit zero or more values of type `A`, may fail with errors of type `E`, and uses an context of type `R`. One way to think of `Stream` is as a `Effect` program that could emit multiple values. `Stream` is a purely functional *pull* based stream. Pull based streams offer inherent laziness and backpressure, relieving users of the need to manage buffers between operators. As an optimization, `Stream` does not emit single values, but rather an array of values. This allows the cost of effect evaluation to be amortized. `Stream` forms a monad on its `A` type parameter, and has error management facilities for its `E` type parameter, modeled similarly to `Effect` (with some adjustments for the multiple-valued nature of `Stream`). These aspects allow for rich and expressive composition of streams.

Stream
<number> =
import Stream
Stream
.
const succeed: <number>(value: number) => Stream.Stream<number, never, never>

Creates a single-valued pure stream.

succeed
(5)
12
13
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
14
// { _id: 'Chunk', values: [ 5 ] }

You can construct a stream from a Chunk like this:

1
import {
import Stream
Stream
,
import Chunk
Chunk
,
import Effect
Effect
} from "effect"
2
3
// Creating a stream with values from a single Chunk
4
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromChunk: <number>(chunk: Chunk.Chunk<number>) => Stream.Stream<number, never, never>

Creates a stream from a `Chunk` of values.

fromChunk
(
import Chunk
Chunk
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>

Builds a `NonEmptyChunk` from an non-empty collection of elements.

make
(1, 2, 3))
5
6
import Effect
Effect
.
const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
7
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

Moreover, you can create a stream from multiple Chunks as well:

1
import {
import Stream
Stream
,
import Chunk
Chunk
,
import Effect
Effect
} from "effect"
2
3
// Creating a stream with values from multiple Chunks
4
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromChunks: <number>(...chunks: Chunk.Chunk<number>[]) => Stream.Stream<number, never, never>

Creates a stream from an arbitrary number of chunks.

fromChunks
(
import Chunk
Chunk
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>

Builds a `NonEmptyChunk` from an non-empty collection of elements.

make
(1, 2, 3),
import Chunk
Chunk
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>

Builds a `NonEmptyChunk` from an non-empty collection of elements.

make
(4, 5, 6))
5
6
import Effect
Effect
.
const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
7
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }

You can generate a stream from an Effect workflow by employing the Stream.fromEffect constructor. For instance, consider the following stream, which generates a single random number:

1
import {
import Stream
Stream
,
import Random
Random
,
import Effect
Effect
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromEffect: <number, never, never>(effect: Effect.Effect<number, never, never>) => Stream.Stream<number, never, never>

Either emits the success value of this effect or terminates the stream with the failure value of this effect.

fromEffect
(
import Random
Random
.
const nextInt: Effect.Effect<number, never, never>

Returns the next integer value from the pseudo-random number generator.

nextInt
)
4
5
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
6
// Example Output: { _id: 'Chunk', values: [ 1042302242 ] }

This method allows you to seamlessly transform the output of an Effect into a stream, providing a straightforward way to work with asynchronous operations within your streams.

Imagine you have an asynchronous function that relies on callbacks. If you want to capture the results emitted by those callbacks as a stream, you can use the Stream.async function. This function is designed to adapt functions that invoke their callbacks multiple times and emit the results as a stream.

Let’s break down how to use it in the following example:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Chunk
Chunk
,
import Option
Option
,
import StreamEmit
StreamEmit
} from "effect"
2
3
const
const events: number[]
events
= [1, 2, 3, 4]
4
5
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
(alias) async<number, never, never>(register: (emit: StreamEmit.Emit<never, never, number, void>) => void | Effect.Effect<void, never, never>, bufferSize?: number | "unbounded" | { readonly bufferSize?: number | undefined; readonly strategy?: "dropping" | "sliding" | "suspend" | undefined; } | undefined): Stream.Stream<...> export async

Creates a stream from an asynchronous callback that can be called multiple times. The optionality of the error type `E` in `Emit` can be used to signal the end of the stream by setting it to `None`. The registration function can optionally return an `Effect`, which will be executed if the `Fiber` executing this Effect is interrupted.

async
(
6
(
(parameter) emit: StreamEmit.Emit<never, never, number, void>
emit
:
import StreamEmit
StreamEmit
.
interface Emit<in R, in E, in A, out B>

An `Emit<R, E, A, B>` represents an asynchronous callback that can be called multiple times. The callback can be called with a value of type `Effect<Chunk<A>, Option<E>, R>`, where succeeding with a `Chunk<A>` indicates to emit those elements, failing with `Some<E>` indicates to terminate with that error, and failing with `None` indicates to terminate with an end of stream signal.

Emit
<never, never, number, void>) => {
7
const events: number[]
events
.
(method) Array<number>.forEach(callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

forEach
((
(parameter) n: number
n
) => {
8
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload) namespace setTimeout

Schedules execution of a one-time `callback` after `delay` milliseconds. The `callback` will likely not be invoked in precisely `delay` milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified. When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. If `callback` is not a function, a `TypeError` will be thrown. This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.

setTimeout
(() => {
9
if (
(parameter) n: number
n
=== 3) {
10
// Terminate the stream
11
(parameter) emit: StreamEmit.Emit (f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit
(
import Effect
Effect
.
const fail: <Option.Option<never>>(error: Option.Option<never>) => Effect.Effect<never, Option.Option<never>, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
()))
12
} else {
13
// Add the current item to the stream
14
(parameter) emit: StreamEmit.Emit (f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit
(
import Effect
Effect
.
const succeed: <Chunk.NonEmptyChunk<number>>(value: Chunk.NonEmptyChunk<number>) => Effect.Effect<Chunk.NonEmptyChunk<number>, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
import Chunk
Chunk
.
const of: <number>(a: number) => Chunk.NonEmptyChunk<number>

Builds a `NonEmptyChunk` from a single element.

of
(
(parameter) n: number
n
)))
15
}
16
}, 100 *
(parameter) n: number
n
)
17
})
18
}
19
)
20
21
import Effect
Effect
.
const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
22
// { _id: 'Chunk', values: [ 1, 2 ] }

The StreamEmit.Emit<R, E, A, void> type represents an asynchronous callback that can be called multiple times. This callback takes a value of type Effect<Chunk<A>, Option<E>, R>. Here’s what each of the possible outcomes means:

  • When the value provided to the callback results in a Chunk<A> upon success, it signifies that the specified elements should be emitted as part of the stream.

  • If the value passed to the callback results in a failure with Some<E>, it indicates the termination of the stream with the specified error.

  • When the value passed to the callback results in a failure with None, it serves as a signal for the end of the stream, essentially terminating it.

To put it simply, this type allows you to specify how your asynchronous callback interacts with the stream, determining when to emit elements, when to terminate with an error, or when to signal the end of the stream.

You can create a pure stream from an Iterable of values using the Stream.fromIterable constructor. It’s a straightforward way to convert a collection of values into a stream.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const numbers: number[]
numbers
= [1, 2, 3]
4
5
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromIterable: <number>(iterable: Iterable<number>) => Stream.Stream<number, never, never>

Creates a new `Stream` from an iterable collection of values.

fromIterable
(
const numbers: number[]
numbers
)
6
7
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
8
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

When you have an effect that produces a value of type Iterable, you can employ the Stream.fromIterableEffect constructor to generate a stream from that effect.

For instance, let’s say you have a database operation that retrieves a list of users. Since this operation involves effects, you can utilize Stream.fromIterableEffect to convert the result into a Stream:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Context
Context
} from "effect"
2
3
class
class Database
Database
extends
import Context
Context
.
const Tag: <"Database">(id: "Database") => <Self, Shape>() => Context.TagClass<Self, "Database", Shape> namespace Tag
Tag
("Database")<
4
class Database
Database
,
5
{ readonly
(property) getUsers: Effect.Effect<string[], never, never>
getUsers
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<
interface Array<T>
Array
<string>> }
6
>() {}
7
8
const
const getUsers: Effect.Effect<string[], never, Database>
getUsers
=
class Database
Database
.
(method) Pipeable.pipe<typeof Database, Effect.Effect<string[], never, Database>>(this: typeof Database, ab: (_: typeof Database) => Effect.Effect<string[], never, Database>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const andThen: <{ readonly getUsers: Effect.Effect<Array<string>>; }, Effect.Effect<string[], never, never>>(f: (a: { readonly getUsers: Effect.Effect<Array<string>>; }) => Effect.Effect<string[], 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) _: { readonly getUsers: Effect.Effect<Array<string>>; }
_
) =>
(parameter) _: { readonly getUsers: Effect.Effect<Array<string>>; }
_
.
(property) getUsers: Effect.Effect<string[], never, never>
getUsers
))
9
10
const
const stream: Stream.Stream<string, never, Database>
stream
=
import Stream
Stream
.
const fromIterableEffect: <string, never, Database>(effect: Effect.Effect<Iterable<string>, never, Database>) => Stream.Stream<string, never, Database>

Creates a stream from an effect producing a value of type `Iterable<A>`.

fromIterableEffect
(
const getUsers: Effect.Effect<string[], never, Database>
getUsers
)
11
12
import Effect
Effect
.
const runPromise: <Chunk<string>, never>(effect: Effect.Effect<Chunk<string>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<string>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
13
import Stream
Stream
.
const runCollect: <string, never, never>(self: Stream.Stream<string, never, never>) => Effect.Effect<Chunk<string>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
14
const stream: Stream.Stream<string, never, Database>
stream
.
(method) Pipeable.pipe<Stream.Stream<string, never, Database>, Stream.Stream<string, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, Database>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe
(
15
import Stream
Stream
.
const provideService: <typeof Database>(tag: typeof Database, resource: { readonly getUsers: Effect.Effect<Array<string>>; }) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<...> (+1 overload)

Provides the stream with the single service it requires. If the stream requires more than one service use `Stream.provideContext` instead.

provideService
(
class Database
Database
, {
16
(property) getUsers: Effect.Effect<string[], never, never>
getUsers
:
import Effect
Effect
.
const succeed: <string[]>(value: string[]) => Effect.Effect<string[], never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(["user1", "user2"])
17
})
18
)
19
)
20
).
(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
21
// { _id: 'Chunk', values: [ 'user1', 'user2' ] }

This enables you to work seamlessly with effects and convert their results into streams for further processing.

Async iterables are another type of data source that can be converted into a stream. With the Stream.fromAsyncIterable constructor, you can work with asynchronous data sources and handle potential errors gracefully.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const myAsyncIterable: () => AsyncGenerator<1 | 2, void, unknown>
myAsyncIterable
= async function* () {
4
yield 1
5
yield 2
6
}
7
8
const
const stream: Stream.Stream<1 | 2, Error, never>
stream
=
import Stream
Stream
.
const fromAsyncIterable: <1 | 2, Error>(iterable: AsyncIterable<1 | 2>, onError: (e: unknown) => Error) => Stream.Stream<1 | 2, Error, never>

Creates a stream from an `AsyncIterable`.

fromAsyncIterable
(
9
const myAsyncIterable: () => AsyncGenerator<1 | 2, void, unknown>
myAsyncIterable
(),
10
(
(parameter) e: unknown
e
) => new
var Error: ErrorConstructor new (message?: string) => Error
Error
(
var String: StringConstructor (value?: any) => string

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

String
(
(parameter) e: unknown
e
)) // Error Handling
11
)
12
13
import Effect
Effect
.
const runPromise: <Chunk<1 | 2>, Error>(effect: Effect.Effect<Chunk<1 | 2>, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <1 | 2, Error, never>(self: Stream.Stream<1 | 2, Error, never>) => Effect.Effect<Chunk<1 | 2>, Error, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<1 | 2, Error, never>
stream
)).
(method) Promise<Chunk<1 | 2>>.then<void, never>(onfulfilled?: ((value: Chunk<1 | 2>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
14
// { _id: 'Chunk', values: [ 1, 2 ] }

In this code, we define an async iterable and then create a stream named stream from it. Additionally, we provide an error handler function to manage any potential errors that may occur during the conversion.

You can create a stream that endlessly repeats a specific value using the Stream.repeatValue constructor:

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const repeatValue: <number>(value: number) => Stream.Stream<number, never, never>

Repeats the provided value infinitely.

repeatValue
(0)
4
5
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
6
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
7
)
8
// { _id: 'Chunk', values: [ 0, 0, 0, 0, 0 ] }

Stream.repeat allows you to create a stream that repeats a specified stream’s content according to a schedule. This can be useful for generating recurring events or values.

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Schedule
Schedule
} from "effect"
2
3
// Creating a stream that repeats a value indefinitely
4
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const repeat: <number, never, never, number, never>(self: Stream.Stream<number, never, never>, schedule: Schedule.Schedule<number, unknown, never>) => Stream.Stream<number, never, never> (+1 overload)

Repeats the entire stream using the specified schedule. The stream will execute normally, and then repeat again according to the provided schedule.

repeat
(
import Stream
Stream
.
const succeed: <number>(value: number) => Stream.Stream<number, never, never>

Creates a single-valued pure stream.

succeed
(1),
import Schedule
Schedule
.
const forever: Schedule.Schedule<number, unknown, never>

A schedule that always recurs, producing a count of repeats: 0, 1, 2.

forever
)
5
6
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
7
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
8
)
9
// { _id: 'Chunk', values: [ 1, 1, 1, 1, 1 ] }

Imagine you have an effectful API call, and you want to use the result of that call to create a stream. You can achieve this by creating a stream from the effect and repeating it indefinitely.

Here’s an example of generating a stream of random numbers:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Random
Random
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const repeatEffect: <number, never, never>(effect: Effect.Effect<number, never, never>) => Stream.Stream<number, never, never>

Creates a stream from an effect producing a value of type `A` which repeats forever.

repeatEffect
(
import Random
Random
.
const nextInt: Effect.Effect<number, never, never>

Returns the next integer value from the pseudo-random number generator.

nextInt
)
4
5
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
6
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
7
)
8
/*
9
Example Output:
10
{
11
_id: 'Chunk',
12
values: [ 1666935266, 604851965, 2194299958, 3393707011, 4090317618 ]
13
}
14
*/

You can repeatedly evaluate a given effect and terminate the stream based on specific conditions.

In this example, we’re draining an Iterator to create a stream from it:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Option
Option
} from "effect"
2
3
const
const drainIterator: <A>(it: Iterator<A>) => Stream.Stream<A>
drainIterator
= <
(type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
>(
(parameter) it: Iterator<A, any, any>
it
:
interface Iterator<T, TReturn = any, TNext = any>
Iterator
<
(type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
>):
import Stream
Stream
.
interface Stream<out A, out E = never, out R = never> namespace Stream

A `Stream<A, E, R>` is a description of a program that, when evaluated, may emit zero or more values of type `A`, may fail with errors of type `E`, and uses an context of type `R`. One way to think of `Stream` is as a `Effect` program that could emit multiple values. `Stream` is a purely functional *pull* based stream. Pull based streams offer inherent laziness and backpressure, relieving users of the need to manage buffers between operators. As an optimization, `Stream` does not emit single values, but rather an array of values. This allows the cost of effect evaluation to be amortized. `Stream` forms a monad on its `A` type parameter, and has error management facilities for its `E` type parameter, modeled similarly to `Effect` (with some adjustments for the multiple-valued nature of `Stream`). These aspects allow for rich and expressive composition of streams.

Stream
<
(type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
> =>
4
import Stream
Stream
.
const repeatEffectOption: <A, never, never>(effect: Effect.Effect<A, Option.Option<never>, never>) => Stream.Stream<A, never, never>

Creates a stream from an effect producing values of type `A` until it fails with `None`.

repeatEffectOption
(
5
import Effect
Effect
.
const sync: <IteratorResult<A, any>>(thunk: LazyArg<IteratorResult<A, any>>) => Effect.Effect<IteratorResult<A, any>, never, never>

Creates an `Effect` that represents a synchronous side-effectful computation. The provided function (`thunk`) should not throw errors; if it does, the error is treated as a defect. Use `Effect.sync` when you are certain the operation will not fail.

sync
(() =>
(parameter) it: Iterator<A, any, any>
it
.
(method) Iterator<A, any, any>.next(...[value]: [] | [any]): IteratorResult<A, any>
next
()).
(method) Pipeable.pipe<Effect.Effect<IteratorResult<A, any>, never, never>, Effect.Effect<A, Option.Option<never>, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<IteratorResult<A, any>, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
6
import Effect
Effect
.
const andThen: <IteratorResult<A, any>, Effect.Effect<never, Option.Option<never>, never> | Effect.Effect<A, never, never>>(f: (a: IteratorResult<A, any>) => Effect.Effect<...> | Effect.Effect<...>) => <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) res: IteratorResult<A, any>
res
) => {
7
if (
(parameter) res: IteratorResult<A, any>
res
.
(property) done?: boolean | undefined
done
) {
8
return
import Effect
Effect
.
const fail: <Option.Option<never>>(error: Option.Option<never>) => Effect.Effect<never, Option.Option<never>, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
())
9
}
10
return
import Effect
Effect
.
const succeed: <A>(value: A) => Effect.Effect<A, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) res: IteratorYieldResult<A>
res
.
(property) IteratorYieldResult<A>.value: A
value
)
11
})
12
)
13
)

You can create a stream that emits void values at specified intervals using the Stream.tick constructor. This is useful for creating periodic events.

1
import {
import Stream
Stream
,
import Effect
Effect
} from "effect"
2
3
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
const tick: (interval: DurationInput) => Stream.Stream<void>

A stream that emits void values spaced by the specified duration.

tick
("100 millis")
4
5
import Effect
Effect
.
const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<void>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<void, never, never>, Stream.Stream<void, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<void, never, never>) => Stream.Stream<void, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<void>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
6
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
7
)
8
/*
9
Output:
10
{
11
_id: 'Chunk',
12
values: [ undefined, undefined, undefined, undefined, undefined ]
13
}
14
*/

In functional programming, the concept of unfold can be thought of as the counterpart to fold.

With fold, we process a data structure and produce a return value. For example, we can take an Array<number> and calculate the sum of its elements.

On the other hand, unfold represents an operation where we start with an initial value and generate a recursive data structure, adding one element at a time using a specified state function. For example, we can create a sequence of natural numbers starting from 1 and using the increment function as the state function.

The Stream module includes an unfold function defined as follows:

declare const unfold: <S, A>(
initialState: S,
step: (s: S) => Option.Option<readonly [A, S]>
) => Stream<A>

Here’s how it works:

  • initialState. This is the initial state value.
  • step. The state function step takes the current state s as input. If the result of this function is None, the stream ends. If it’s Some<[A, S]>, the next element in the stream is A, and the state S is updated for the next step process.

For example, let’s create a stream of natural numbers using Stream.unfold:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Option
Option
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const unfold: <number, number>(s: number, f: (s: number) => Option.Option<readonly [number, number]>) => Stream.Stream<number, never, never>

Creates a stream by peeling off the "layers" of a value of type `S`.

unfold
(1, (
(parameter) n: number
n
) =>
import Option
Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new `Option` that wraps the given value.

some
([
(parameter) n: number
n
,
(parameter) n: number
n
+ 1]))
4
5
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
6
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
7
)
8
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

Sometimes, we may need to perform effectful state transformations during the unfolding operation. This is where Stream.unfoldEffect comes in handy. It allows us to work with effects while generating streams.

Here’s an example of creating an infinite stream of random 1 and -1 values using Stream.unfoldEffect:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Option
Option
,
import Random
Random
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const unfoldEffect: <number, number, never, never>(s: number, f: (s: number) => Effect.Effect<Option.Option<readonly [number, number]>, never, never>) => Stream.Stream<number, never, never>

Creates a stream by effectfully peeling off the "layers" of a value of type `S`.

unfoldEffect
(1, (
(parameter) n: number
n
) =>
4
import Random
Random
.
const nextBoolean: Effect.Effect<boolean, never, never>

Returns the next boolean value from the pseudo-random number generator.

nextBoolean
.
(method) Pipeable.pipe<Effect.Effect<boolean, never, never>, Effect.Effect<Option.Option<[number, number]>, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<boolean, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
5
import Effect
Effect
.
const map: <boolean, Option.Option<[number, number]>>(f: (a: boolean) => Option.Option<[number, number]>) => <E, R>(self: Effect.Effect<boolean, E, R>) => Effect.Effect<...> (+1 overload)
map
((
(parameter) b: boolean
b
) => (
(parameter) b: boolean
b
?
import Option
Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new `Option` that wraps the given value.

some
([
(parameter) n: number
n
, -
(parameter) n: number
n
]) :
import Option
Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new `Option` that wraps the given value.

some
([
(parameter) n: number
n
,
(parameter) n: number
n
])))
6
)
7
)
8
9
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

take
(5)))).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
10
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
11
)
12
// Example Output: { _id: 'Chunk', values: [ 1, 1, 1, 1, -1 ] }

There are also similar operations like Stream.unfoldChunk and Stream.unfoldChunkEffect tailored for working with Chunk data types.

Stream.paginate is similar to Stream.unfold but allows emitting values one step further.

For example, the following stream emits 0, 1, 2, 3 elements:

1
import {
import Stream
Stream
,
import Effect
Effect
,
import Option
Option
} from "effect"
2
3
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const paginate: <number, number>(s: number, f: (s: number) => readonly [number, Option.Option<number>]) => Stream.Stream<number, never, never>

Like `Stream.unfold`, but allows the emission of values to end one step further than the unfolding of the state. This is useful for embedding paginated APIs, hence the name.

paginate
(0, (
(parameter) n: number
n
) => [
4
(parameter) n: number
n
,
5
(parameter) n: number
n
< 3 ?
import Option
Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new `Option` that wraps the given value.

some
(
(parameter) n: number
n
+ 1) :
import Option
Option
.
const none: <number>() => Option.Option<number>

Creates a new `Option` that represents the absence of a value.

none
()
6
])
7
8
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
9
// { _id: 'Chunk', values: [ 0, 1, 2, 3 ] }

Here’s how it works:

  • We start with an initial value of 0.
  • The provided function takes the current value n and returns a tuple. The first element of the tuple is the value to emit (n), and the second element determines whether to continue (Option.some(n + 1)) or stop (Option.none()).

There are also similar operations like Stream.paginateChunk and Stream.paginateChunkEffect tailored for working with Chunk data types.

You might wonder about the difference between the unfold and paginate combinators and when to use one over the other. Let’s explore this by diving into an example.

Imagine we have a paginated API that provides a substantial amount of data in a paginated manner. When we make a request to this API, it returns a ResultPage object containing the results for the current page and a flag indicating whether it’s the last page or if there’s more data to retrieve on the next page. Here’s a simplified representation of our API:

1
import {
import Chunk
Chunk
,
import Effect
Effect
} from "effect"
2
3
type
type RawData = string
RawData
= string
4
5
class
class PageResult
PageResult
{
6
constructor(
7
readonly
(property) PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A> namespace Chunk
Chunk
<
type RawData = string
RawData
>,
8
readonly
(property) PageResult.isLast: boolean
isLast
: boolean
9
) {}
10
}
11
12
const
const pageSize: 2
pageSize
= 2
13
14
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
15
(parameter) pageNumber: number
pageNumber
: number
16
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
17
return
import Effect
Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
18
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
19
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

map
(
20
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty `Chunk` containing a range of integers, including both endpoints.

range
(1,
const pageSize: 2
pageSize
),
21
(
(parameter) index: number
index
) => `Result ${
(parameter) pageNumber: number
pageNumber
}-${
(parameter) index: number
index
}`
22
),
23
(parameter) pageNumber: number
pageNumber
=== 2 // Return 3 pages
24
)
25
)
26
}

Our goal is to convert this paginated API into a stream of RowData events. For our initial attempt, we might think that using the Stream.unfold operation is the way to go:

1
import {
import Chunk
Chunk
,
import Effect
Effect
,
import Stream
Stream
,
import Option
Option
} from "effect"
2
24 collapsed lines
3
type
type RawData = string
RawData
= string
4
5
class
class PageResult
PageResult
{
6
constructor(
7
readonly
(property) PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A> namespace Chunk
Chunk
<
type RawData = string
RawData
>,
8
readonly
(property) PageResult.isLast: boolean
isLast
: boolean
9
) {}
10
}
11
12
const
const pageSize: 2
pageSize
= 2
13
14
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
15
(parameter) pageNumber: number
pageNumber
: number
16
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
17
return
import Effect
Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
18
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
19
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

map
(
20
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty `Chunk` containing a range of integers, including both endpoints.

range
(1,
const pageSize: 2
pageSize
),
21
(
(parameter) index: number
index
) => `Result ${
(parameter) pageNumber: number
pageNumber
}-${
(parameter) index: number
index
}`
22
),
23
(parameter) pageNumber: number
pageNumber
=== 2 // Return 3 pages
24
)
25
)
26
}
27
28
const
const firstAttempt: Stream.Stream<string, Error, never>
firstAttempt
=
import Stream
Stream
.
const unfoldChunkEffect: <number, string, Error, never>(s: number, f: (s: number) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<string>, number]>, Error, never>) => Stream.Stream<...>

Creates a stream by effectfully peeling off the "layers" of a value of type `S`.

unfoldChunkEffect
(0, (
(parameter) pageNumber: number
pageNumber
) =>
29
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
(
(parameter) pageNumber: number
pageNumber
).
(method) Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<Option.None<readonly [Chunk.Chunk<string>, number]> | Option.Some<readonly [Chunk.Chunk<string>, number]>, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
30
import Effect
Effect
.
const map: <PageResult, Option.None<readonly [Chunk.Chunk<string>, number]> | Option.Some<readonly [Chunk.Chunk<string>, number]>>(f: (a: PageResult) => Option.None<...> | Option.Some<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)
map
((
(parameter) page: PageResult
page
) => {
31
if (
(parameter) page: PageResult
page
.
(property) PageResult.isLast: boolean
isLast
) {
32
return
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
()
33
}
34
return
import Option
Option
.
const some: <readonly [Chunk.Chunk<string>, number]>(value: readonly [Chunk.Chunk<string>, number]) => Option.Option<readonly [Chunk.Chunk<string>, number]>

Creates a new `Option` that wraps the given value.

some
([
(parameter) page: PageResult
page
.
(property) PageResult.results: Chunk.Chunk<string>
results
,
(parameter) pageNumber: number
pageNumber
+ 1] as
type const = readonly [Chunk.Chunk<string>, number]
const
)
35
})
36
)
37
)
38
39
import Effect
Effect
.
const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const firstAttempt: Stream.Stream<string, Error, never>
firstAttempt
)).
(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
40
/*
41
Output:
42
{
43
_id: "Chunk",
44
values: [ "Result 0-1", "Result 0-2", "Result 1-1", "Result 1-2" ]
45
}
46
*/

However, this approach has a drawback, it doesn’t include the results from the last page. To work around this, we perform an extra API call to include those missing results:

1
import {
import Chunk
Chunk
,
import Effect
Effect
,
import Stream
Stream
,
import Option
Option
} from "effect"
2
24 collapsed lines
3
type
type RawData = string
RawData
= string
4
5
class
class PageResult
PageResult
{
6
constructor(
7
readonly
(property) PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A> namespace Chunk
Chunk
<
type RawData = string
RawData
>,
8
readonly
(property) PageResult.isLast: boolean
isLast
: boolean
9
) {}
10
}
11
12
const
const pageSize: 2
pageSize
= 2
13
14
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
15
(parameter) pageNumber: number
pageNumber
: number
16
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
17
return
import Effect
Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
18
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
19
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

map
(
20
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty `Chunk` containing a range of integers, including both endpoints.

range
(1,
const pageSize: 2
pageSize
),
21
(
(parameter) index: number
index
) => `Result ${
(parameter) pageNumber: number
pageNumber
}-${
(parameter) index: number
index
}`
22
),
23
(parameter) pageNumber: number
pageNumber
=== 2 // Return 3 pages
24
)
25
)
26
}
27
28
const
const secondAttempt: Stream.Stream<string, Error, never>
secondAttempt
=
import Stream
Stream
.
const unfoldChunkEffect: <Option.Option<number>, string, Error, never>(s: Option.Option<number>, f: (s: Option.Option<number>) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<string>, Option.Option<number>]>, Error, never>) => Stream.Stream<...>

Creates a stream by effectfully peeling off the "layers" of a value of type `S`.

unfoldChunkEffect
(
29
import Option
Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new `Option` that wraps the given value.

some
(0),
30
(
(parameter) pageNumber: Option.Option<number>
pageNumber
) =>
31
import Option
Option
.
const match: <number, Effect.Effect<Option.Option<never>, never, never>, Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>>(self: Option.Option<...>, options: { ...; }) => Effect.Effect<...> | Effect.Effect<...> (+1 overload)

Matches the given `Option` and returns either the provided `onNone` value or the result of the provided `onSome` function when passed the `Option`'s value.

match
(
(parameter) pageNumber: Option.Option<number>
pageNumber
, {
32
// We already hit the last page
33
(property) onNone: LazyArg<Effect.Effect<Option.Option<never>, never, never>>
onNone
: () =>
import Effect
Effect
.
const succeed: <Option.Option<never>>(value: Option.Option<never>) => Effect.Effect<Option.Option<never>, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
()),
34
// We did not hit the last page yet
35
(property) onSome: (a: number) => Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>
onSome
: (
(parameter) pageNumber: number
pageNumber
) =>
36
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
(
(parameter) pageNumber: number
pageNumber
).
(method) Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
37
import Effect
Effect
.
const map: <PageResult, Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>>(f: (a: PageResult) => Option.Option<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)
map
((
(parameter) page: PageResult
page
) =>
38
import Option
Option
.
const some: <[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>(value: [Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]) => Option.Option<...>

Creates a new `Option` that wraps the given value.

some
([
39
(parameter) page: PageResult
page
.
(property) PageResult.results: Chunk.Chunk<string>
results
,
40
(parameter) page: PageResult
page
.
(property) PageResult.isLast: boolean
isLast
?
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
() :
import Option
Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new `Option` that wraps the given value.

some
(
(parameter) pageNumber: number
pageNumber
+ 1)
41
])
42
)
43
)
44
})
45
)
46
47
import Effect
Effect
.
const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const secondAttempt: Stream.Stream<string, Error, never>
secondAttempt
)).
(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
48
/*
49
Output:
50
{
51
_id: 'Chunk',
52
values: [
53
'Result 0-1',
54
'Result 0-2',
55
'Result 1-1',
56
'Result 1-2',
57
'Result 2-1',
58
'Result 2-2'
59
]
60
}
61
*/

While this approach works, it’s clear that Stream.unfold isn’t the most friendly option for retrieving data from paginated APIs. It requires additional workarounds to include the results from the last page.

This is where Stream.paginate comes to the rescue. It provides a more ergonomic way to convert a paginated API into an Effect stream. Let’s rewrite our solution using Stream.paginate:

1
import {
import Chunk
Chunk
,
import Effect
Effect
,
import Stream
Stream
,
import Option
Option
} from "effect"
2
24 collapsed lines
3
type
type RawData = string
RawData
= string
4
5
class
class PageResult
PageResult
{
6
constructor(
7
readonly
(property) PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A> namespace Chunk
Chunk
<
type RawData = string
RawData
>,
8
readonly
(property) PageResult.isLast: boolean
isLast
: boolean
9
) {}
10
}
11
12
const
const pageSize: 2
pageSize
= 2
13
14
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
15
(parameter) pageNumber: number
pageNumber
: number
16
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
17
return
import Effect
Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
18
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
19
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

map
(
20
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty `Chunk` containing a range of integers, including both endpoints.

range
(1,
const pageSize: 2
pageSize
),
21
(
(parameter) index: number
index
) => `Result ${
(parameter) pageNumber: number
pageNumber
}-${
(parameter) index: number
index
}`
22
),
23
(parameter) pageNumber: number
pageNumber
=== 2 // Return 3 pages
24
)
25
)
26
}
27
28
const
const finalAttempt: Stream.Stream<string, Error, never>
finalAttempt
=
import Stream
Stream
.
const paginateChunkEffect: <number, string, Error, never>(s: number, f: (s: number) => Effect.Effect<readonly [Chunk.Chunk<string>, Option.Option<number>], Error, never>) => Stream.Stream<...>

Like `Stream.unfoldChunkEffect`, but allows the emission of values to end one step further than the unfolding of the state. This is useful for embedding paginated APIs, hence the name.

paginateChunkEffect
(0, (
(parameter) pageNumber: number
pageNumber
) =>
29
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
(
(parameter) pageNumber: number
pageNumber
).
(method) Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<[Chunk.Chunk<string>, Option.Option<number>], Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
30
import Effect
Effect
.
const andThen: <PageResult, [Chunk.Chunk<string>, Option.Option<number>]>(f: (a: PageResult) => [Chunk.Chunk<string>, Option.Option<number>]) => <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) page: PageResult
page
) => {
31
return [
32
(parameter) page: PageResult
page
.
(property) PageResult.results: Chunk.Chunk<string>
results
,
33
(parameter) page: PageResult
page
.
(property) PageResult.isLast: boolean
isLast
?
import Option
Option
.
const none: <number>() => Option.Option<number>

Creates a new `Option` that represents the absence of a value.

none
<number>() :
import Option
Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new `Option` that wraps the given value.

some
(
(parameter) pageNumber: number
pageNumber
+ 1)
34
]
35
})
36
)
37
)
38
39
import Effect
Effect
.
const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const finalAttempt: Stream.Stream<string, Error, never>
finalAttempt
)).
(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
40
/*
41
Output:
42
{
43
_id: 'Chunk',
44
values: [
45
'Result 0-1',
46
'Result 0-2',
47
'Result 1-1',
48
'Result 1-2',
49
'Result 2-1',
50
'Result 2-2'
51
]
52
}
53
*/

In Effect, there are two essential asynchronous messaging data types: Queue and PubSub. You can easily transform these data types into Streams by utilizing Stream.fromQueue and Stream.fromPubSub, respectively.

We can create a stream from a Schedule that does not require any further input. The stream will emit an element for each value output from the schedule, continuing for as long as the schedule continues:

1
import {
import Effect
Effect
,
import Stream
Stream
,
import Schedule
Schedule
} from "effect"
2
3
// Emits values every 1 second for a total of 10 emissions
4
const
const schedule: Schedule.Schedule<number, unknown, never>
schedule
=
import Schedule
Schedule
.
const spaced: (duration: DurationInput) => Schedule.Schedule<number>

Returns a schedule that recurs continuously, each repetition spaced the specified duration from the last run.

spaced
("1 second").
(method) Pipeable.pipe<Schedule.Schedule<number, unknown, never>, Schedule.Schedule<number, unknown, never>>(this: Schedule.Schedule<...>, ab: (_: Schedule.Schedule<number, unknown, never>) => Schedule.Schedule<number, unknown, never>): Schedule.Schedule<...> (+21 overloads)
pipe
(
5
import Schedule
Schedule
.
const compose: <number, unknown, never>(that: Schedule.Schedule<number, unknown, never>) => <In, R>(self: Schedule.Schedule<unknown, In, R>) => Schedule.Schedule<number, In, R> (+1 overload)

Returns the composition of this schedule and the specified schedule, by piping the output of this one into the input of the other. Effects described by this schedule will always be executed before the effects described by the second schedule.

compose
(
import Schedule
Schedule
.
const recurs: (n: number) => Schedule.Schedule<number>

A schedule spanning all time, which can be stepped only the specified number of times before it terminates.

recurs
(10))
6
)
7
8
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromSchedule: <number, never>(schedule: Schedule.Schedule<number, unknown, never>) => Stream.Stream<number, never, never>

Creates a stream from a `Schedule` that does not require any further input. The stream will emit an element for each value output from the schedule, continuing for as long as the schedule continues.

fromSchedule
(
const schedule: Schedule.Schedule<number, unknown, never>
schedule
)
9
10
import Effect
Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Chunk<number>>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
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
)
11
/*
12
Output:
13
{
14
_id: 'Chunk',
15
values: [
16
0, 1, 2, 3, 4,
17
5, 6, 7, 8, 9
18
]
19
}
20
*/