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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.make(1, 2, 3)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3 ] }

@since2.0.0

make
(1, 2, 3)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

The empty stream.

@example

import { Effect, Stream } from "effect"

const stream = Stream.empty

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [] }

@since2.0.0

empty
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<never, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
const void: Stream.Stream<void, never, never>
export void

A stream that contains a single void value.

@example

import { Effect, Stream } from "effect"

const stream = Stream.void

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ undefined ] }

@since2.0.0

void
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream of numbers from 1 to 5
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.

@example

import { Effect, Stream } from "effect"

// A Stream with a range of numbers from 1 to 5 const stream = Stream.range(1, 5)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

range
(1, 5)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream of incrementing numbers
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))), ...

@example

import { Effect, Stream } from "effect"

// An infinite Stream of numbers starting from 1 and incrementing const stream = Stream.iterate(1, (n) => n + 1)

// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(10)))).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] }

@since2.0.0

iterate
(1, (
n: number
n
) =>
n: number
n
+ 1) // Produces 1, 2, 3, ...
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Console
Console
} from "effect"
// Creating a single-valued stream from a scoped resource
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.

@example

import { Console, Effect, Stream } from "effect"

// Creating a single-valued stream from a scoped resource const stream = Stream.scoped( Effect.acquireUseRelease( Console.log("acquire"), () => Console.log("use"), () => Console.log("release") ) )

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // acquire // use // release // { _id: 'Chunk', values: [ undefined ] }

@since2.0.0

scoped
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@paramacquire - The Effect value that acquires the resource.

@paramuse - The Effect value that is executed between the acquisition and release of the resource.

@paramrelease - The Effect value that releases the resource.

@returnsA new Effect value that represents the acquisition, use, and release of the resource.

@since2.0.0

acquireUseRelease
(
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("acquire"),
() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("use"),
() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("release")
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
acquire
use
release
{ _id: 'Chunk', values: [ undefined ] }
*/

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

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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.

@since2.0.0

@since2.0.0

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

Terminates with the specified error.

@example

import { Effect, Stream } from "effect"

const stream = Stream.fail("Uh oh!")

Effect.runPromiseExit(Stream.runCollect(stream)).then(console.log) // { // _id: 'Exit', // _tag: 'Failure', // cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' } // }

@since2.0.0

fail
("Uh oh!")
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

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

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.

@since2.0.0

@since2.0.0

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

Creates a single-valued pure stream.

@example

import { Effect, Stream } from "effect"

// A Stream with a single number const stream = Stream.succeed(3)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 3 ] }

@since2.0.0

succeed
(5)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 5 ] }

You can construct a stream from a Chunk like this:

import {
import Stream
Stream
,
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream with values from a single Chunk
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.

@example

import { Chunk, Effect, Stream } from "effect"

// Creating a stream with values from a single Chunk const stream = Stream.fromChunk(Chunk.make(1, 2, 3))

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3 ] }

@since2.0.0

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.

@since2.0.0

make
(1, 2, 3))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

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

import {
import Stream
Stream
,
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream with values from multiple Chunks
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.

@example

import { Chunk, Effect, Stream } from "effect"

// Creating a stream with values from multiple Chunks const stream = Stream.fromChunks(Chunk.make(1, 2, 3), Chunk.make(4, 5, 6))

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }

@since2.0.0

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.

@since2.0.0

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.

@since2.0.0

make
(4, 5, 6))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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:

import {
import Stream
Stream
,
import Random
Random
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
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.

@example

import { Effect, Random, Stream } from "effect"

const stream = Stream.fromEffect(Random.nextInt)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // Example Output: { _id: 'Chunk', values: [ 922694024 ] }

@since2.0.0

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

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

@since2.0.0

nextInt
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// 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:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Chunk
Chunk
,
import Option

@since2.0.0

@since2.0.0

Option
,
import StreamEmit
StreamEmit
} from "effect"
const
const events: number[]
events
= [1, 2, 3, 4]
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
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.

@example

import type { StreamEmit } from "effect" import { Chunk, Effect, Option, Stream } from "effect"

const events = [1, 2, 3, 4]

const stream = Stream.async( (emit: StreamEmit.Emit<never, never, number, void>) => { events.forEach((n) => { setTimeout(() => { if (n === 3) { emit(Effect.fail(Option.none())) // Terminate the stream } else { emit(Effect.succeed(Chunk.of(n))) // Add the current item to the stream } }, 100 * n) }) } )

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2 ] }

@since2.0.0

async
(
(
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.

@since2.0.0

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

Performs the specified action for each element in an array.

@paramcallbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.

@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

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

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().

@sincev0.0.1

@paramcallback The function to call when the timer elapses.

@paramdelay The number of milliseconds to wait before calling the callback.

@paramargs Optional arguments to pass when the callback is called.

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

@since2.0.0

@since2.0.0

@since2.0.0

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

catchAll

or

catchTag

.

@example

import { Effect } from "effect"

// Example of creating a failed effect const failedEffect = Effect.fail("Something went wrong")

// Handle the failure failedEffect.pipe( Effect.catchAll((error) => Effect.succeed(Recovered from: ${error})), Effect.runPromise ).then(console.log) // Output: "Recovered from: Something went wrong"

@since2.0.0

fail
(
import Option

@since2.0.0

@since2.0.0

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

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

@since2.0.0

none
()))
} else {
// Add the current item to the stream
emit: StreamEmit.Emit
(f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Creating an effect that succeeds with the number 42 const success = Effect.succeed(42)

@since2.0.0

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

Builds a NonEmptyChunk from a single element.

@since2.0.0

of
(
n: number
n
)))
}
}, 100 *
n: number
n
)
})
}
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const numbers: number[]
numbers
= [1, 2, 3]
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.

@example

import { Effect, Stream } from "effect"

const numbers = [1, 2, 3]

const stream = Stream.fromIterable(numbers)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3 ] }

@since2.0.0

fromIterable
(
const numbers: number[]
numbers
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Context

@since2.0.0

@since2.0.0

Context
} from "effect"
class
class Database
Database
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"Database">(id: "Database") => <Self, Shape>() => Context.TagClass<Self, "Database", Shape>

@example

import { Context, Layer } from "effect"

class MyTag extends Context.Tag("MyTag")< MyTag, { readonly myNum: number }

() { static Live = Layer.succeed(this, { myNum: 108 }) }

@since2.0.0

Tag
("Database")<
class Database
Database
,
{ readonly
getUsers: Effect.Effect<string[], never, never>
getUsers
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

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.

@since2.0.0

@since2.0.0

Effect
<
interface Array<T>
Array
<string>> }
>() {}
const
const getUsers: Effect.Effect<string[], never, Database>
getUsers
=
class Database
Database
.
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

@since2.0.0

@since2.0.0

@since2.0.0

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 Effects, 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

@example

import { Effect } from "effect"

assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen(1))), 1) assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen((s) => s.length))), 2)

assert.deepStrictEqual(await Effect.runPromise(Effect.succeed("aa").pipe(Effect.andThen(Promise.resolve(1)))), 1) assert.deepStrictEqual(await Effect.runPromise(Effect.succeed("aa").pipe(Effect.andThen((s) => Promise.resolve(s.length)))), 2)

assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen(Effect.succeed(1)))), 1) assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen((s) => Effect.succeed(s.length)))), 2)

@since2.0.0

andThen
((
_: {
readonly getUsers: Effect.Effect<Array<string>>;
}
_
) =>
_: {
readonly getUsers: Effect.Effect<Array<string>>;
}
_
.
getUsers: Effect.Effect<string[], never, never>
getUsers
))
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>.

@example

import { Context, Effect, Stream } from "effect"

class Database extends Context.Tag("Database")< Database, { readonly getUsers: Effect.Effect<Array> }

() {}

const getUsers = Database.pipe(Effect.andThen((_) => _.getUsers))

const stream = Stream.fromIterableEffect(getUsers)

// Effect.runPromise( // Stream.runCollect(stream.pipe(Stream.provideService(Database, { getUsers: Effect.succeed(["user1", "user2"]) }))) // ).then(console.log) // { _id: 'Chunk', values: [ 'user1', 'user2' ] }

@since2.0.0

fromIterableEffect
(
const getUsers: Effect.Effect<string[], never, Database>
getUsers
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

runPromise
(
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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<string, never, Database>
stream
.
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
(
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.

@since2.0.0

provideService
(
class Database
Database
, {
getUsers: Effect.Effect<string[], never, never>
getUsers
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Creating an effect that succeeds with the number 42 const success = Effect.succeed(42)

@since2.0.0

succeed
(["user1", "user2"])
})
)
)
).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const myAsyncIterable: () => AsyncGenerator<1 | 2, void, unknown>
myAsyncIterable
= async function* () {
yield 1
yield 2
}
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.

@example

import { Effect, Stream } from "effect"

const myAsyncIterable = async function*() { yield 1 yield 2 }

const stream = Stream.fromAsyncIterable( myAsyncIterable(), (e) => new Error(String(e)) // Error Handling )

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 1, 2 ] }

@since2.0.0

fromAsyncIterable
(
const myAsyncIterable: () => AsyncGenerator<1 | 2, void, unknown>
myAsyncIterable
(),
(
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
(
e: unknown
e
)) // Error Handling
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<1 | 2, Error, never>
stream
)).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.repeatValue(0)

// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) // { _id: 'Chunk', values: [ 0, 0, 0, 0, 0 ] }

@since2.0.0

repeatValue
(0)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schedule
Schedule
} from "effect"
// Creating a stream that repeats a value indefinitely
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.

@example

import { Effect, Schedule, Stream } from "effect"

const stream = Stream.repeat(Stream.succeed(1), Schedule.forever)

// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) // { _id: 'Chunk', values: [ 1, 1, 1, 1, 1 ] }

@since2.0.0

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

Creates a single-valued pure stream.

@example

import { Effect, Stream } from "effect"

// A Stream with a single number const stream = Stream.succeed(3)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 3 ] }

@since2.0.0

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.

@since2.0.0

forever
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _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:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Random
Random
} from "effect"
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.

@example

import { Effect, Random, Stream } from "effect"

const stream = Stream.repeatEffect(Random.nextInt)

// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) // Example Output: { _id: 'Chunk', values: [ 3891571149, 4239494205, 2352981603, 2339111046, 1488052210 ] }

@since2.0.0

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

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

@since2.0.0

nextInt
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Example Output:
{
_id: 'Chunk',
values: [ 1666935266, 604851965, 2194299958, 3393707011, 4090317618 ]
}
*/

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:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const drainIterator: <A>(it: Iterator<A>) => Stream.Stream<A>
drainIterator
= <
function (type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
>(
it: Iterator<A, any, any>
it
:
interface Iterator<T, TReturn = any, TNext = any>
Iterator
<
function (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>

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.

@since2.0.0

@since2.0.0

Stream
<
function (type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
> =>
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.

@example

// In this example, we're draining an Iterator to create a stream from it import { Stream, Effect, Option } from "effect"

const drainIterator = (it: Iterator): Stream.Stream => Stream.repeatEffectOption( Effect.sync(() => it.next()).pipe( Effect.andThen((res) => { if (res.done) { return Effect.fail(Option.none()) } return Effect.succeed(res.value) }) ) )

@since2.0.0

repeatEffectOption
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Creating an effect that logs a message const log = (message: string) => Effect.sync(() => { console.log(message) // side effect })

const program = log("Hello, World!")

@since2.0.0

sync
(() =>
it: Iterator<A, any, any>
it
.
Iterator<A, any, any>.next(...[value]: [] | [any]): IteratorResult<A, any>
next
()).
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
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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 Effects, 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

@example

import { Effect } from "effect"

assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen(1))), 1) assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen((s) => s.length))), 2)

assert.deepStrictEqual(await Effect.runPromise(Effect.succeed("aa").pipe(Effect.andThen(Promise.resolve(1)))), 1) assert.deepStrictEqual(await Effect.runPromise(Effect.succeed("aa").pipe(Effect.andThen((s) => Promise.resolve(s.length)))), 2)

assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen(Effect.succeed(1)))), 1) assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen((s) => Effect.succeed(s.length)))), 2)

@since2.0.0

andThen
((
res: IteratorResult<A, any>
res
) => {
if (
res: IteratorResult<A, any>
res
.
done?: boolean | undefined
done
) {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

catchAll

or

catchTag

.

@example

import { Effect } from "effect"

// Example of creating a failed effect const failedEffect = Effect.fail("Something went wrong")

// Handle the failure failedEffect.pipe( Effect.catchAll((error) => Effect.succeed(Recovered from: ${error})), Effect.runPromise ).then(console.log) // Output: "Recovered from: Something went wrong"

@since2.0.0

fail
(
import Option

@since2.0.0

@since2.0.0

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

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

@since2.0.0

none
())
}
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Creating an effect that succeeds with the number 42 const success = Effect.succeed(42)

@since2.0.0

succeed
(
res: IteratorYieldResult<A>
res
.
IteratorYieldResult<A>.value: A
value
)
})
)
)

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

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
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.

@example

import { Effect, Stream } from "effect"

let last = Date.now() const log = (message: string) => Effect.sync(() => { const end = Date.now() console.log(${message} after ${end - last}ms) last = end })

const stream = Stream.tick("1 seconds").pipe(Stream.tap(() => log("tick")))

// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) // tick after 4ms // tick after 1003ms // tick after 1001ms // tick after 1002ms // tick after 1002ms // { _id: 'Chunk', values: [ undefined, undefined, undefined, undefined, undefined ] }

@since2.0.0

tick
("100 millis")
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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.

@example

import { Effect } from "effect"

// Execute an effect and handle the result with a Promise Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1

// Execute a failing effect and handle the rejection Effect.runPromise(Effect.fail("my error")).catch((error) => { console.error("Effect failed with error:", error) })

@since2.0.0

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.

@since2.0.0

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
.
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.

@example

import { Effect, Stream } from "effect"

const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)

// Effect.runPromise(Stream.runCollect(stream)).then(console.log) // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
{
_id: 'Chunk',
values: [ undefined, undefined, undefined, undefined, undefined ]
}
*/

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:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
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.

@example

import { Effect, Option, Stream } from "effect"

const stream = Stream.unfold(1, (n) => Option.some([n, n + 1]))

// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

unfold
(1, (
n: number
n
) =>
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
([
n: number
n
,
n: number
n