Error Handling in Streams
This guide demonstrates techniques for managing errors and implementing recovery strategies in Effect’s Stream module.
The Stream.onError
function allows for cleanup or other tasks if a stream encounters an error.
Example (Executing Cleanup on Stream Error)
1import { import Stream
Stream, import Console
Console, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) 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<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const dieMessage: (message: string) => Stream.Stream<never>
The stream that dies with an exception described by `message`.
dieMessage("Oh! Boom!")),5 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.
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.
make(4, 5)),6 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.
onError(() => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log("Some cleanup job..."))7)8
9import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream))10/*11Output:12Some cleanup job...13RuntimeException: Oh! Boom!14*/
Stream.orElse
lets you recover from errors by switching to an alternative stream.
Example (Switching to an Alternative Stream on Error)
When s1
encounters an error, Stream.orElse
switches to s2
, allowing continued processing.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const 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.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const fail: <string>(error: string) => Stream.Stream<never, string, never>
Terminates with the specified error.
fail("Oh! Error!")),5 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.
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.
make(4, 5))6)7
8const 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.
make("a", "b", "c")9
10const 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`.
orElse(const s1: Stream.Stream<number, string, never>
s1, () => const s2: Stream.Stream<string, never, never>
s2)11
12import Effect
Effect.const runPromise: <Chunk<string | number>, never>(effect: Effect.Effect<Chunk<string | number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <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.
runCollect(const stream: Stream.Stream<string | number, never, never>
stream)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)13/*14Output:15{ _id: 'Chunk', values: [ 1, 2, 3, 'a', 'b', 'c' ] }16*/
Stream.orElseEither
enables error recovery by switching to an alternative stream if the original one fails, and wraps each element in an Either to indicate its source stream. This lets you distinguish between values from the primary and fallback streams.
Example (Differentiating Elements from Primary and Fallback Streams)
In this example, if s1
fails, Stream.orElseEither
switches to s2
, with each element wrapped in an Either
to indicate whether it came from the original (Left
) or fallback (Right
) stream.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const 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.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const fail: <string>(error: string) => Stream.Stream<never, string, never>
Terminates with the specified error.
fail("Oh! Error!")),5 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.
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.
make(4, 5))6)7
8const 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.
make("a", "b", "c")9
10const 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`.
orElseEither(const s1: Stream.Stream<number, string, never>
s1, () => const s2: Stream.Stream<string, never, never>
s2)11
12import Effect
Effect.const runPromise: <Chunk<Either<string, number>>, never>(effect: Effect.Effect<Chunk<Either<string, number>>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <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.
runCollect(const stream: Stream.Stream<Either<string, number>, never, never>
stream)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)13/*14Output:15{16 _id: 'Chunk',17 values: [18 { _id: 'Either', _tag: 'Left', left: 1 },19 { _id: 'Either', _tag: 'Left', left: 2 },20 { _id: 'Either', _tag: 'Left', left: 3 },21 { _id: 'Either', _tag: 'Right', right: 'a' },22 { _id: 'Either', _tag: 'Right', right: 'b' },23 { _id: 'Either', _tag: 'Right', right: 'c' }24 ]25}26*/
Stream.catchAll
offers detailed error handling that allows for tailored recovery actions based on the specific error encountered. Unlike Stream.orElse
, which provides a general fallback stream, Stream.catchAll
lets you respond selectively to different error types and values.
Example (Handling Specific Errors with Different Streams)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<number, "Uh Oh!" | "Ouch", never>
stream = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) 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<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const fail: <"Uh Oh!">(error: "Uh Oh!") => Stream.Stream<never, "Uh Oh!", never>
Terminates with the specified error.
fail("Uh Oh!" as type const = "Uh Oh!"
const)),5 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.
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.
make(4, 5)),6 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.
concat(import Stream
Stream.const fail: <"Ouch">(error: "Ouch") => Stream.Stream<never, "Ouch", never>
Terminates with the specified error.
fail("Ouch" as type const = "Ouch"
const))7)8
9const const recovered: Stream.Stream<string | number | boolean, never, never>
recovered = 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<...> (+1 overload)
Switches over to the stream produced by the provided function in case this
one fails with a typed error.
catchAll(10 const stream: Stream.Stream<number, "Uh Oh!" | "Ouch", never>
stream,11 ((parameter) error: "Uh Oh!" | "Ouch"
error): import Stream
Stream.interface Stream<out A, out E = never, out R = never>
namespace Stream
A `Stream<A, E, R>` is a description of a program that, when evaluated, may
emit zero or more values of type `A`, may fail with errors of type `E`, and
uses an context of type `R`. One way to think of `Stream` is as a
`Effect` program that could emit multiple values.
`Stream` is a purely functional *pull* based stream. Pull based streams offer
inherent laziness and backpressure, relieving users of the need to manage
buffers between operators. As an optimization, `Stream` does not emit
single values, but rather an array of values. This allows the cost of effect
evaluation to be amortized.
`Stream` forms a monad on its `A` type parameter, and has error management
facilities for its `E` type parameter, modeled similarly to `Effect` (with
some adjustments for the multiple-valued nature of `Stream`). These aspects
allow for rich and expressive composition of streams.
Stream<string | boolean> => {12 switch ((parameter) error: "Uh Oh!" | "Ouch"
error) {13 case "Uh Oh!":14 return 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.
make("a", "b", "c")15 case "Ouch":16 return 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.
make(true, false, false)17 }18 }19)20
21import Effect
Effect.const runPromise: <Chunk<string | number | boolean>, never>(effect: Effect.Effect<Chunk<string | number | boolean>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <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.
runCollect(const recovered: Stream.Stream<string | number | boolean, never, never>
recovered)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)22/*23Output:24{ _id: 'Chunk', values: [ 1, 2, 3, 'a', 'b', 'c' ] }25*/
To handle specific errors in a stream, you can use Stream.catchSome
. This function allows you to recover from particular errors by switching to an alternative stream when a match is found.
Example (Handling a Specific Error with an Alternative Stream)
1import { import Stream
Stream, import Effect
Effect, import Option
Option } from "effect"2
3const 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.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const fail: <string>(error: string) => Stream.Stream<never, string, never>
Terminates with the specified error.
fail("Oh! Error!")),5 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.
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.
make(4, 5))6)7
8const const recovered: Stream.Stream<string | number, string, never>
recovered = 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<...> (+1 overload)
Switches over to the stream produced by the provided function in case this
one fails with some typed error.
catchSome(const stream: Stream.Stream<number, string, never>
stream, ((parameter) error: string
error) => {9 if ((parameter) error: string
error === "Oh! Error!") {10 return import Option
Option.const some: <Stream.Stream<string, never, never>>(value: Stream.Stream<string, never, never>) => Option.Option<Stream.Stream<string, never, never>>
Creates a new `Option` that wraps the given value.
some(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.
make("a", "b", "c"))11 }12 return import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()13})14
15import Effect
Effect.const runPromise: <Chunk<string | number>, string>(effect: Effect.Effect<Chunk<string | number>, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <string | 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.
runCollect(const recovered: Stream.Stream<string | number, string, never>
recovered)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)16/*17Output:18{ _id: 'Chunk', values: [ 1, 2, 3, 'a', 'b', 'c' ] }19*/
To handle specific causes of stream failures, you can use Stream.catchSomeCause
. This function allows you to selectively recover from certain failure causes, such as defects or other specific issues, by switching to an alternative stream.
Example (Recovering from a Defect in a Stream)
1import { import Stream
Stream, import Effect
Effect, import Option
Option, import Cause
Cause } from "effect"2
3const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const dieMessage: (message: string) => Stream.Stream<never>
The stream that dies with an exception described by `message`.
dieMessage("Oh! Error!")),5 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.
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.
make(4, 5))6)7
8const const recovered: Stream.Stream<string | number, never, never>
recovered = 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<...> (+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.
catchSomeCause(const stream: Stream.Stream<number, never, never>
stream, ((parameter) cause: Cause.Cause<never>
cause) => {9 if (import Cause
Cause.const isDie: <never>(self: Cause.Cause<never>) => boolean
Returns `true` if the specified cause contains a defect, `false` otherwise.
isDie((parameter) cause: Cause.Cause<never>
cause)) {10 return import Option
Option.const some: <Stream.Stream<string, never, never>>(value: Stream.Stream<string, never, never>) => Option.Option<Stream.Stream<string, never, never>>
Creates a new `Option` that wraps the given value.
some(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.
make("a", "b", "c"))11 }12 return import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()13})14
15import Effect
Effect.const runPromise: <Chunk<string | number>, never>(effect: Effect.Effect<Chunk<string | number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <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.
runCollect(const recovered: Stream.Stream<string | number, never, never>
recovered)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)16/*17Output:18{ _id: 'Chunk', values: [ 1, 2, 3, 'a', 'b', 'c' ] }19*/
The Stream.catchAllCause
function provides a way to recover from any failure, whether it’s a standard error or an unexpected defect, by allowing you to switch to an alternative stream.
Example (Handling Defects in a Stream)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const 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.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 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.
concat(import Stream
Stream.const dieMessage: (message: string) => Stream.Stream<never>
The stream that dies with an exception described by `message`.
dieMessage("Boom!")),5 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.
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.
make(4, 5))6)7
8const 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.
make("a", "b", "c")9
10const 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<...> (+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.
catchAllCause(const s1: Stream.Stream<number, never, never>
s1, () => const s2: Stream.Stream<string, never, never>
s2)11
12import Effect
Effect.const runPromise: <Chunk<string | number>, never>(effect: Effect.Effect<Chunk<string | number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <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.
runCollect(const stream: Stream.Stream<string | number, never, never>
stream)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)13/*14Output:15{ _id: 'Chunk', values: [ 1, 2, 3, 'a', 'b', 'c' ] }16*/
Sometimes, a stream may encounter temporary or recoverable errors. The Stream.retry
operator provides a way to handle these cases by specifying a retry schedule, allowing the stream to attempt recovery according to the given schedule.
Example (Retrying a Stream with Exponential Backoff)
1import { import Stream
Stream, import Effect
Effect, import Schedule
Schedule } from "effect"2import * as (alias) module "node:readline"
import NodeReadLine
NodeReadLine from "node:readline"3
4const const readLine: (message: string) => Effect.Effect<string>
readLine = ((parameter) message: string
message: string): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<string> =>5 import Effect
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.
The provided function (`thunk`) returns a `Promise` that should never reject.
If the `Promise` does reject, the rejection is treated as a defect.
An optional `AbortSignal` can be provided to allow for interruption of the
wrapped `Promise` API.
promise(6 () =>7 new var Promise: PromiseConstructor
new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>
Creates a new Promise.
Promise(((parameter) resolve: (value: string | PromiseLike<string>) => void
resolve) => {8 const const rl: NodeReadLine.Interface
rl = (alias) module "node:readline"
import NodeReadLine
NodeReadLine.function createInterface(options: NodeReadLine.ReadLineOptions): NodeReadLine.Interface (+1 overload)
The `readline.createInterface()` method creates a new `readline.Interface` instance.
```js
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:
```js
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](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without
waiting for user input, call `process.stdin.unref()`.
createInterface({9 (property) ReadLineOptions.input: NodeJS.ReadableStream
input: var process: NodeJS.Process
process.(property) NodeJS.Process.stdin: NodeJS.ReadStream & {
fd: 0;
}
The `process.stdin` property returns a stream connected to`stdin` (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,10 (property) ReadLineOptions.output?: NodeJS.WritableStream | undefined
output: var process: NodeJS.Process
process.(property) NodeJS.Process.stdout: NodeJS.WriteStream & {
fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (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`:
```js
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.
stdout11 })12 const rl: NodeReadLine.Interface
rl.(method) 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:
```js
rl.question('What is your favorite food? ', (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
```
Using an `AbortController` to cancel a question.
```js
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);
```
question((parameter) message: string
message, ((parameter) answer: string
answer) => {13 const rl: NodeReadLine.Interface
rl.(method) 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.
close()14 (parameter) resolve: (value: string | PromiseLike<string>) => void
resolve((parameter) answer: string
answer)15 })16 })17 )18
19const 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.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, string, never>): Stream.Stream<...> (+21 overloads)
pipe(20 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.
concat(21 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.
fromEffect(22 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<never, string, never>> | YieldWrap<Effect.Effect<string, never, never>>, number>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen(function* () {23 const const s: string
s = yield* const readLine: (message: string) => Effect.Effect<string>
readLine("Enter a number: ")24 const const n: number
n = function parseInt(string: string, radix?: number): number
Converts a string to an integer.
parseInt(const s: string
s)25 if (var Number: NumberConstructor
An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number.(method) 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.
isNaN(const n: number
n)) {26 // Fail if input is not a number27 return yield* import Effect
Effect.const fail: <string>(error: string) => Effect.Effect<never, string, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail("NaN")28 }29 return const n: number
n30 })31 ).(method) Pipeable.pipe<Stream.Stream<number, string, never>, Stream.Stream<number, string, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, string, never>) => Stream.Stream<number, string, never>): Stream.Stream<...> (+21 overloads)
pipe(32 // Retry with exponential backoff33 import Stream
Stream.const retry: <string, never, string, Duration>(schedule: Schedule.Schedule<Duration, string, never>) => <A, R>(self: Stream.Stream<A, string, R>) => Stream.Stream<...> (+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.
retry(import Schedule
Schedule.const exponential: (base: DurationInput, factor?: number) => Schedule.Schedule<Duration>
A schedule that always recurs, but will wait a certain amount between
repetitions, given by `base * factor.pow(n)`, where `n` is the number of
repetitions so far. Returns the current duration between recurrences.
exponential("1 second"))34 )35 )36)37
38import Effect
Effect.const runPromise: <Chunk<number>, string>(effect: Effect.Effect<Chunk<number>, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, 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.
runCollect(const stream: Stream.Stream<number, string, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)39/*40Example Output:41Enter a number: a42Enter a number: b43Enter a number: c44Enter a number: 445{ _id: 'Chunk', values: [ 1, 2, 3, 4 ] }46*/
In some cases, you may want to selectively handle specific types of errors in a stream while terminating on others. The Stream.refineOrDie
function allows you to filter and retain only certain error types, terminating the stream if a non-matching error occurs.
Example (Filtering and Retaining Specific Error Types)
1import { import Stream
Stream, import Option
Option } from "effect"2
3// ┌─── Stream<number, Error, never>4// ▼5const const stream: Stream.Stream<number, Error, never>
stream = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, Error, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, Error, never>): Stream.Stream<...> (+21 overloads)
pipe(6 import Stream
Stream.const concat: <never, Error, never>(that: Stream.Stream<never, Error, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, Error | 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.
concat(import Stream
Stream.const fail: <Error>(error: Error) => Stream.Stream<never, Error, never>
Terminates with the specified error.
fail(new var Error: ErrorConstructor
new (message?: string) => Error
Error()))7)8
9// ┌─── Stream<number, SyntaxError, never>10// ▼11const const refined: Stream.Stream<number, SyntaxError, never>
refined = import Stream
Stream.const refineOrDie: <number, Error, never, SyntaxError>(self: Stream.Stream<number, Error, never>, pf: (error: Error) => Option.Option<SyntaxError>) => Stream.Stream<...> (+1 overload)
Keeps some of the errors, and terminates the fiber with the rest
refineOrDie(const stream: Stream.Stream<number, Error, never>
stream, ((parameter) error: Error
error) => {12 if ((parameter) error: Error
error instanceof var SyntaxError: SyntaxErrorConstructor
SyntaxError) {13 return import Option
Option.const some: <SyntaxError>(value: SyntaxError) => Option.Option<SyntaxError>
Creates a new `Option` that wraps the given value.
some((parameter) error: SyntaxError
error)14 }15 return import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()16})
In this example, stream
begins with a failure due to a generic Error
. By applying Stream.refineOrDie
, we filter out non-SyntaxError
errors. If the error is a SyntaxError
, it is retained in refined
; otherwise, the stream terminates, ensuring only specific error types are processed further.
When working with streams, there are scenarios where you may want to handle timeouts, such as terminating a stream if it doesn’t produce a value within a certain duration. In this section, we’ll explore how to manage timeouts using various operators.
The Stream.timeout
function allows you to impose a time limit on a stream. If the stream does not emit a value within the specified duration, it will terminate.
Example (Applying a Timeout to a Stream)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Create a stream that will never emit a value4const 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.
fromEffect(import Effect
Effect.const never: Effect.Effect<never, never, never>
Returns an effect that will never produce anything. The moral equivalent of
`while(true) {}`, only without the wasted CPU cycles.
never).(method) Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<never, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<never, never, never>): Stream.Stream<...> (+21 overloads)
pipe(5 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.
timeout("2 seconds")6)7
8import Effect
Effect.const runPromise: <Chunk<never>, never>(effect: Effect.Effect<Chunk<never>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<never>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <never, never, never>(self: Stream.Stream<never, never, never>) => Effect.Effect<Chunk<never>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<never, never, never>
stream)).(method) Promise<Chunk<never>>.then<void, never>(onfulfilled?: ((value: Chunk<never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{ _id: 'Chunk', values: [] }12*/
The Stream.timeoutFail
function allows you to set a timeout on a stream with a custom failure message. If the stream does not emit a value within the specified duration, it will fail with the provided error message.
Example (Timeout with Custom Failure Message)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Create a stream that never emits a value4const 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.
fromEffect(import Effect
Effect.const never: Effect.Effect<never, never, never>
Returns an effect that will never produce anything. The moral equivalent of
`while(true) {}`, only without the wasted CPU cycles.
never).(method) Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<never, string, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<never, string, never>): Stream.Stream<...> (+21 overloads)
pipe(5 import Stream
Stream.const timeoutFail: <string>(error: LazyArg<string>, duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<...> (+1 overload)
Fails the stream with given error if it does not produce a value after d
duration.
timeoutFail(() => "timeout", "2 seconds")6)7
8import Effect
Effect.const runPromiseExit: <Chunk<never>, string>(effect: Effect.Effect<Chunk<never>, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<Chunk<never>, string>>
Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result.
Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
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.
runCollect(const stream: Stream.Stream<never, string, never>
stream)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{12 _id: 'Exit',13 _tag: 'Failure',14 cause: { _id: 'Cause', _tag: 'Fail', failure: 'timeout' }15}16*/
The Stream.timeoutFailCause
function allows you to set a timeout on a stream with a custom failure cause. If the stream does not produce a value within the specified duration, it fails with the provided cause.
Example (Timeout with Custom Failure Cause)
1import { import Stream
Stream, import Effect
Effect, import Cause
Cause } from "effect"2
3// Create a stream that never emits a value4const 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.
fromEffect(import Effect
Effect.const never: Effect.Effect<never, never, never>
Returns an effect that will never produce anything. The moral equivalent of
`while(true) {}`, only without the wasted CPU cycles.
never).(method) Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<never, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<never, never, never>): Stream.Stream<...> (+21 overloads)
pipe(5 import Stream
Stream.const timeoutFailCause: <never>(cause: LazyArg<Cause.Cause<never>>, duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<...> (+1 overload)
Fails the stream with given cause if it does not produce a value after d
duration.
timeoutFailCause(() => import Cause
Cause.const die: (defect: unknown) => Cause.Cause<never>
Constructs a new `Die` cause from the specified `defect`.
die("timeout"), "2 seconds")6)7
8import Effect
Effect.const runPromiseExit: <Chunk<never>, never>(effect: Effect.Effect<Chunk<never>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<Chunk<never>, never>>
Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result.
Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
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.
runCollect(const stream: Stream.Stream<never, never, never>
stream)).(method) 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<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{12 _id: 'Exit',13 _tag: 'Failure',14 cause: { _id: 'Cause', _tag: 'Die', defect: 'timeout' }15}16*/
The Stream.timeoutTo
function lets you specify a fallback stream that will be used if the original stream fails to emit a value within the given duration. This can be useful for setting default behavior when a stream becomes unresponsive.
Example (Switching to a Fallback Stream on Timeout)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Create a stream that never emits a value4const 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.
fromEffect(import Effect
Effect.const never: Effect.Effect<never, never, never>
Returns an effect that will never produce anything. The moral equivalent of
`while(true) {}`, only without the wasted CPU cycles.
never).(method) Pipeable.pipe<Stream.Stream<never, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<never, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(5 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<...> (+1 overload)
Switches the stream if it does not produce a value after the specified
duration.
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.
make(1, 2, 3))6)7
8import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{ _id: 'Chunk', values: [ 1, 2, 3 ] }12*/