Creating Streams
In this guide, we’ll explore a variety of ways to create streams using built-in constructors, from single-value streams and ranges to streams created from asynchronous sources like iterables, effects, and schedules.
The Stream.make
constructor lets you create a stream from a list of values. Each value passed to Stream.make
will be emitted by the stream in the order provided.
Example (Creating a Stream from Values)
1import { import Stream
Stream, 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)4
5import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)6// Output: { _id: 'Chunk', values: [ 1, 2, 3 ] }
When you need a stream that doesn’t emit any values, use Stream.empty
. This constructor creates a stream that remains empty throughout its lifecycle.
Example (Creating an Empty Stream)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<never, never, never>
stream = import Stream
Stream.const empty: Stream.Stream<never, never, never>
The empty stream.
empty4
5import Effect
Effect.const runPromise: <Chunk<never>, never>(effect: Effect.Effect<Chunk<never>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<never>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <never, never, never>(self: Stream.Stream<never, never, never>) => Effect.Effect<Chunk<never>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<never, never, never>
stream)).(method) Promise<Chunk<never>>.then<void, never>(onfulfilled?: ((value: Chunk<never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)6// Output: { _id: 'Chunk', values: [] }
If you need a stream that emits a single void
value, use Stream.void
. This is useful for creating a stream that simply represents a single event or signal.
Example (Creating a Stream with a Single Void Value)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<void, never, never>
stream = import Stream
Stream.(alias) const void: Stream.Stream<void, never, never>
export void
A stream that contains a single `void` value.
void4
5import Effect
Effect.const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<void>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<void, never, never>
stream)).(method) Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<void>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)6// Output: { _id: 'Chunk', values: [ undefined ] }
To create a stream of sequential integers within a specified range [min, max]
, including both endpoints, you can use Stream.range
.
Example (Creating a Stream of Numbers in a Range)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Stream that generates numbers from 1 to 54const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const range: (min: number, max: number, chunkSize?: number) => Stream.Stream<number>
Constructs a stream from a range of integers, including both endpoints.
range(1, 5)5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)7// Output: { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }
With Stream.iterate
, you can generate a stream by applying a function iteratively to an initial value. The initial value becomes the first element produced by the stream, followed by subsequent values produced by f(init)
, f(f(init))
, and so on.
The Stream.iterate
constructor generates a stream by repeatedly applying a function to an initial value. The stream begins with the initial value, followed by f(init)
, f(f(init))
, and so on.
Example (Creating an Iterative Stream of Incrementing Numbers)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Stream of incrementing numbers starting from 14const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const iterate: <number>(value: number, next: (value: number) => number) => Stream.Stream<number, never, never>
The infinite stream of iterative function application: a, f(a), f(f(a)),
f(f(f(a))), ...
iterate(1, ((parameter) n: number
n) => (parameter) n: number
n + 1) // Produces 1, 2, 3, ...5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log8)9// Output: { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }
Similar to the Effect
data type, you can create a Stream
that either succeeds with a value or fails with an error using the Stream.succeed
and Stream.fail
functions.
Example (Creating Streams from Success and Failure)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Stream that successfully emits a single numeric value4const const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber: import Stream
Stream.interface Stream<out A, out E = never, out R = never>
namespace Stream
A `Stream<A, E, R>` is a description of a program that, when evaluated, may
emit zero or more values of type `A`, may fail with errors of type `E`, and
uses an context of type `R`. One way to think of `Stream` is as a
`Effect` program that could emit multiple values.
`Stream` is a purely functional *pull* based stream. Pull based streams offer
inherent laziness and backpressure, relieving users of the need to manage
buffers between operators. As an optimization, `Stream` does not emit
single values, but rather an array of values. This allows the cost of effect
evaluation to be amortized.
`Stream` forms a monad on its `A` type parameter, and has error management
facilities for its `E` type parameter, modeled similarly to `Effect` (with
some adjustments for the multiple-valued nature of `Stream`). These aspects
allow for rich and expressive composition of streams.
Stream<number> = import Stream
Stream.const succeed: <number>(value: number) => Stream.Stream<number, never, never>
Creates a single-valued pure stream.
succeed(5)5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)7// Output: { _id: 'Chunk', values: [ 5 ] }8
9// Stream that fails with an error message10const const streamWithError: Stream.Stream<never, string, never>
streamWithError: import Stream
Stream.interface Stream<out A, out E = never, out R = never>
namespace Stream
A `Stream<A, E, R>` is a description of a program that, when evaluated, may
emit zero or more values of type `A`, may fail with errors of type `E`, and
uses an context of type `R`. One way to think of `Stream` is as a
`Effect` program that could emit multiple values.
`Stream` is a purely functional *pull* based stream. Pull based streams offer
inherent laziness and backpressure, relieving users of the need to manage
buffers between operators. As an optimization, `Stream` does not emit
single values, but rather an array of values. This allows the cost of effect
evaluation to be amortized.
`Stream` forms a monad on its `A` type parameter, and has error management
facilities for its `E` type parameter, modeled similarly to `Effect` (with
some adjustments for the multiple-valued nature of `Stream`). These aspects
allow for rich and expressive composition of streams.
Stream<never, string> =11 import Stream
Stream.const fail: <string>(error: string) => Stream.Stream<never, string, never>
Terminates with the specified error.
fail("Uh oh!")12
13// Attempt to run the stream, which will throw an error14import Effect
Effect.const runPromise: <Chunk<never>, string>(effect: Effect.Effect<Chunk<never>, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<never>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <never, string, never>(self: Stream.Stream<never, string, never>) => Effect.Effect<Chunk<never>, string, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const streamWithError: Stream.Stream<never, string, never>
streamWithError))15/*16throws:17[Error: Uh oh!] {18 name: '(FiberFailure) Error',19 [Symbol(effect/Runtime/FiberFailure/Cause)]: {20 _tag: 'Fail',21 error: 'Uh oh!'22 }23 ...24}25*/
You can create a stream from a Chunk with Stream.fromChunk
.
Example (Creating a Stream from a Single Chunk)
1import { import Stream
Stream, import Chunk
Chunk, import Effect
Effect } from "effect"2
3// Create a stream with values from a single Chunk4const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const fromChunk: <number>(chunk: Chunk.Chunk<number>) => Stream.Stream<number, never, never>
Creates a stream from a `Chunk` of values.
fromChunk(import Chunk
Chunk.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>
Builds a `NonEmptyChunk` from an non-empty collection of elements.
make(1, 2, 3))5
6import Effect
Effect.const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)7// Output: { _id: 'Chunk', values: [ 1, 2, 3 ] }
You can also construct a stream from multiple chunks, combining their values into a continuous stream.
Example (Creating a Stream from Multiple Chunks)
1import { import Stream
Stream, import Chunk
Chunk, import Effect
Effect } from "effect"2
3// Create a stream with values from multiple Chunks4const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const fromChunks: <number>(...chunks: Chunk.Chunk<number>[]) => Stream.Stream<number, never, never>
Creates a stream from an arbitrary number of chunks.
fromChunks(import Chunk
Chunk.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>
Builds a `NonEmptyChunk` from an non-empty collection of elements.
make(1, 2, 3), import Chunk
Chunk.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>
Builds a `NonEmptyChunk` from an non-empty collection of elements.
make(4, 5, 6))5
6import Effect
Effect.const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)7// Output: { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }
To create a stream from an Effect
, use the Stream.fromEffect
constructor. This is useful when you want to convert a one-time asynchronous effect into a stream.
Example (Creating a Stream from a Single Random Number)
In this example, we generate a stream that produces a single random number:
1import { import Stream
Stream, import Random
Random, import Effect
Effect } from "effect"2
3// Create a stream from an Effect that generates a random integer4const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const fromEffect: <number, never, never>(effect: Effect.Effect<number, never, never>) => Stream.Stream<number, never, never>
Either emits the success value of this effect or terminates the stream
with the failure value of this effect.
fromEffect(import Random
Random.const nextInt: Effect.Effect<number, never, never>
Returns the next integer value from the pseudo-random number generator.
nextInt)5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)7// Example Output: { _id: 'Chunk', values: [ 1042302242 ] }
If you have an asynchronous function that uses callbacks, you can capture its emitted values as a stream with the Stream.async
function. This method is ideal for adapting functions that call back multiple times, streaming their outputs as they arrive.
Example (Creating a Stream from an Asynchronous Callback)
1import { import Stream
Stream, import Effect
Effect, import Chunk
Chunk, import Option
Option } from "effect"2
3const const events: number[]
events = [1, 2, 3, 4]4
5const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.(alias) async<number, never, never>(register: (emit: Emit<never, never, number, void>) => void | Effect.Effect<void, never, never>, bufferSize?: number | "unbounded" | {
readonly bufferSize?: number | undefined;
readonly strategy?: "dropping" | "sliding" | "suspend" | undefined;
} | undefined): Stream.Stream<...>
export async
Creates a stream from an asynchronous callback that can be called multiple
times. The optionality of the error type `E` in `Emit` can be used to
signal the end of the stream by setting it to `None`.
The registration function can optionally return an `Effect`, which will be
executed if the `Fiber` executing this Effect is interrupted.
async<number>(((parameter) emit: Emit<never, never, number, void>
emit) => {6 const events: number[]
events.(method) Array<number>.forEach(callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void
Performs the specified action for each element in an array.
forEach(((parameter) n: number
n) => {7 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {8 if ((parameter) n: number
n === 3) {9 // Terminate the stream after the third event10 (parameter) emit: Emit
(f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit(import Effect
Effect.const fail: <Option.Option<never>>(error: Option.Option<never>) => Effect.Effect<never, Option.Option<never>, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail(import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()))11 } else {12 // Emit the current item to the stream13 (parameter) emit: Emit
(f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit(import Effect
Effect.const succeed: <Chunk.NonEmptyChunk<number>>(value: Chunk.NonEmptyChunk<number>) => Effect.Effect<Chunk.NonEmptyChunk<number>, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(import Chunk
Chunk.const of: <number>(a: number) => Chunk.NonEmptyChunk<number>
Builds a `NonEmptyChunk` from a single element.
of((parameter) n: number
n)))14 }15 }, 100 * (parameter) n: number
n)16 })17})18
19import Effect
Effect.const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)20// Output: { _id: 'Chunk', values: [ 1, 2 ] }
The emit: StreamEmit.Emit<R, E, A, void>
type represents an asynchronous callback that can emit values multiple times. This callback accepts values of type Effect<Chunk<A>, Option<E>, R>
and provides the following behaviors:
- When the callback succeeds with a
Chunk<A>
, it emits the elements in the chunk to the stream. - If the callback fails with
Some<E>
, it terminates the stream with the specified error. - If the callback fails with
None
, it ends the stream, signaling that there are no further values.
In short, this type lets you define how the callback interacts with the stream, specifying when to emit values, terminate due to an error, or simply end.
To create a stream from any Iterable
(such as an array, set, or custom iterable), use the Stream.fromIterable
constructor. This method provides a simple way to turn a collection of values into a stream.
Example (Creating a Stream from an Iterable)
In this example, we convert a Set
of numbers into a stream:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const numbers: Set<number>
numbers = new var Set: SetConstructor
new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
Set([1, 2, 3])4
5// Create a stream from the Set of numbers6const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const fromIterable: <number>(iterable: Iterable<number>) => Stream.Stream<number, never, never>
Creates a new `Stream` from an iterable collection of values.
fromIterable(const numbers: Set<number>
numbers)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// Output: { _id: 'Chunk', values: [ 1, 2, 3 ] }
If you have an effect that returns an Iterable
, you can use the Stream.fromIterableEffect
constructor to turn the effect’s result into a stream.
Example (Generating a Stream from an Effect)
In this example, imagine a database operation that retrieves a list of users. Since fetching users is an effectful operation, we can transform its result into a stream using Stream.fromIterableEffect
:
1import { import Stream
Stream, import Effect
Effect, import Context
Context } from "effect"2
3// Define a database service with an operation to get users4class class Database
Database extends import Context
Context.const Tag: <"Database">(id: "Database") => <Self, Shape>() => Context.TagClass<Self, "Database", Shape>
namespace Tag
Tag("Database")<5 class Database
Database,6 { readonly (property) getUsers: Effect.Effect<string[], never, never>
getUsers: import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<interface Array<T>
Array<string>> }7>() {}8
9const const getUsers: Effect.Effect<string[], never, Database>
getUsers = class Database
Database.(method) Pipeable.pipe<typeof Database, Effect.Effect<string[], never, Database>>(this: typeof Database, ab: (_: typeof Database) => Effect.Effect<string[], never, Database>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const andThen: <{
readonly getUsers: Effect.Effect<Array<string>>;
}, Effect.Effect<string[], never, never>>(f: (a: {
readonly getUsers: Effect.Effect<Array<string>>;
}) => Effect.Effect<string[], never, never>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)
Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action.
The `that` action can take various forms:
- a value
- a function returning a value
- a promise
- a function returning a promise
- an effect
- a function returning an effect
andThen(((parameter) _: {
readonly getUsers: Effect.Effect<Array<string>>;
}
_) => (parameter) _: {
readonly getUsers: Effect.Effect<Array<string>>;
}
_.(property) getUsers: Effect.Effect<string[], never, never>
getUsers))10
11const const stream: Stream.Stream<string, never, Database>
stream = import Stream
Stream.const fromIterableEffect: <string, never, Database>(effect: Effect.Effect<Iterable<string>, never, Database>) => Stream.Stream<string, never, Database>
Creates a stream from an effect producing a value of type `Iterable<A>`.
fromIterableEffect(const getUsers: Effect.Effect<string[], never, Database>
getUsers)12
13import Effect
Effect.const runPromise: <Chunk<string>, never>(effect: Effect.Effect<Chunk<string>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<string>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(14 import Stream
Stream.const runCollect: <string, never, never>(self: Stream.Stream<string, never, never>) => Effect.Effect<Chunk<string>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(15 const stream: Stream.Stream<string, never, Database>
stream.(method) Pipeable.pipe<Stream.Stream<string, never, Database>, Stream.Stream<string, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, Database>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(16 import Stream
Stream.const provideService: <typeof Database>(tag: typeof Database, resource: {
readonly getUsers: Effect.Effect<Array<string>>;
}) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<...> (+1 overload)
Provides the stream with the single service it requires. If the stream
requires more than one service use `Stream.provideContext` instead.
provideService(class Database
Database, {17 (property) getUsers: Effect.Effect<string[], never, never>
getUsers: import Effect
Effect.const succeed: <string[]>(value: string[]) => Effect.Effect<string[], never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(["user1", "user2"])18 })19 )20 )21).(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)22// Output: { _id: 'Chunk', values: [ 'user1', 'user2' ] }
Async iterables are another type of data source that can be converted into a stream. With the Stream.fromAsyncIterable
constructor, you can work with asynchronous data sources and handle potential errors gracefully.
Example (Streaming from an Async Iterable)
In this example, we define an async iterable and then create a stream from it. An error handler is also provided to capture and process any errors that might occur during conversion.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const delay: (n: number, delay: number) => Promise<unknown>
delay = ((parameter) n: number
n: number, (parameter) delay: number
delay: number) =>4 new var Promise: PromiseConstructor
new <unknown>(executor: (resolve: (value: unknown) => void, reject: (reason?: any) => void) => void) => Promise<unknown>
Creates a new Promise.
Promise(((parameter) resolve: (value: unknown) => void
resolve) => function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => (parameter) resolve: (value: unknown) => void
resolve((parameter) n: number
n), (parameter) delay: number
delay))5
6// Define an async iterable that yields values asynchronously7const const myAsyncIterable: () => AsyncGenerator<unknown, void, unknown>
myAsyncIterable = async function* () {8 yield const delay: (n: number, delay: number) => Promise<unknown>
delay(1, 100)9 yield const delay: (n: number, delay: number) => Promise<unknown>
delay(2, 150)10}11
12// Create a stream from the async iterable, including an error handler13const const stream: Stream.Stream<unknown, Error, never>
stream = import Stream
Stream.const fromAsyncIterable: <unknown, Error>(iterable: AsyncIterable<unknown>, onError: (e: unknown) => Error) => Stream.Stream<unknown, Error, never>
Creates a stream from an `AsyncIterable`.
fromAsyncIterable(14 const myAsyncIterable: () => AsyncGenerator<unknown, void, unknown>
myAsyncIterable(),15 ((parameter) e: unknown
e) => new var Error: ErrorConstructor
new (message?: string) => Error
Error(var String: StringConstructor
(value?: any) => string
Allows manipulation and formatting of text strings and determination and location of substrings within strings.
String((parameter) e: unknown
e)) // Custom error handling16)17
18import Effect
Effect.const runPromise: <Chunk<unknown>, Error>(effect: Effect.Effect<Chunk<unknown>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<unknown>>
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: <unknown, Error, never>(self: Stream.Stream<unknown, Error, never>) => Effect.Effect<Chunk<unknown>, Error, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<unknown, Error, never>
stream)).(method) Promise<Chunk<unknown>>.then<void, never>(onfulfilled?: ((value: Chunk<unknown>) => 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)19// Output: { _id: 'Chunk', values: [ 1, 2 ] }
To create a stream that continuously repeats a single value, use the Stream.repeatValue
constructor.
Example (Creating a Stream of Repeated Values)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Create a stream that endlessly repeats the value 04const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const repeatValue: <number>(value: number) => Stream.Stream<number, never, never>
Repeats the provided value infinitely.
repeatValue(0)5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log8)9// Output: { _id: 'Chunk', values: [ 0, 0, 0, 0, 0 ] }
In this example, the stream emits the value 0
repeatedly. Using Stream.take(5)
, we limit the output to the first five occurrences.
You can use Stream.repeat
to create a stream that continuously repeats the contents of another stream according to a schedule. This approach is useful for generating recurring events or repeating values over time.
Example (Repeating a Stream Sequence on a Schedule)
1import { import Stream
Stream, import Effect
Effect, import Schedule
Schedule } from "effect"2
3// Create a stream that endlessly repeats the values 1, 2, and 34const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const repeat: <number, never, never, number, never>(self: Stream.Stream<number, never, never>, schedule: Schedule.Schedule<number, unknown, never>) => Stream.Stream<number, never, never> (+1 overload)
Repeats the entire stream using the specified schedule. The stream will
execute normally, and then repeat again according to the provided schedule.
repeat(import Stream
Stream.const 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), import Schedule
Schedule.const forever: Schedule.Schedule<number, unknown, never>
A schedule that always recurs, producing a count of repeats: 0, 1, 2.
forever)5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log8)9// Output: { _id: 'Chunk', values: [ 1, 2, 3, 1, 2 ] }
In this example, the stream repeats the sequence [1, 2, 3]
. The Stream.take(5)
operator limits the output to the first five values.
If you have an effectful operation, such as an API call, and want to repeatedly use its result in a stream, you can do this by creating a stream from the effect and repeating it.
Example (Generating a Stream of Random Numbers)
1import { import Stream
Stream, import Effect
Effect, import Random
Random } from "effect"2
3// Create a stream that repeats a random number generation effect4const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const repeatEffect: <number, never, never>(effect: Effect.Effect<number, never, never>) => Stream.Stream<number, never, never>
Creates a stream from an effect producing a value of type `A` which repeats
forever.
repeatEffect(import Random
Random.const nextInt: Effect.Effect<number, never, never>
Returns the next integer value from the pseudo-random number generator.
nextInt)5
6import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log8)9/*10Example Output:11{12 _id: 'Chunk',13 values: [ 1666935266, 604851965, 2194299958, 3393707011, 4090317618 ]14}15*/
In this example, Stream.repeatEffect
continually invokes the random number generator, creating a stream of random numbers. Using Stream.take(5)
, we limit the output to the first five values.
You can evaluate an effect repeatedly to create a stream, with the ability to terminate based on specific conditions.
Example (Creating a Stream from an Iterator with Termination)
In this example, we create a helper function, drainIterator
, that converts an Iterator
into a stream. The stream will continue emitting values from the iterator until it reaches the end.
1import { import Stream
Stream, import Effect
Effect, import Option
Option } from "effect"2
3const const drainIterator: <A>(it: Iterator<A>) => Stream.Stream<A>
drainIterator = <(type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A>((parameter) it: Iterator<A, any, any>
it: interface Iterator<T, TReturn = any, TNext = any>
Iterator<(type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A>): import Stream
Stream.interface Stream<out A, out E = never, out R = never>
namespace Stream
A `Stream<A, E, R>` is a description of a program that, when evaluated, may
emit zero or more values of type `A`, may fail with errors of type `E`, and
uses an context of type `R`. One way to think of `Stream` is as a
`Effect` program that could emit multiple values.
`Stream` is a purely functional *pull* based stream. Pull based streams offer
inherent laziness and backpressure, relieving users of the need to manage
buffers between operators. As an optimization, `Stream` does not emit
single values, but rather an array of values. This allows the cost of effect
evaluation to be amortized.
`Stream` forms a monad on its `A` type parameter, and has error management
facilities for its `E` type parameter, modeled similarly to `Effect` (with
some adjustments for the multiple-valued nature of `Stream`). These aspects
allow for rich and expressive composition of streams.
Stream<(type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A> =>4 import Stream
Stream.const repeatEffectOption: <A, never, never>(effect: Effect.Effect<A, Option.Option<never>, never>) => Stream.Stream<A, never, never>
Creates a stream from an effect producing values of type `A` until it fails
with `None`.
repeatEffectOption(5 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<never, Option.Option<never>, never>>, A>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<never, Option.Option<never>, never>>, A, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {6 const const res: IteratorResult<A, any>
res = (parameter) it: Iterator<A, any, any>
it.(method) Iterator<A, any, any>.next(...[value]: [] | [any]): IteratorResult<A, any>
next()7 if (const res: IteratorResult<A, any>
res.(property) done?: boolean | undefined
done) {8 // End the stream when iterator completes9 return yield* import Effect
Effect.const fail: <Option.Option<never>>(error: Option.Option<never>) => Effect.Effect<never, Option.Option<never>, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail(import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none())10 }11 // Emit the next iterator value12 return const res: IteratorYieldResult<A>
res.(property) IteratorYieldResult<A>.value: A
value13 })14 )15
16import 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(17 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 drainIterator: <number>(it: Iterator<number, any, any>) => Stream.Stream<number, never, never>
drainIterator(new var Set: SetConstructor
new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
Set([1, 2, 3]).(method) Set<number>.values(): SetIterator<number>
Returns an iterable of values in the set.
values()))18).(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)19// Output: { _id: 'Chunk', values: [ 1, 2, 3 ] }
The Stream.tick
constructor lets you create a stream that emits void
values at specified intervals, useful for setting up periodic events or timed triggers.
Example (Emitting Values at Fixed Intervals)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Stream that emits every 100 milliseconds4const const stream: Stream.Stream<void, never, never>
stream = import Stream
Stream.const tick: (interval: DurationInput) => Stream.Stream<void>
A stream that emits void values spaced by the specified duration.
tick("100 millis")5
6import Effect
Effect.const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<void>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<void, never, never>
stream.(method) Pipeable.pipe<Stream.Stream<void, never, never>, Stream.Stream<void, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<void, never, never>) => Stream.Stream<void, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<void>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log8)9/*10Output:11{12 _id: 'Chunk',13 values: [ undefined, undefined, undefined, undefined, undefined ]14}15*/
In this example, the stream emits a void
value every 100 milliseconds. Using Stream.take(5)
, we limit the output to the first five values.
The unfold
function is often thought of as the opposite of reduce
.
In reduce
, we take a data structure and summarize it into a single return value, like calculating the sum of an Array<number>
. By contrast, unfold
starts with an initial value and iteratively builds a data structure, adding one element at a time based on a specified state function. For example, starting from 1
and using an increment function to generate a sequence of natural numbers.
The Stream module provides an unfold
function, defined as follows:
declare const unfold: <S, A>( initialState: S, step: (s: S) => Option.Option<readonly [A, S]>) => Stream<A>
Here’s how it works:
- initialState: The starting value for the stream generation.
- step: A state function that takes the current state
s
as input. If it returnsNone
, the stream ends; if it returnsSome<[A, S]>
,A
is the next element, andS
is updated for the next iteration.
Example (Creating a Stream of Natural Numbers)
1import { import Stream
Stream, import Effect
Effect, import Option
Option } from "effect"2
3const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const unfold: <number, number>(s: number, f: (s: number) => Option.Option<readonly [number, number]>) => Stream.Stream<number, never, never>
Creates a stream by peeling off the "layers" of a value of type `S`.
unfold(1, ((parameter) n: number
n) => import Option
Option.const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>
Creates a new `Option` that wraps the given value.
some([(parameter) n: number
n, (parameter) n: number
n + 1]))4
5import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(6 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log7)8// Output: { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }
For cases where the state transformation itself is effectful, Stream.unfoldEffect
enables working with effects during the unfolding process.
Example (Generating Random Values with Effectful State Transformations)
Here’s an example of creating an infinite stream of random 1
and -1
values:
1import { import Stream
Stream, import Effect
Effect, import Option
Option, import Random
Random } from "effect"2
3const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const unfoldEffect: <number, number, never, never>(s: number, f: (s: number) => Effect.Effect<Option.Option<readonly [number, number]>, never, never>) => Stream.Stream<number, never, never>
Creates a stream by effectfully peeling off the "layers" of a value of type
`S`.
unfoldEffect(1, ((parameter) n: number
n) =>4 import Random
Random.const nextBoolean: Effect.Effect<boolean, never, never>
Returns the next boolean value from the pseudo-random number generator.
nextBoolean.(method) Pipeable.pipe<Effect.Effect<boolean, never, never>, Effect.Effect<Option.Option<[number, number]>, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<boolean, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(5 import Effect
Effect.const map: <boolean, Option.Option<[number, number]>>(f: (a: boolean) => Option.Option<[number, number]>) => <E, R>(self: Effect.Effect<boolean, E, R>) => Effect.Effect<...> (+1 overload)
map(((parameter) b: boolean
b) => ((parameter) b: boolean
b ? import Option
Option.const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>
Creates a new `Option` that wraps the given value.
some([(parameter) n: number
n, -(parameter) n: number
n]) : import Option
Option.const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>
Creates a new `Option` that wraps the given value.
some([(parameter) n: number
n, (parameter) n: number
n])))6 )7)8
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.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Takes the specified number of elements from this stream.
take(5)))).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(10 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log11)12// Example Output: { _id: 'Chunk', values: [ 1, 1, 1, 1, -1 ] }
Stream.paginate
is similar to Stream.unfold
but allows emitting values one step further.
Example (Creating a Simple Paginated Stream)
1import { import Stream
Stream, import Effect
Effect, import Option
Option } from "effect"2
3const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const paginate: <number, number>(s: number, f: (s: number) => readonly [number, Option.Option<number>]) => Stream.Stream<number, never, never>
Like `Stream.unfold`, but allows the emission of values to end one step further
than the unfolding of the state. This is useful for embedding paginated
APIs, hence the name.
paginate(0, ((parameter) n: number
n) => [4 (parameter) n: number
n,5 (parameter) n: number
n < 3 ? import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some((parameter) n: number
n + 1) : import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none()6])7
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// { _id: 'Chunk', values: [ 0, 1, 2, 3 ] }
Here’s how it works:
- Start with an initial value of
0
. - The function takes the current value
n
and returns a tuple. The first item is the emitted value (n
), and the second item decides if the stream continues (Option.some(n + 1)
) or stops (Option.none()
).
The difference between the Stream.unfold
and Stream.paginate
combinators often comes down to how they handle state and control continuation. Let’s explore these distinctions with a practical example.
Imagine a paginated API that returns data in chunks. Each request yields a PageResult
object containing the results for the current page and a flag indicating whether it’s the last page or if there’s more data. Here’s a simple mock of such an API:
1import { import Chunk
Chunk, import Effect
Effect } from "effect"2
3type type RawData = string
RawData = string4
5class class PageResult
PageResult {6 constructor(7 readonly (property) PageResult.results: Chunk.Chunk<string>
results: import Chunk
Chunk.interface Chunk<out A>
namespace Chunk
Chunk<type RawData = string
RawData>,8 readonly (property) PageResult.isLast: boolean
isLast: boolean9 ) {}10}11
12const const pageSize: 2
pageSize = 213
14const const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated = (15 (parameter) pageNumber: number
pageNumber: number16): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<class PageResult
PageResult, interface Error
Error> => {17 return import Effect
Effect.const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(18 new constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult(19 import Chunk
Chunk.const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)
Transforms the elements of a chunk using the specified mapping function.
If the input chunk is non-empty, the resulting chunk will also be non-empty.
map(20 import Chunk
Chunk.const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>
Create a non empty `Chunk` containing a range of integers, including both endpoints.
range(1, const pageSize: 2
pageSize),21 ((parameter) index: number
index) => `Result ${(parameter) pageNumber: number
pageNumber}-${(parameter) index: number
index}`22 ),23 (parameter) pageNumber: number
pageNumber === 2 // Return 3 pages24 )25 )26}
Our goal is to turn this paginated API into a stream of RawData
events.
Initially, we might consider using Stream.unfoldChunkEffect
, a variant of Stream.unfoldEffect
that handles chunks of values rather than single values:
1import { import Chunk
Chunk, import Effect
Effect, import Stream
Stream, import Option
Option } from "effect"2
24 collapsed lines
3type type RawData = string
RawData = string4
5class class PageResult
PageResult {6 constructor(7 readonly (property) PageResult.results: Chunk.Chunk<string>
results: import Chunk
Chunk.interface Chunk<out A>
namespace Chunk
Chunk<type RawData = string
RawData>,8 readonly (property) PageResult.isLast: boolean
isLast: boolean9 ) {}10}11
12const const pageSize: 2
pageSize = 213
14const const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated = (15 (parameter) pageNumber: number
pageNumber: number16): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<class PageResult
PageResult, interface Error
Error> => {17 return import Effect
Effect.const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(18 new constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult(19 import Chunk
Chunk.const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)
Transforms the elements of a chunk using the specified mapping function.
If the input chunk is non-empty, the resulting chunk will also be non-empty.
map(20 import Chunk
Chunk.const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>
Create a non empty `Chunk` containing a range of integers, including both endpoints.
range(1, const pageSize: 2
pageSize),21 ((parameter) index: number
index) => `Result ${(parameter) pageNumber: number
pageNumber}-${(parameter) index: number
index}`22 ),23 (parameter) pageNumber: number
pageNumber === 2 // Return 3 pages24 )25 )26}27
28const const firstAttempt: Stream.Stream<string, Error, never>
firstAttempt = import Stream
Stream.const unfoldChunkEffect: <number, string, Error, never>(s: number, f: (s: number) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<string>, number]>, Error, never>) => Stream.Stream<...>
Creates a stream by effectfully peeling off the "layers" of a value of type
`S`.
unfoldChunkEffect(0, ((parameter) pageNumber: number
pageNumber) =>29 const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated((parameter) pageNumber: number
pageNumber).(method) Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<Option.None<readonly [Chunk.Chunk<string>, number]> | Option.Some<readonly [Chunk.Chunk<string>, number]>, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(30 import Effect
Effect.const map: <PageResult, Option.None<readonly [Chunk.Chunk<string>, number]> | Option.Some<readonly [Chunk.Chunk<string>, number]>>(f: (a: PageResult) => Option.None<...> | Option.Some<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)
map(((parameter) page: PageResult
page) => {31 if ((parameter) page: PageResult
page.(property) PageResult.isLast: boolean
isLast) {32 return import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()33 }34 return import Option
Option.const some: <readonly [Chunk.Chunk<string>, number]>(value: readonly [Chunk.Chunk<string>, number]) => Option.Option<readonly [Chunk.Chunk<string>, number]>
Creates a new `Option` that wraps the given value.
some([(parameter) page: PageResult
page.(property) PageResult.results: Chunk.Chunk<string>
results, (parameter) pageNumber: number
pageNumber + 1] as type const = readonly [Chunk.Chunk<string>, number]
const)35 })36 )37)38
39import Effect
Effect.const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const firstAttempt: Stream.Stream<string, Error, never>
firstAttempt)).(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)40/*41Output:42{43 _id: "Chunk",44 values: [ "Result 0-1", "Result 0-2", "Result 1-1", "Result 1-2" ]45}46*/
However, this approach has a drawback, it doesn’t include the results from the last page.
We could resolve this with extra logic to capture the last page, but this adds complexity:
1import { import Chunk
Chunk, import Effect
Effect, import Stream
Stream, import Option
Option } from "effect"2
24 collapsed lines
3type type RawData = string
RawData = string4
5class class PageResult
PageResult {6 constructor(7 readonly (property) PageResult.results: Chunk.Chunk<string>
results: import Chunk
Chunk.interface Chunk<out A>
namespace Chunk
Chunk<type RawData = string
RawData>,8 readonly (property) PageResult.isLast: boolean
isLast: boolean9 ) {}10}11
12const const pageSize: 2
pageSize = 213
14const const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated = (15 (parameter) pageNumber: number
pageNumber: number16): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<class PageResult
PageResult, interface Error
Error> => {17 return import Effect
Effect.const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(18 new constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult(19 import Chunk
Chunk.const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)
Transforms the elements of a chunk using the specified mapping function.
If the input chunk is non-empty, the resulting chunk will also be non-empty.
map(20 import Chunk
Chunk.const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>
Create a non empty `Chunk` containing a range of integers, including both endpoints.
range(1, const pageSize: 2
pageSize),21 ((parameter) index: number
index) => `Result ${(parameter) pageNumber: number
pageNumber}-${(parameter) index: number
index}`22 ),23 (parameter) pageNumber: number
pageNumber === 2 // Return 3 pages24 )25 )26}27
28const const secondAttempt: Stream.Stream<string, Error, never>
secondAttempt = import Stream
Stream.const unfoldChunkEffect: <Option.Option<number>, string, Error, never>(s: Option.Option<number>, f: (s: Option.Option<number>) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<string>, Option.Option<number>]>, Error, never>) => Stream.Stream<...>
Creates a stream by effectfully peeling off the "layers" of a value of type
`S`.
unfoldChunkEffect(29 import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(0),30 ((parameter) pageNumber: Option.Option<number>
pageNumber) =>31 import Option
Option.const match: <number, Effect.Effect<Option.Option<never>, never, never>, Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>>(self: Option.Option<...>, options: {
...;
}) => Effect.Effect<...> | Effect.Effect<...> (+1 overload)
Matches the given `Option` and returns either the provided `onNone` value or the result of the provided `onSome`
function when passed the `Option`'s value.
match((parameter) pageNumber: Option.Option<number>
pageNumber, {32 // We already hit the last page33 (property) onNone: LazyArg<Effect.Effect<Option.Option<never>, never, never>>
onNone: () => import Effect
Effect.const succeed: <Option.Option<never>>(value: Option.Option<never>) => Effect.Effect<Option.Option<never>, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()),34 // We did not hit the last page yet35 (property) onSome: (a: number) => Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>
onSome: ((parameter) pageNumber: number
pageNumber) =>36 const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated((parameter) pageNumber: number
pageNumber).(method) Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(37 import Effect
Effect.const map: <PageResult, Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>>(f: (a: PageResult) => Option.Option<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)
map(((parameter) page: PageResult
page) =>38 import Option
Option.const some: <[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>(value: [Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]) => Option.Option<...>
Creates a new `Option` that wraps the given value.
some([39 (parameter) page: PageResult
page.(property) PageResult.results: Chunk.Chunk<string>
results,40 (parameter) page: PageResult
page.(property) PageResult.isLast: boolean
isLast ? import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none() : import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some((parameter) pageNumber: number
pageNumber + 1)41 ])42 )43 )44 })45)46
47import Effect
Effect.const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const secondAttempt: Stream.Stream<string, Error, never>
secondAttempt)).(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)48/*49Output:50{51 _id: 'Chunk',52 values: [53 'Result 0-1',54 'Result 0-2',55 'Result 1-1',56 'Result 1-2',57 'Result 2-1',58 'Result 2-2'59 ]60}61*/
While this approach works, it’s clear that Stream.unfoldChunkEffect
isn’t the most friendly option for retrieving data from paginated APIs.
It requires additional workarounds to include the results from the last page.
This is where Stream.paginate
(and its variants) comes to the rescue.
It provides a more ergonomic way to convert a paginated API into a stream. Let’s rewrite our solution using Stream.paginateChunkEffect
:
1import { import Chunk
Chunk, import Effect
Effect, import Stream
Stream, import Option
Option } from "effect"2
24 collapsed lines
3type type RawData = string
RawData = string4
5class class PageResult
PageResult {6 constructor(7 readonly (property) PageResult.results: Chunk.Chunk<string>
results: import Chunk
Chunk.interface Chunk<out A>
namespace Chunk
Chunk<type RawData = string
RawData>,8 readonly (property) PageResult.isLast: boolean
isLast: boolean9 ) {}10}11
12const const pageSize: 2
pageSize = 213
14const const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated = (15 (parameter) pageNumber: number
pageNumber: number16): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<class PageResult
PageResult, interface Error
Error> => {17 return import Effect
Effect.const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(18 new constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult(19 import Chunk
Chunk.const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)
Transforms the elements of a chunk using the specified mapping function.
If the input chunk is non-empty, the resulting chunk will also be non-empty.
map(20 import Chunk
Chunk.const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>
Create a non empty `Chunk` containing a range of integers, including both endpoints.
range(1, const pageSize: 2
pageSize),21 ((parameter) index: number
index) => `Result ${(parameter) pageNumber: number
pageNumber}-${(parameter) index: number
index}`22 ),23 (parameter) pageNumber: number
pageNumber === 2 // Return 3 pages24 )25 )26}27
28const const finalAttempt: Stream.Stream<string, Error, never>
finalAttempt = import Stream
Stream.const paginateChunkEffect: <number, string, Error, never>(s: number, f: (s: number) => Effect.Effect<readonly [Chunk.Chunk<string>, Option.Option<number>], Error, never>) => Stream.Stream<...>
Like `Stream.unfoldChunkEffect`, but allows the emission of values to end one step
further than the unfolding of the state. This is useful for embedding
paginated APIs, hence the name.
paginateChunkEffect(0, ((parameter) pageNumber: number
pageNumber) =>29 const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated((parameter) pageNumber: number
pageNumber).(method) Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<[Chunk.Chunk<string>, Option.Option<number>], Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(30 import Effect
Effect.const andThen: <PageResult, [Chunk.Chunk<string>, Option.Option<number>]>(f: (a: PageResult) => [Chunk.Chunk<string>, Option.Option<number>]) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)
Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action.
The `that` action can take various forms:
- a value
- a function returning a value
- a promise
- a function returning a promise
- an effect
- a function returning an effect
andThen(((parameter) page: PageResult
page) => {31 return [32 (parameter) page: PageResult
page.(property) PageResult.results: Chunk.Chunk<string>
results,33 (parameter) page: PageResult
page.(property) PageResult.isLast: boolean
isLast ? import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none<number>() : import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some((parameter) pageNumber: number
pageNumber + 1)34 ]35 })36 )37)38
39import Effect
Effect.const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const finalAttempt: Stream.Stream<string, Error, never>
finalAttempt)).(method) Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)40/*41Output:42{43 _id: 'Chunk',44 values: [45 'Result 0-1',46 'Result 0-2',47 'Result 1-1',48 'Result 1-2',49 'Result 2-1',50 'Result 2-2'51 ]52}53*/
Effect provides two core asynchronous messaging types: Queue and PubSub. You can convert these data types into Stream
s using Stream.fromQueue
and Stream.fromPubSub
, making it easy to process their emitted values in a stream-based workflow.
To create a stream from a Schedule
, you can use Stream.fromSchedule
, which will emit values as dictated by the schedule’s configuration. This stream will produce an element for each interval specified in the schedule, continuing for the duration of the schedule.
The values emitted from Stream.fromSchedule
are integers, starting from 0
and incrementing by 1
for each tick of the schedule.
Example (Creating a Stream from a Schedule)
1import { import Effect
Effect, import Stream
Stream, import Schedule
Schedule } from "effect"2
3// Configures a schedule to emit a value every 1 second, repeating 5 times4const const schedule: Schedule.Schedule<number, unknown, never>
schedule = import Schedule
Schedule.const spaced: (duration: DurationInput) => Schedule.Schedule<number>
Returns a schedule that recurs continuously, each repetition spaced the
specified duration from the last run.
spaced("1 second").(method) Pipeable.pipe<Schedule.Schedule<number, unknown, never>, Schedule.Schedule<number, unknown, never>>(this: Schedule.Schedule<...>, ab: (_: Schedule.Schedule<number, unknown, never>) => Schedule.Schedule<number, unknown, never>): Schedule.Schedule<...> (+21 overloads)
pipe(5 import Schedule
Schedule.const compose: <number, unknown, never>(that: Schedule.Schedule<number, unknown, never>) => <In, R>(self: Schedule.Schedule<unknown, In, R>) => Schedule.Schedule<number, In, R> (+1 overload)
Returns the composition of this schedule and the specified schedule, by
piping the output of this one into the input of the other. Effects
described by this schedule will always be executed before the effects
described by the second schedule.
compose(import Schedule
Schedule.const recurs: (n: number) => Schedule.Schedule<number>
A schedule spanning all time, which can be stepped only the specified
number of times before it terminates.
recurs(5))6)7
8const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const fromSchedule: <number, never>(schedule: Schedule.Schedule<number, unknown, never>) => Stream.Stream<number, never, never>
Creates a stream from a `Schedule` that does not require any further
input. The stream will emit an element for each value output from the
schedule, continuing for as long as the schedule continues.
fromSchedule(const schedule: Schedule.Schedule<number, unknown, never>
schedule)9
10import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)11/*12Output:13{ _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }14*/