Skip to content

流中的错误处理

在处理可能遇到错误的流时,了解如何优雅地处理这些错误至关重要。Stream.orElse 函数是从失败中恢复并在出现错误时切换到替代流的强大工具。

示例

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const s1: Stream.Stream<number, string, never>
s1
=
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, string, never>, bc: (_: Stream.Stream<number, string, never>) => Stream.Stream<number, string, never>): Stream.Stream<number, string, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, string, never>(that: Stream.Stream<never, string, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, string | E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
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
("Oh! Error!")),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5))
)
const
const s2: Stream.Stream<string, never, never>
s2
=
import Stream
Stream
.
const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, 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
("a", "b", "c")
const
const stream: Stream.Stream<string | number, never, never>
stream
=
import Stream
Stream
.
const orElse: <number, string, never, string, never, never>(self: Stream.Stream<number, string, never>, that: LazyArg<Stream.Stream<string, never, never>>) => Stream.Stream<string | number, never, never> (+1 overload)

Switches to the provided stream in case this one fails with a typed error.

See also Stream.catchAll.

@since2.0.0

orElse
(
const s1: Stream.Stream<number, string, never>
s1
, () =>
const s2: Stream.Stream<string, never, never>
s2
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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, "a", "b", "c" ]
}
*/

在此示例中,s1 遇到错误,但我们不是终止流,而是使用 Stream.orElse 优雅地切换到 s2。这确保即使一个流失败,我们也可以继续处理数据。

还有一个名为 Stream.orElseEither 的变体,它使用 Either 数据类型根据成功或失败来区分来自两个流的元素:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const s1: Stream.Stream<number, string, never>
s1
=
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, string, never>, bc: (_: Stream.Stream<number, string, never>) => Stream.Stream<number, string, never>): Stream.Stream<number, string, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, string, never>(that: Stream.Stream<never, string, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, string | E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
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
("Oh! Error!")),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5))
)
const
const s2: Stream.Stream<string, never, never>
s2
=
import Stream
Stream
.
const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, 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
("a", "b", "c")
const
const stream: Stream.Stream<Either<string, number>, never, never>
stream
=
import Stream
Stream
.
const orElseEither: <number, string, never, string, never, never>(self: Stream.Stream<number, string, never>, that: LazyArg<Stream.Stream<string, never, never>>) => Stream.Stream<Either<string, number>, never, never> (+1 overload)

Switches to the provided stream in case this one fails with a typed error.

See also Stream.catchAll.

@since2.0.0

orElseEither
(
const s1: Stream.Stream<number, string, never>
s1
, () =>
const s2: Stream.Stream<string, never, never>
s2
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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: [
{
_id: "Either",
_tag: "Left",
left: 1
}, {
_id: "Either",
_tag: "Left",
left: 2
}, {
_id: "Either",
_tag: "Left",
left: 3
}, {
_id: "Either",
_tag: "Right",
right: "a"
}, {
_id: "Either",
_tag: "Right",
right: "b"
}, {
_id: "Either",
_tag: "Right",
right: "c"
}
]
}
*/

Stream.orElse 相比,Stream.catchAll 函数提供了高级错误处理功能。使用 Stream.catchAll,您可以根据遇到的失败的类型和值做出决策。

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const s1: Stream.Stream<number, "Uh Oh!" | "Ouch", never>
s1
=
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, "Uh Oh!", never>, Stream.Stream<number, "Uh Oh!", never>, Stream.Stream<number, "Uh Oh!" | "Ouch", never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, "Uh Oh!", never>, bc: (_: Stream.Stream<number, "Uh Oh!", never>) => Stream.Stream<number, "Uh Oh!", never>, cd: (_: Stream.Stream<number, "Uh Oh!", never>) => Stream.Stream<number, "Uh Oh!" | "Ouch", never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, "Uh Oh!", never>(that: Stream.Stream<never, "Uh Oh!", never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, "Uh Oh!" | E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const fail: <"Uh Oh!">(error: "Uh Oh!") => Stream.Stream<never, "Uh Oh!", 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!" as
type const = "Uh Oh!"
const
)),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5)),
import Stream
Stream
.
const concat: <never, "Ouch", never>(that: Stream.Stream<never, "Ouch", never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, "Ouch" | E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const fail: <"Ouch">(error: "Ouch") => Stream.Stream<never, "Ouch", 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
("Ouch" as
type const = "Ouch"
const
))
)
const
const s2: Stream.Stream<string, never, never>
s2
=
import Stream
Stream
.
const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, 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
("a", "b", "c")
const
const s3: Stream.Stream<boolean, never, never>
s3
=
import Stream
Stream
.
const make: <[boolean, boolean, boolean]>(as_0: boolean, as_1: boolean, as_2: boolean) => Stream.Stream<boolean, 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
(true, false, false)
const
const stream: Stream.Stream<string | number | boolean, never, never>
stream
=
import Stream
Stream
.
const catchAll: <number, "Uh Oh!" | "Ouch", never, string | boolean, never, never>(self: Stream.Stream<number, "Uh Oh!" | "Ouch", never>, f: (error: "Uh Oh!" | "Ouch") => Stream.Stream<string | boolean, never, never>) => Stream.Stream<string | number | boolean, never, never> (+1 overload)

Switches over to the stream produced by the provided function in case this one fails with a typed error.

@since2.0.0

catchAll
(
const s1: Stream.Stream<number, "Uh Oh!" | "Ouch", never>
s1
,
(
error: "Uh Oh!" | "Ouch"
error
):
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
<string | boolean> => {
switch (
error: "Uh Oh!" | "Ouch"
error
) {
case "Uh Oh!":
return
const s2: Stream.Stream<string, never, never>
s2
case "Ouch":
return
const s3: Stream.Stream<boolean, never, never>
s3
}
}
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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, "a", "b", "c" ]
}
*/

在此示例中,我们有一个流 s1,它可能遇到两种不同类型的错误。我们不是像使用 Stream.orElse 那样直接切换到替代流,而是使用 Stream.catchAll 来精确确定如何处理每种类型的错误。这种对错误恢复的控制级别使您能够根据特定的错误条件选择不同的流或操作。

在处理流时,必须为各种失败场景做好准备,包括在流处理过程中可能发生的缺陷。为了解决这个问题,Stream.catchAllCause 函数提供了一个强健的解决方案。它使您能够优雅地处理和恢复可能出现的任何类型的失败。

示例

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const s1: Stream.Stream<number, never, never>
s1
=
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>, bc: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<number, never, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, never, never>(that: Stream.Stream<never, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const dieMessage: (message: string) => Stream.Stream<never>

The stream that dies with an exception described by message.

@since2.0.0

dieMessage
("Boom!")),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5))
)
const
const s2: Stream.Stream<string, never, never>
s2
=
import Stream
Stream
.
const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, 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
("a", "b", "c")
const
const stream: Stream.Stream<string | number, never, never>
stream
=
import Stream
Stream
.
const catchAllCause: <number, never, never, string, never, never>(self: Stream.Stream<number, never, never>, f: (cause: Cause<never>) => Stream.Stream<string, never, never>) => Stream.Stream<string | number, never, never> (+1 overload)

Switches over to the stream produced by the provided function in case this one fails. Allows recovery from all causes of failure, including interruption if the stream is uninterruptible.

@since2.0.0

catchAllCause
(
const s1: Stream.Stream<number, never, never>
s1
, () =>
const s2: Stream.Stream<string, never, never>
s2
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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, "a", "b", "c" ]
}
*/

在此示例中,s1 可能遇到缺陷,但我们不是让应用程序崩溃,而是使用 Stream.catchAllCause 优雅地切换到替代流 s2。这确保您的应用程序保持强健,即使面对意外问题也能继续处理数据。

在流处理中,可能存在需要从特定类型的失败中恢复的情况。Stream.catchSomeStream.catchSomeCause 函数来拯救,允许您有选择地处理和缓解错误。

如果您想从特定错误中恢复,可以使用 Stream.catchSome

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 s1: Stream.Stream<number, string, never>
s1
=
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, string, never>, bc: (_: Stream.Stream<number, string, never>) => Stream.Stream<number, string, never>): Stream.Stream<number, string, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, string, never>(that: Stream.Stream<never, string, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, string | E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
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
("Oh! Error!")),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5))
)
const
const s2: Stream.Stream<string, never, never>
s2
=
import Stream
Stream
.
const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, 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
("a", "b", "c")
const
const stream: Stream.Stream<string | number, string, never>
stream
=
import Stream
Stream
.
const catchSome: <number, string, never, string, never, never>(self: Stream.Stream<number, string, never>, pf: (error: string) => Option.Option<Stream.Stream<string, never, never>>) => Stream.Stream<string | number, string, never> (+1 overload)

Switches over to the stream produced by the provided function in case this one fails with some typed error.

@since2.0.0

catchSome
(
const s1: Stream.Stream<number, string, never>
s1
, (
error: string
error
) => {
if (
error: string
error
=== "Oh! Error!") {
return
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <Stream.Stream<string, never, never>>(value: Stream.Stream<string, never, never>) => Option.Option<Stream.Stream<string, never, never>>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(
const s2: Stream.Stream<string, never, never>
s2
)
}
return
import Option

@since2.0.0

@since2.0.0

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

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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, "a", "b", "c" ]
}
*/

要从特定原因中恢复,您可以使用 Stream.catchSomeCause 函数:

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
,
import Cause
Cause
} from "effect"
const
const s1: Stream.Stream<number, never, never>
s1
=
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>, bc: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<number, never, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, never, never>(that: Stream.Stream<never, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const dieMessage: (message: string) => Stream.Stream<never>

The stream that dies with an exception described by message.

@since2.0.0

dieMessage
("Oh! Error!")),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5))
)
const
const s2: Stream.Stream<string, never, never>
s2
=
import Stream
Stream
.
const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, 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
("a", "b", "c")
const
const stream: Stream.Stream<string | number, never, never>
stream
=
import Stream
Stream
.
const catchSomeCause: <number, never, never, string, never, never>(self: Stream.Stream<number, never, never>, pf: (cause: Cause.Cause<never>) => Option.Option<Stream.Stream<string, never, never>>) => Stream.Stream<string | number, never, never> (+1 overload)

Switches over to the stream produced by the provided function in case this one fails with some errors. Allows recovery from all causes of failure, including interruption if the stream is uninterruptible.

@since2.0.0

catchSomeCause
(
const s1: Stream.Stream<number, never, never>
s1
, (
cause: Cause.Cause<never>
cause
) => {
if (
import Cause
Cause
.
const isDie: <never>(self: Cause.Cause<never>) => boolean

Checks if a Cause contains a defect.

Details

This function returns true if the Cause includes any unexpected or unhandled errors (Die). It's useful for differentiating known failures from unexpected ones.

@since2.0.0

isDie
(
cause: Cause.Cause<never>
cause
)) {
return
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <Stream.Stream<string, never, never>>(value: Stream.Stream<string, never, never>) => Option.Option<Stream.Stream<string, never, never>>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(
const s2: Stream.Stream<string, never, never>
s2
)
}
return
import Option

@since2.0.0

@since2.0.0

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

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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, "a", "b", "c" ]
}
*/

在流处理中,优雅地处理错误并在需要时执行清理任务至关重要。Stream.onError 函数允许我们做到这一点。如果我们的流遇到错误,我们可以指定要执行的清理任务。

import {
import Stream
Stream
,
import Console
Console
,
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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>, bc: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>, cd: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <never, never, never>(that: Stream.Stream<never, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const dieMessage: (message: string) => Stream.Stream<never>

The stream that dies with an exception described by message.

@since2.0.0

dieMessage
("Oh! Boom!")),
import Stream
Stream
.
const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const make: <[number, number]>(as_0: number, as_1: 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
(4, 5)),
import Stream
Stream
.
const onError: <never, void, never>(cleanup: (cause: Cause<never>) => Effect.Effect<void, never, never>) => <A, R>(self: Stream.Stream<A, never, R>) => Stream.Stream<A, never, R> (+1 overload)

Runs the specified effect if this stream fails, providing the error to the effect if it exists.

Note: Unlike Effect.onError there is no guarantee that the provided effect will not be interrupted.

@since2.0.0

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

@since2.0.0

log
(
"Stream application closed! We are doing some cleanup jobs."
).
Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<void, never, never>>(this: Effect.Effect<void, never, never>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<void, never, never>): Effect.Effect<void, never, never> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const orDie: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, never, R>

Converts an effect's failure into a fiber termination, removing the error from the effect's type.

Details

The orDie function is used when you encounter errors that you do not want to handle or recover from. It removes the error type from the effect and ensures that any failure will terminate the fiber. This is useful for propagating failures as defects, signaling that they should not be handled within the effect.

*When to Use

Use orDie when failures should be treated as unrecoverable defects and no error handling is required.

Example (Propagating an Error as a Defect)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = Effect.orDie(divide(1, 0))
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...

@seeorDieWith if you need to customize the error.

@since2.0.0

orDie
)
)
)
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;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@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<void>

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
)
/*
输出:
Stream application closed! We are doing some cleanup jobs.
error: RuntimeException: Oh! Boom!
*/

有时,流可能遇到临时或可恢复的失败。在这种情况下,Stream.retry 操作符很有用。它允许您指定重试调度,流将根据该调度进行重试。

示例

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schedule
Schedule
} from "effect"
import * as
module "node:readline"
NodeReadLine
from "node:readline"
const
const stream: Stream.Stream<number, string, 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).
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<number, never, never>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, string, never>): Stream.Stream<number, string, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const concat: <number, string, never>(that: Stream.Stream<number, string, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, string | E, R> (+1 overload)

Concatenates the specified stream with this stream, resulting in a stream that emits the elements from this stream and then the elements from the specified stream.

@example

import { Effect, Stream } from "effect"
const s1 = Stream.make(1, 2, 3)
const s2 = Stream.make(4, 5)
const stream = Stream.concat(s1, s2)
Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

concat
(
import Stream
Stream
.
const fromEffect: <number, string, never>(effect: Effect.Effect<number, string, never>) => Stream.Stream<number, string, 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 Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<never, string, never>> | YieldWrap<Effect.Effect<string, never, never>>, number>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<never, string, never>> | YieldWrap<Effect.Effect<string, never, never>>, number, never>) => Effect.Effect<number, string, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const s: string
s
= yield*
const readLine: (message: string) => Effect.Effect<string>
readLine
("Enter a number: ")
const
const n: number
n
=
function parseInt(string: string, radix?: number): number

Converts a string to an integer.

@paramstring A string to convert into a number.

@paramradix A value between 2 and 36 that specifies the base of the number in string. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.

parseInt
(
const s: string
s
)
if (
var Number: NumberConstructor

An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

Number
.
NumberConstructor.isNaN(number: unknown): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter to a number. Only values of the type number, that are also NaN, result in true.

@paramnumber A numeric value.

isNaN
(
const n: number
n
)) {
return yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an Effect that represents a recoverable error.

When to Use

Use this function to explicitly signal an error in an Effect. The error will keep propagating unless it is handled. You can handle the error with functions like

catchAll

or

catchTag

.

Example (Creating a Failed Effect)

import { Effect } from "effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
new Error("Operation failed due to network error")
)

@seesucceed to create an effect that represents a successful value.

@since2.0.0

fail
("NaN")
}
return
const n: number
n
})
).
Pipeable.pipe<Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<number, string, never>, ab: (_: Stream.Stream<number, string, never>) => Stream.Stream<number, string, never>): Stream.Stream<number, string, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const retry: <string, never, Duration>(policy: Schedule.Schedule<Duration, string, never>) => <A, R>(self: Stream.Stream<A, string, R>) => Stream.Stream<A, string, R> (+1 overload)

When the stream fails, retry it according to the given schedule

This retries the entire stream, so will re-execute all of the stream's acquire operations.

The schedule is reset as soon as the first element passes through the stream again.

@since2.0.0

retry
(
import Schedule
Schedule
.
const exponential: (base: DurationInput, factor?: number) => Schedule.Schedule<Duration>

Creates a schedule that recurs indefinitely with exponentially increasing delays.

Details

This schedule starts with an initial delay of base and increases the delay exponentially on each repetition using the formula base * factor^n, where n is the number of times the schedule has executed so far. If no factor is provided, it defaults to 2, causing the delay to double after each execution.

@since2.0.0

exponential
("1 second")))
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@since2.0.0

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

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
)
/*
输出:
Enter a number: a
Enter a number: b
Enter a number: c
Enter a number: 4
{
_id: "Chunk",
values: [ 1, 2, 3, 4 ]
}
*/
const
const readLine: (message: string) => Effect.Effect<string>
readLine
= (
message: string
message
: string):
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 describes a workflow or job, which can succeed or fail.

Details

The Effect interface represents a computation that can model a workflow involving various types of operations, such as synchronous, asynchronous, concurrent, and parallel interactions. It operates within a context of type R, and the result can either be a success with a value of type A or a failure with an error of type E. The Effect is designed to handle complex interactions with external resources, offering advanced features such as fiber-based concurrency, scheduling, interruption handling, and scalability. This makes it suitable for tasks that require fine-grained control over concurrency and error management.

To execute an Effect value, you need a Runtime, which provides the environment necessary to run and manage the computation.

@since2.0.0

@since2.0.0

Effect
<string> =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const promise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Effect.Effect<string, never, never>

Creates an Effect that represents an asynchronous computation guaranteed to succeed.

Details

The provided function (thunk) returns a Promise that should never reject; if it does, the error will be treated as a "defect".

This defect is not a standard error but indicates a flaw in the logic that was expected to be error-free. You can think of it similar to an unexpected crash in the program, which can be further managed or logged using tools like

catchAllDefect

.

Interruptions

An optional AbortSignal can be provided to allow for interruption of the wrapped Promise API.

When to Use

Use this function when you are sure the operation will not reject.

Example (Delayed Message)

import { Effect } from "effect"
const delay = (message: string) =>
Effect.promise<string>(
() =>
new Promise((resolve) => {
setTimeout(() => {
resolve(message)
}, 2000)
})
)
// ┌─── Effect<string, never, never>
// ▼
const program = delay("Async operation completed successfully!")

@seetryPromise for a version that can handle failures.

@since2.0.0

promise
(
() =>
new
var Promise: PromiseConstructor
new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>

Creates a new Promise.

@paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

Promise
((
resolve: (value: string | PromiseLike<string>) => void
resolve
) => {
const
const rl: NodeReadLine.Interface
rl
=
module "node:readline"
NodeReadLine
.
function createInterface(options: NodeReadLine.ReadLineOptions): NodeReadLine.Interface (+1 overload)

The readline.createInterface() method creates a new readline.Interface instance.

import readline from 'node:readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

Once the readline.Interface instance is created, the most common case is to listen for the 'line' event:

rl.on('line', (line) => {
console.log(`Received: ${line}`);
});

If terminal is true for this instance then the output stream will get the best compatibility if it defines an output.columns property and emits a 'resize' event on the output if or when the columns ever change (process.stdout does this automatically when it is a TTY).

When creating a readline.Interface using stdin as input, the program will not terminate until it receives an EOF character. To exit without waiting for user input, call process.stdin.unref().

@sincev0.1.98

createInterface
({
ReadLineOptions.input: NodeJS.ReadableStream

The Readable stream to listen to

input
:
var process: NodeJS.Process
process
.
NodeJS.Process.stdin: NodeJS.ReadStream & {
fd: 0;
}

The process.stdin property returns a stream connected tostdin (fd 0). It is a net.Socket (which is a Duplex stream) unless fd 0 refers to a file, in which case it is a Readable stream.

For details of how to read from stdin see readable.read().

As a Duplex stream, process.stdin can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10. For more information see Stream compatibility.

In "old" streams mode the stdin stream is paused by default, so one must call process.stdin.resume() to read from it. Note also that calling process.stdin.resume() itself would switch stream to "old" mode.

stdin
,
ReadLineOptions.output?: NodeJS.WritableStream | undefined

The Writable stream to write readline data to.

output
:
var process: NodeJS.Process
process
.
NodeJS.Process.stdout: NodeJS.WriteStream & {
fd: 1;
}

The process.stdout property returns a stream connected tostdout (fd 1). It is a net.Socket (which is a Duplex stream) unless fd 1 refers to a file, in which case it is a Writable stream.

For example, to copy process.stdin to process.stdout:

import { stdin, stdout } from 'node:process';
stdin.pipe(stdout);

process.stdout differs from other Node.js streams in important ways. See note on process I/O for more information.

stdout
})
const rl: NodeReadLine.Interface
rl
.
Interface.question(query: string, callback: (answer: string) => void): void (+1 overload)

The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, then invokes the callback function passing the provided input as the first argument.

When called, rl.question() will resume the input stream if it has been paused.

If the Interface was created with output set to null or undefined the query is not written.

The callback function passed to rl.question() does not follow the typical pattern of accepting an Error object or null as the first argument. The callback is called with the provided answer as the only argument.

An error will be thrown if calling rl.question() after rl.close().

Example usage:

rl.question('What is your favorite food? ', (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});

Using an AbortController to cancel a question.

const ac = new AbortController();
const signal = ac.signal;
rl.question('What is your favorite food? ', { signal }, (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
signal.addEventListener('abort', () => {
console.log('The food question timed out');
}, { once: true });
setTimeout(() => ac.abort(), 10000);

@sincev0.3.3

@paramquery A statement or query to write to output, prepended to the prompt.

@paramcallback A callback function that is invoked with the user's input in response to the query.

question
(
message: string
message
, (
answer: string
answer
) => {
const rl: NodeReadLine.Interface
rl
.
Interface.close(): void

The rl.close() method closes the Interface instance and relinquishes control over the input and output streams. When called, the 'close' event will be emitted.

Calling rl.close() does not immediately stop other events (including 'line') from being emitted by the Interface instance.

@sincev0.1.98

close
()
resolve: (value: string | PromiseLike<string>) => void
resolve
(
answer: string
answer
)
})
})
)

在此示例中,流要求用户输入一个数字,但如果输入了无效值(例如 “a”、“b”、“c”),它会因 “NaN” 而失败。但是,我们使用带有指数退避调度的 Stream.retry,这意味着它将在延迟递增的持续时间后重试。这允许我们处理临时错误并最终收集有效输入。

在处理流时,可能存在您想要有选择地保留某些错误并用剩余错误终止流的情况。您可以使用 Stream.refineOrDie 函数来实现这一点。

示例

import {
import Stream
Stream
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const stream: Stream.Stream<never, Error, never>
stream
=
import Stream
Stream
.
const fail: <Error>(error: Error) => Stream.Stream<never, Error, 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
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
())
const
const res: Stream.Stream<never, SyntaxError, never>
res
=
import Stream
Stream
.
const refineOrDie: <never, Error, never, SyntaxError>(self: Stream.Stream<never, Error, never>, pf: (error: Error) => Option.Option<SyntaxError>) => Stream.Stream<never, SyntaxError, never> (+1 overload)

Keeps some of the errors, and terminates the fiber with the rest

@since2.0.0

refineOrDie
(
const stream: Stream.Stream<never, Error, never>
stream
, (
error: Error
error
) => {
if (
error: Error
error
instanceof
var SyntaxError: SyntaxErrorConstructor
SyntaxError
) {
return
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <SyntaxError>(value: SyntaxError) => Option.Option<SyntaxError>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(
error: SyntaxError
error
)
}
return
import Option

@since2.0.0

@since2.0.0

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

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
})

在此示例中,stream 最初因通用 Error 而失败。但是,我们使用 Stream.refineOrDie 来过滤并仅保留 SyntaxError 类型的错误。任何其他错误都将被终止,而 SyntaxErrors 将保留在 refinedStream 中。

在处理流时,存在您可能想要处理超时的场景,例如如果流在特定持续时间内不产生值则终止流。在本节中,我们将探索如何使用各种操作符管理超时。

Stream.timeout 操作符允许您在流上设置超时。如果流在指定持续时间内不产生值,它将终止。

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 fromEffect: <never, never, never>(effect: Effect.Effect<never, never, never>) => Stream.Stream<never, 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 Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const never: Effect.Effect<never, never, never>

An effect that that runs indefinitely and never produces any result. The moral equivalent of while(true) {}, only without the wasted CPU cycles.

When to Use

It could be useful for long-running background tasks or to simulate waiting behavior without actually consuming resources. This effect is ideal for cases where you want to keep the program alive or in a certain state without performing any active work.

@since2.0.0

never
).
Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<never, never, never>>(this: Stream.Stream<never, never, never>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<never, never, never>): Stream.Stream<never, never, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const timeout: (duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Ends the stream if it does not produce a value after the specified duration.

@since2.0.0

timeout
("2 seconds")
)
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;
} | undefined) => Promise<Chunk<never>>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@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<void>

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: []
}
*/

Stream.timeoutFail 操作符将超时与自定义失败消息结合起来。如果流超时,它会因指定的错误消息而失败。

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<never, string, never>
stream
=
import Stream
Stream
.
const fromEffect: <never, never, never>(effect: Effect.Effect<never, never, never>) => Stream.Stream<never, 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 Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const never: Effect.Effect<never, never, never>

An effect that that runs indefinitely and never produces any result. The moral equivalent of while(true) {}, only without the wasted CPU cycles.

When to Use

It could be useful for long-running background tasks or to simulate waiting behavior without actually consuming resources. This effect is ideal for cases where you want to keep the program alive or in a certain state without performing any active work.

@since2.0.0

never
).
Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<never, string, never>>(this: Stream.Stream<never, never, never>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<never, string, never>): Stream.Stream<never, string, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const timeoutFail: <string>(error: LazyArg<string>, duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, string | E, R> (+1 overload)

Fails the stream with given error if it does not produce a value after d duration.

@since2.0.0

timeoutFail
(() => "timeout", "2 seconds")
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <Chunk<never>, string>(effect: Effect.Effect<Chunk<never>, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<Chunk<never>, string>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
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 stream: Stream.Stream<never, string, never>
stream
)).
Promise<Exit<Chunk<never>, string>>.then<void, never>(onfulfilled?: ((value: Exit<Chunk<never>, string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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: 'Exit',
_tag: 'Failure',
cause: { _id: 'Cause', _tag: 'Fail', failure: 'timeout' }
}
*/

Stream.timeoutFail 类似,Stream.timeoutFailCause 将超时与自定义失败原因结合起来。如果流超时,它会因指定的原因而失败。

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Cause
Cause
} from "effect"
const
const stream: Stream.Stream<never, never, never>
stream
=
import Stream
Stream
.
const fromEffect: <never, never, never>(effect: Effect.Effect<never, never, never>) => Stream.Stream<never, 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 Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const never: Effect.Effect<never, never, never>

An effect that that runs indefinitely and never produces any result. The moral equivalent of while(true) {}, only without the wasted CPU cycles.

When to Use

It could be useful for long-running background tasks or to simulate waiting behavior without actually consuming resources. This effect is ideal for cases where you want to keep the program alive or in a certain state without performing any active work.

@since2.0.0

never
).
Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<never, never, never>>(this: Stream.Stream<never, never, never>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<never, never, never>): Stream.Stream<never, never, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const timeoutFailCause: <never>(cause: LazyArg<Cause.Cause<never>>, duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Fails the stream with given cause if it does not produce a value after d duration.

@since2.0.0

timeoutFailCause
(() =>
import Cause
Cause
.
const die: (defect: unknown) => Cause.Cause<never>

Creates a Die cause from an unexpected error.

Details

This function wraps an unhandled or unknown defect (like a runtime crash) into a Cause. It's useful for capturing unforeseen issues in a structured way.

@seeisDie Check if a Cause contains a defect

@since2.0.0

die
("timeout"), "2 seconds")
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <Chunk<never>, never>(effect: Effect.Effect<Chunk<never>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<Chunk<never>, never>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
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<Exit<Chunk<never>, never>>.then<void, never>(onfulfilled?: ((value: Exit<Chunk<never>, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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: 'Exit',
_tag: 'Failure',
cause: { _id: 'Cause', _tag: 'Die', defect: 'timeout' }
}
*/

The Stream.timeoutTo operator allows you to switch to another stream if the first stream does not produce a value within the specified duration.

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 fromEffect: <never, never, never>(effect: Effect.Effect<never, never, never>) => Stream.Stream<never, 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 Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const never: Effect.Effect<never, never, never>

An effect that that runs indefinitely and never produces any result. The moral equivalent of while(true) {}, only without the wasted CPU cycles.

When to Use

It could be useful for long-running background tasks or to simulate waiting behavior without actually consuming resources. This effect is ideal for cases where you want to keep the program alive or in a certain state without performing any active work.

@since2.0.0

never
).
Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<never, never, never>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<number, never, never> (+21 overloads)
pipe
(
import Stream
Stream
.
const timeoutTo: <number, never, never>(duration: DurationInput, that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)

Switches the stream if it does not produce a value after the specified duration.

@since2.0.0

timeoutTo
("2 seconds",
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;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@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<void>

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 ]
}
*/