Operations
In this section, we’ll explore some essential operations you can perform on streams. These operations allow you to manipulate and interact with stream elements in various ways.
Tapping is an operation that involves running an effect on each emission of the stream. It allows you to observe each element, perform some effectful operation, and discard the result of this observation. Importantly, the Stream.tap
operation does not alter the elements of the stream, and it does not affect the return type of the stream.
For instance, you can use Stream.tap
to print each element of a stream:
1import { import Stream
Stream, import Console
Console, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`before mapping: ${(parameter) n: number
n}`)),5 import Stream
Stream.const map: <number, number>(f: (a: number) => number) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Transforms the elements of this stream using the supplied function.
map(((parameter) n: number
n) => (parameter) n: number
n * 2),6 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`after mapping: ${(parameter) n: number
n}`))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) 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) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)10/*11Output:12before mapping: 113after mapping: 214before mapping: 215after mapping: 416before mapping: 317after mapping: 618{ _id: 'Chunk', values: [ 2, 4, 6 ] }19*/
Another essential operation is taking elements, which allows you to extract a specific number of elements from a stream. Here are several ways to achieve this:
take
. To extract a fixed number of elements.takeWhile
. To extract elements until a certain condition is met.takeUntil
. To extract elements until a specific condition is met.takeRight
. To extract a specified number of elements from the end.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const 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(0, ((parameter) n: number
n) => (parameter) n: number
n + 1)4
5// Using `take` to extract a fixed number of elements:6const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const take: <number, never, never>(self: Stream.Stream<number, never, never>, n: number) => Stream.Stream<number, never, never> (+1 overload)
Takes the specified number of elements from this stream.
take(const stream: Stream.Stream<number, never, never>
stream, 5)7import 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 s1: Stream.Stream<number, never, never>
s1)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)8/*9Output:10{ _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }11*/12
13// Using `takeWhile` to extract elements while a condition is met:14const const s2: Stream.Stream<number, never, never>
s2 = import Stream
Stream.const takeWhile: <number, never, never>(self: Stream.Stream<number, never, never>, predicate: Predicate<number>) => Stream.Stream<number, never, never> (+3 overloads)
Takes all elements of the stream for as long as the specified predicate
evaluates to `true`.
takeWhile(const stream: Stream.Stream<number, never, never>
stream, ((parameter) n: number
n) => (parameter) n: number
n < 5)15import 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 s2: Stream.Stream<number, never, never>
s2)).(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)16/*17Output:18{ _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }19*/20
21// Using `takeUntil` to extract elements until a condition is met:22const const s3: Stream.Stream<number, never, never>
s3 = import Stream
Stream.const takeUntil: <number, never, never>(self: Stream.Stream<number, never, never>, predicate: Predicate<number>) => Stream.Stream<number, never, never> (+1 overload)
Takes all elements of the stream until the specified predicate evaluates to
`true`.
takeUntil(const stream: Stream.Stream<number, never, never>
stream, ((parameter) n: number
n) => (parameter) n: number
n === 5)23import 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 s3: Stream.Stream<number, never, never>
s3)).(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)24/*25Output:26{ _id: 'Chunk', values: [ 0, 1, 2, 3, 4, 5 ] }27*/28
29// Using `takeRight` to take elements from the end of the stream:30const const s4: Stream.Stream<number, never, never>
s4 = import Stream
Stream.const takeRight: <number, never, never>(self: Stream.Stream<number, never, never>, n: number) => Stream.Stream<number, never, never> (+1 overload)
Takes the last specified number of elements from this stream.
takeRight(const s3: Stream.Stream<number, never, never>
s3, 3)31import 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 s4: Stream.Stream<number, never, never>
s4)).(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)32/*33Output:34{ _id: 'Chunk', values: [ 3, 4, 5 ] }35*/
When working with asynchronous data sources, like async iterables, you often need to consume data in a loop until a certain condition is met. This tutorial introduces how you can achieve similar behavior using Streams in a beginner-friendly manner.
In async iterables, data consumption can continue in a loop until a break or return statement is encountered. To replicate this behavior with Streams, you have a couple of options:
-
Stream.takeUntil: This function allows you to take elements from a stream until a specified condition evaluates to true. It’s akin to breaking out of a loop in async iterables when a certain condition is met.
-
Stream.toPull: The
Stream.toPull
function is another way to replicate looping through async iterables. It returns an effect that repeatedly pulls data chunks from the stream. This effect can fail withNone
when the stream is finished or withSome
error if it fails.
Let’s take a closer look at the second option, Stream.toPull
.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// Simulate a chunked stream4const 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([1, 2, 3, 4, 5]).(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(5 import Stream
Stream.const rechunk: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Re-chunks the elements of the stream into chunks of `n` elements each. The
last chunk might contain less than `n` elements.
rechunk(2)6)7
8const const program: Effect.Effect<never, Option<never>, Scope>
program = import Effect
Effect.const gen: <YieldWrap<Effect.Effect<Effect.Effect<Chunk<number>, Option<never>, never>, never, Scope>> | YieldWrap<Effect.Effect<Chunk<number>, Option<...>, never>>, never>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen(function* () {9 // Create an effect to get data chunks from the stream10 const const getChunk: Effect.Effect<Chunk<number>, Option<never>, never>
getChunk = yield* import Stream
Stream.const toPull: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Effect.Effect<Chunk<number>, Option<never>, never>, never, Scope>
Returns in a scope a ZIO effect that can be used to repeatedly pull chunks
from the stream. The pull effect fails with None when the stream is
finished, or with Some error if it fails, otherwise it returns a chunk of
the stream's output.
toPull(const stream: Stream.Stream<number, never, never>
stream)11
12 // Continuously fetch and process chunks13 while (true) {14 const const chunk: Chunk<number>
chunk = yield* const getChunk: Effect.Effect<Chunk<number>, Option<never>, never>
getChunk15 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(const chunk: Chunk<number>
chunk)16 }17})18
19import Effect
Effect.const runPromise: <never, Option<never>>(effect: Effect.Effect<never, Option<never>, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<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 Effect
Effect.const scoped: <never, Option<never>, Scope>(effect: Effect.Effect<never, Option<never>, Scope>) => Effect.Effect<never, Option<never>, never>
Scopes all resources used in this workflow to the lifetime of the workflow,
ensuring that their finalizers are run as soon as this workflow completes
execution, whether by success, failure, or interruption.
scoped(const program: Effect.Effect<never, Option<never>, Scope>
program)).(method) Promise<never>.then<void, void>(onfulfilled?: ((value: never) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => void | PromiseLike<void>) | 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, 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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error)20/*21Output:22{ _id: 'Chunk', values: [ 1, 2 ] }23{ _id: 'Chunk', values: [ 3, 4 ] }24{ _id: 'Chunk', values: [ 5 ] }25(FiberFailure) Error: {26 "_id": "Option",27 "_tag": "None"28}29*/
In this example, we’re using Stream.toPull
to repeatedly pull data chunks from the stream
. The code enters a loop and continues to fetch and display chunks until there’s no more data left to process.
In this section, we’ll explore how to transform elements within a stream using the Stream.map
family of operations. These operations allow you to apply a function to each element of the stream, producing a new stream with the transformed values.
The Stream.map
operation applies a given function to all elements of the stream, creating another stream with the transformed values. Let’s illustrate this with an example:
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).(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 map: <number, number>(f: (a: number) => number) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Transforms the elements of this stream using the supplied function.
map(((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) 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/*7Output:8{ _id: 'Chunk', values: [ 2, 3, 4 ] }9*/
If your transformation involves effects, you can use Stream.mapEffect
instead. It allows you to apply an effectful function to each element of the stream, producing a new stream with effectful results:
1import { import Stream
Stream, import Random
Random, 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(10, 20, 30).(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(4 import Stream
Stream.const mapEffect: <number, number, never, never>(f: (a: number) => Effect.Effect<number, never, never>, options?: {
readonly concurrency?: number | "unbounded" | undefined;
readonly unordered?: boolean | undefined;
} | undefined) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+3 overloads)
Maps over elements of the stream with the specified effectful function.
mapEffect(((parameter) n: number
n) => import Random
Random.const nextIntBetween: (min: number, max: number) => Effect.Effect<number>
Returns the next integer value in the specified range from the
pseudo-random number generator.
nextIntBetween(0, (parameter) n: number
n))5)6
7import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)8/*9Example Output:10{ _id: 'Chunk', values: [ 5, 9, 22 ] }11*/
You can evaluate effects concurrently using the concurrency
option. It allows you to specify the number of concurrent running effects. The results are emitted downstream in the original order.
Let’s write a simple page downloader that fetches URLs concurrently:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const getUrls: Effect.Effect<string[], never, never>
getUrls = 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(["url0", "url1", "url2"])4
5const const fetchUrl: (url: string) => Effect.Effect<string[], never, never>
fetchUrl = ((parameter) url: string
url: string) =>6 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([7 `Resource 0-${(parameter) url: string
url}`,8 `Resource 1-${(parameter) url: string
url}`,9 `Resource 2-${(parameter) url: string
url}`10 ])11
12const const stream: Stream.Stream<string[], never, never>
stream = import Stream
Stream.const fromIterableEffect: <string, never, never>(effect: Effect.Effect<Iterable<string>, never, never>) => Stream.Stream<string, never, never>
Creates a stream from an effect producing a value of type `Iterable<A>`.
fromIterableEffect(const getUrls: Effect.Effect<string[], never, never>
getUrls).(method) Pipeable.pipe<Stream.Stream<string, never, never>, Stream.Stream<string[], never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, never>) => Stream.Stream<string[], never, never>): Stream.Stream<...> (+21 overloads)
pipe(13 import Stream
Stream.const mapEffect: <string, string[], never, never>(f: (a: string) => Effect.Effect<string[], never, never>, options?: {
readonly concurrency?: number | "unbounded" | undefined;
readonly unordered?: boolean | undefined;
} | undefined) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+3 overloads)
Maps over elements of the stream with the specified effectful function.
mapEffect(const fetchUrl: (url: string) => Effect.Effect<string[], never, never>
fetchUrl, { (property) concurrency?: number | "unbounded" | undefined
concurrency: 4 })14)15
16import 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(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(const stream: Stream.Stream<string[], never, never>
stream)).(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)17/*18Output:19{20 _id: 'Chunk',21 values: [22 [ 'Resource 0-url0', 'Resource 1-url0', 'Resource 2-url0' ],23 [ 'Resource 0-url1', 'Resource 1-url1', 'Resource 2-url1' ],24 [ 'Resource 0-url2', 'Resource 1-url2', 'Resource 2-url2' ]25 ]26}27*/
The Stream.mapAccum
operation is similar to Stream.map
, but it transforms elements statefully and allows you to map and accumulate in a single operation. Let’s see how you can use it to calculate the running total of an input stream:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const runningTotal: (stream: Stream.Stream<number>) => Stream.Stream<number>
runningTotal = (4 (parameter) stream: Stream.Stream<number, never, never>
stream: 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>5): 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> =>6 (parameter) 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 mapAccum: <number, number, number>(s: number, f: (s: number, a: number) => readonly [number, number]) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Statefully maps over the elements of this stream to produce new elements.
mapAccum(0, ((parameter) s: number
s, (parameter) a: number
a) => [(parameter) s: number
s + (parameter) a: number
a, (parameter) s: number
s + (parameter) a: number
a]))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(9 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 runningTotal: (stream: Stream.Stream<number>) => Stream.Stream<number>
runningTotal(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(0, 5)))10).(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, 3, 6, 10, 15 ] }14*/
The Stream.mapConcat
operation is akin to Stream.map
, but it takes things a step further. It maps each element to zero or more elements of type Iterable
and then flattens the entire stream. Let’s illustrate this with an example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const numbers: Stream.Stream<number, never, never>
numbers = import Stream
Stream.const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("1-2-3", "4-5", "6").(method) Pipeable.pipe<Stream.Stream<string, never, never>, Stream.Stream<string, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, never>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const mapConcat: <string, string>(f: (a: string) => Iterable<string>) => <E, R>(self: Stream.Stream<string, E, R>) => Stream.Stream<string, E, R> (+1 overload)
Maps each element to an iterable, and flattens the iterables into the
output of this stream.
mapConcat(((parameter) s: string
s) => (parameter) s: string
s.(method) String.split(separator: string | RegExp, limit?: number): string[] (+1 overload)
Split a string into substrings using the specified separator and return them as an array.
split("-")),5 import Stream
Stream.const map: <string, number>(f: (a: string) => number) => <E, R>(self: Stream.Stream<string, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Transforms the elements of this stream using the supplied function.
map(((parameter) s: string
s) => function parseInt(string: string, radix?: number): number
Converts a string to an integer.
parseInt((parameter) s: string
s))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 numbers: Stream.Stream<number, never, never>
numbers)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{ _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }12*/
In this example, we take a stream of strings like "1-2-3"
and split them into individual numbers, resulting in a flattened stream of integers.
The Stream.as
method allows you to map the success values of a stream to a specified constant value. This can be handy when you want to transform elements into a uniform value. Here’s an example where we map all elements to the null
value:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<null, 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).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<null, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<null, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const as: <null>(value: null) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<null, E, R> (+1 overload)
Maps the success values of this stream to the specified constant value.
as(null))4
5import Effect
Effect.const runPromise: <Chunk<null>, never>(effect: Effect.Effect<Chunk<null>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<null>>
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: <null, never, never>(self: Stream.Stream<null, never, never>) => Effect.Effect<Chunk<null>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<null, never, never>
stream)).(method) Promise<Chunk<null>>.then<void, never>(onfulfilled?: ((value: Chunk<null>) => 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/*7Output:8{ _id: 'Chunk', values: [ null, null, null, null, null ] }9*/
In this case, regardless of the original values in the stream, we’ve mapped them all to null
.
The Stream.filter
operation is like a sieve that lets through elements that meet a specified condition. Think of it as a way to sift through a stream and keep only the elements that satisfy the given criteria. Here’s an example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const 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, 11).(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 filter: <number, number>(predicate: Predicate<number>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+3 overloads)
Filters the elements emitted by this stream using the provided function.
filter(((parameter) n: number
n) => (parameter) n: number
n % 2 === 0))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/*7Output:8{ _id: 'Chunk', values: [ 2, 4, 6, 8, 10 ] }9*/
In this example, we start with a stream of numbers from 1 to 10 and use Stream.filter
to retain only the even numbers (those that satisfy the condition n % 2 === 0
). The result is a filtered stream containing the even numbers from the original stream.
In this section, we’ll explore the concept of stream scanning. Scans are similar to folds, but they provide a historical perspective. Like folds, scans also involve a binary operator and an initial value. However, what makes scans unique is that they emit every intermediate result as part of the stream.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const 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).(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 scan: <number, number>(s: number, f: (s: number, a: number) => number) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Statefully maps over the elements of this stream to produce all
intermediate results of type `S` given an initial S.
scan(0, ((parameter) a: number
a, (parameter) b: number
b) => (parameter) a: number
a + (parameter) b: number
b))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/*7Output:8{ _id: 'Chunk', values: [ 0, 1, 3, 6, 10, 15 ] }9*/
In this example, we have a stream of numbers from 1 to 5, and we use Stream.scan
to perform a cumulative addition starting from an initial value of 0. The result is a stream that emits the accumulated sum at each step: 0, 1, 3, 6, 10, and 15.
Streams scans provide a way to keep a historical record of your stream transformations, which can be invaluable for various applications.
Additionally, if you only need the final result of the scan, you can use Stream.runFold
:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const fold: Effect.Effect<number, never, never>
fold = 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).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Effect.Effect<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Stream
Stream.const runFold: <number, number>(s: number, f: (s: number, a: number) => number) => <E, R>(self: Stream.Stream<number, E, R>) => Effect.Effect<number, E, Exclude<R, Scope>> (+1 overload)
Executes a pure fold over the stream of values - reduces all elements in
the stream to a value of type `S`.
runFold(0, ((parameter) a: number
a, (parameter) b: number
b) => (parameter) a: number
a + (parameter) b: number
b))4
5import Effect
Effect.const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<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(const fold: Effect.Effect<number, never, never>
fold).(method) Promise<number>.then<void, never>(onfulfilled?: ((value: 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) // Output: 15
In this case, Stream.runFold
gives you the final accumulated value, which is 15 in this example.
In this section, we’ll explore the concept of stream draining. Imagine you have a stream filled with effectful operations, but you’re not interested in the values they produce; instead, you want to execute these effects and discard the results. This is where the Stream.drain
function comes into play.
Let’s go through a few examples:
Example (Discarding Values)
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// We create a stream and immediately drain it.4const const s1: Stream.Stream<never, never, never>
s1 = 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).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<never, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<never, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const drain: <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<never, E, R>
Converts this stream to a stream that executes its effects but emits no
elements. Useful for sequencing effects using streams:
drain)5
6import 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 s1: Stream.Stream<never, never, never>
s1)).(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)7/*8Output:9{ _id: 'Chunk', values: [] }10*/
In this example, we have a stream with values from 1 to 5, but we use Stream.drain
to discard these values. As a result, the output stream is empty.
Example (Executing Random Effects)
1import { import Stream
Stream, import Effect
Effect, import Random
Random } from "effect"2
3const const s2: Stream.Stream<number, never, never>
s2 = 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(4 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<number, never, never>>, number>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, never, never>>, number, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {5 const const nextInt: number
nextInt = yield* import Random
Random.const nextInt: Effect.Effect<number, never, never>
Returns the next integer value from the pseudo-random number generator.
nextInt6 const const number: number
number = var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.(method) Math.abs(x: number): number
Returns the absolute value of a number (the value without regard to whether it is positive or negative).
For example, the absolute value of -5 is the same as the absolute value of 5.
abs(const nextInt: number
nextInt % 10)7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(`random number: ${const number: number
number}`)8 return const number: number
number9 })10).(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(3))11
12import 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 s2: Stream.Stream<number, never, never>
s2)).(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)13/*14Example Output:15random number: 716random number: 517random number: 018{ _id: 'Chunk', values: [ 7, 5, 0 ] }19*/20
21const const s3: Stream.Stream<never, never, never>
s3 = import Stream
Stream.const drain: <number, never, never>(self: Stream.Stream<number, never, never>) => Stream.Stream<never, never, never>
Converts this stream to a stream that executes its effects but emits no
elements. Useful for sequencing effects using streams:
drain(const s2: Stream.Stream<number, never, never>
s2)22
23import 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 s3: Stream.Stream<never, never, never>
s3)).(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)24/*25Example Output:26random number: 027random number: 128random number: 729{ _id: 'Chunk', values: [] }30*/
In this example, we create a stream with random effects and collect the values of these effects initially. Later, we use Stream.drain
to execute the same effects without collecting the values. This demonstrates how you can use draining to trigger effectful operations when you’re not interested in the emitted values.
Stream draining can be particularly useful when you need to perform certain actions or cleanup tasks in your application without affecting the main stream of data.
In this section, we’ll explore the Stream.changes
operation, which allows you to detect and emit elements that are different from their preceding elements within the stream.
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, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number, as_5: number, as_6: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 1, 1, 2, 2, 3, 4).(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 changes: <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>
Returns a new stream that only emits elements that are not equal to the
previous element emitted, using natural equality to determine whether two
elements are equal.
changes)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/*7Output:8{ _id: 'Chunk', values: [ 1, 2, 3, 4 ] }9*/
Zipping is a process of combining two or more streams to create a new stream by pairing elements from the input streams. We can achieve this using the Stream.zip
and Stream.zipWith
operators. Let’s dive into some examples:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3// We create two streams and zip them together.4const const s1: Stream.Stream<[number, string], never, never>
s1 = import Stream
Stream.const zip: <number, never, never, string, never, never>(self: Stream.Stream<number, never, never>, that: Stream.Stream<string, never, never>) => Stream.Stream<[number, string], never, never> (+1 overload)
Zips this stream with another point-wise and emits tuples of elements from
both streams.
The new stream will end when one of the sides ends.
zip(5 import Stream
Stream.const make: <[number, number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number, as_5: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5, 6),6 import Stream
Stream.const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("a", "b", "c")7)8
9import Effect
Effect.const runPromise: <Chunk<[number, string]>, never>(effect: Effect.Effect<Chunk<[number, string]>, 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, string], never, never>(self: Stream.Stream<[number, string], never, never>) => Effect.Effect<Chunk<[number, string]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s1: Stream.Stream<[number, string], never, never>
s1)).(method) Promise<Chunk<[number, string]>>.then<void, never>(onfulfilled?: ((value: Chunk<[number, 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)10/*11Output:12{ _id: 'Chunk', values: [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ] }13*/14
15// We create two streams and zip them with custom logic.16const const s2: Stream.Stream<(string | number)[], never, never>
s2 = import Stream
Stream.const zipWith: <number, never, never, string, never, never, (string | number)[]>(left: Stream.Stream<number, never, never>, right: Stream.Stream<string, never, never>, f: (left: number, right: string) => (string | number)[]) => Stream.Stream<...> (+1 overload)
Zips this stream with another point-wise and applies the function to the
paired elements.
The new stream will end when one of the sides ends.
zipWith(17 import Stream
Stream.const make: <[number, number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number, as_5: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5, 6),18 import Stream
Stream.const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("a", "b", "c"),19 ((parameter) n: number
n, (parameter) s: string
s) => [(parameter) n: number
n - (parameter) s: string
s.(property) String.length: number
Returns the length of a String object.
length, (parameter) s: string
s]20)21
22import Effect
Effect.const runPromise: <Chunk<(string | number)[]>, never>(effect: Effect.Effect<Chunk<(string | number)[]>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <(string | number)[], never, never>(self: Stream.Stream<(string | number)[], never, never>) => Effect.Effect<Chunk<(string | number)[]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s2: Stream.Stream<(string | number)[], never, never>
s2)).(method) Promise<Chunk<(string | number)[]>>.then<void, never>(onfulfilled?: ((value: Chunk<(string | number)[]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)23/*24Output:25{ _id: 'Chunk', values: [ [ 0, 'a' ], [ 1, 'b' ], [ 2, 'c' ] ] }26*/
The new stream will end when one of the streams ends.
When one of the input streams ends before the other, you might need to zip with default values. The Stream.zipAll
and Stream.zipAllWith
operations allow you to specify default values for both sides to handle such scenarios. Let’s see an example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<[number, string], never, never>
s1 = import Stream
Stream.const zipAll: <number, never, never, string, never, never>(self: Stream.Stream<number, never, never>, options: {
readonly other: Stream.Stream<string, never, never>;
readonly defaultSelf: number;
readonly defaultOther: string;
}) => Stream.Stream<...> (+1 overload)
Zips this stream with another point-wise, creating a new stream of pairs of
elements from both sides.
The defaults `defaultLeft` and `defaultRight` will be used if the streams
have different lengths and one of the streams has ended before the other.
zipAll(import Stream
Stream.const make: <[number, number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number, as_5: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5, 6), {4 (property) other: Stream.Stream<string, never, never>
other: import Stream
Stream.const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("a", "b", "c"),5 (property) defaultSelf: number
defaultSelf: 0,6 (property) defaultOther: string
defaultOther: "x"7})8
9import Effect
Effect.const runPromise: <Chunk<[number, string]>, never>(effect: Effect.Effect<Chunk<[number, string]>, 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, string], never, never>(self: Stream.Stream<[number, string], never, never>) => Effect.Effect<Chunk<[number, string]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s1: Stream.Stream<[number, string], never, never>
s1)).(method) Promise<Chunk<[number, string]>>.then<void, never>(onfulfilled?: ((value: Chunk<[number, 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)10/*11Output:12{13 _id: 'Chunk',14 values: [15 [ 1, 'a' ],16 [ 2, 'b' ],17 [ 3, 'c' ],18 [ 4, 'x' ],19 [ 5, 'x' ],20 [ 6, 'x' ]21 ]22}23*/24
25const const s2: Stream.Stream<(string | number)[], never, never>
s2 = import Stream
Stream.const zipAllWith: <number, never, never, string, never, never, (string | number)[]>(self: Stream.Stream<number, never, never>, options: {
readonly other: Stream.Stream<string, never, never>;
readonly onSelf: (a: number) => (string | number)[];
readonly onOther: (a2: string) => (string | number)[];
readonly onBoth: (a: number, a2: string) => (string | number)[];
}) => Stream.Stream<...> (+1 overload)
Zips this stream with another point-wise. The provided functions will be
used to create elements for the composed stream.
The functions `left` and `right` will be used if the streams have different
lengths and one of the streams has ended before the other.
zipAllWith(import Stream
Stream.const make: <[number, number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number, as_5: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5, 6), {26 (property) other: Stream.Stream<string, never, never>
other: import Stream
Stream.const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("a", "b", "c"),27 (property) onSelf: (a: number) => (string | number)[]
onSelf: ((parameter) n: number
n) => [(parameter) n: number
n, "x"],28 (property) onOther: (a2: string) => (string | number)[]
onOther: ((parameter) s: string
s) => [0, (parameter) s: string
s],29 (property) onBoth: (a: number, a2: string) => (string | number)[]
onBoth: ((parameter) n: number
n, (parameter) s: string
s) => [(parameter) n: number
n - (parameter) s: string
s.(property) String.length: number
Returns the length of a String object.
length, (parameter) s: string
s]30})31
32import Effect
Effect.const runPromise: <Chunk<(string | number)[]>, never>(effect: Effect.Effect<Chunk<(string | number)[]>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <(string | number)[], never, never>(self: Stream.Stream<(string | number)[], never, never>) => Effect.Effect<Chunk<(string | number)[]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s2: Stream.Stream<(string | number)[], never, never>
s2)).(method) Promise<Chunk<(string | number)[]>>.then<void, never>(onfulfilled?: ((value: Chunk<(string | number)[]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)33/*34Output:35{36 _id: 'Chunk',37 values: [38 [ 0, 'a' ],39 [ 1, 'b' ],40 [ 2, 'c' ],41 [ 4, 'x' ],42 [ 5, 'x' ],43 [ 6, 'x' ]44 ]45}46*/
This allows you to handle zipping when one stream completes earlier than the other.
Sometimes, you might have two streams producing elements at different speeds. If you don’t want to wait for the slower one when zipping elements, you can use Stream.zipLatest
or Stream.zipLatestWith
. These operations combine elements in a way that when a value is emitted by either of the two streams, it is combined with the latest value from the other stream to produce a result. Here’s an example:
1import { import Stream
Stream, import Schedule
Schedule, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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"))5)6
7const const s2: Stream.Stream<string, never, never>
s2 = import Stream
Stream.const make: <[string, string, string, string]>(as_0: string, as_1: string, as_2: string, as_3: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("a", "b", "c", "d").(method) Pipeable.pipe<Stream.Stream<string, never, never>, Stream.Stream<string, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, never>) => Stream.Stream<string, never, never>): Stream.Stream<...> (+21 overloads)
pipe(8 import Stream
Stream.const schedule: <number, string, never, string>(schedule: Schedule.Schedule<number, string, never>) => <E, R>(self: Stream.Stream<string, E, R>) => Stream.Stream<string, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("500 millis"))9)10
11const const stream: Stream.Stream<[number, string], never, never>
stream = import Stream
Stream.const zipLatest: <number, never, never, string, never, never>(left: Stream.Stream<number, never, never>, right: Stream.Stream<string, never, never>) => Stream.Stream<[number, string], never, never> (+1 overload)
Zips the two streams so that when a value is emitted by either of the two
streams, it is combined with the latest value from the other stream to
produce a result.
Note: tracking the latest value is done on a per-chunk basis. That means
that emitted elements that are not the last value in chunks will never be
used for zipping.
zipLatest(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<string, never, never>
s2)12
13import Effect
Effect.const runPromise: <Chunk<[number, string]>, never>(effect: Effect.Effect<Chunk<[number, string]>, 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, string], never, never>(self: Stream.Stream<[number, string], never, never>) => Effect.Effect<Chunk<[number, string]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<[number, string], never, never>
stream)).(method) Promise<Chunk<[number, string]>>.then<void, never>(onfulfilled?: ((value: Chunk<[number, 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)14/*15Output:16{17 _id: 'Chunk',18 values: [19 [ 1, 'a' ],20 [ 1, 'b' ],21 [ 2, 'b' ],22 [ 2, 'c' ],23 [ 2, 'd' ],24 [ 3, 'd' ]25 ]26}27*/
Here, Stream.zipLatest
combines elements from both streams without waiting for the slower one, resulting in a more responsive output.
-
zipWithPrevious
: This operator pairs each element of a stream with its previous element. -
zipWithNext
: It pairs each element of a stream with its next element. -
zipWithPreviousAndNext
: This operator pairs each element with both its previous and next elements.
Here’s an example illustrating these operations:
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, number]>(as_0: number, as_1: number, as_2: number, as_3: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4)4
5const const s1: Stream.Stream<[Option<number>, number], never, never>
s1 = import Stream
Stream.const zipWithPrevious: <number, never, never>(self: Stream.Stream<number, never, never>) => Stream.Stream<[Option<number>, number], never, never>
Zips each element with the previous element. Initially accompanied by
`None`.
zipWithPrevious(const stream: Stream.Stream<number, never, never>
stream)6
7const const s2: Stream.Stream<[number, Option<number>], never, never>
s2 = import Stream
Stream.const zipWithNext: <number, never, never>(self: Stream.Stream<number, never, never>) => Stream.Stream<[number, Option<number>], never, never>
Zips each element with the next element if present.
zipWithNext(const stream: Stream.Stream<number, never, never>
stream)8
9const const s3: Stream.Stream<[Option<number>, number, Option<number>], never, never>
s3 = import Stream
Stream.const zipWithPreviousAndNext: <number, never, never>(self: Stream.Stream<number, never, never>) => Stream.Stream<[Option<number>, number, Option<number>], never, never>
Zips each element with both the previous and next element.
zipWithPreviousAndNext(const stream: Stream.Stream<number, never, never>
stream)10
11import Effect
Effect.const runPromise: <Chunk<[Option<number>, number]>, never>(effect: Effect.Effect<Chunk<[Option<number>, 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: <[Option<number>, number], never, never>(self: Stream.Stream<[Option<number>, number], never, never>) => Effect.Effect<Chunk<[Option<number>, number]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s1: Stream.Stream<[Option<number>, number], never, never>
s1)).(method) Promise<Chunk<[Option<number>, number]>>.then<void, never>(onfulfilled?: ((value: Chunk<[Option<number>, 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(((parameter) chunks: Chunk<[Option<number>, number]>
chunks) =>12 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("%o", (parameter) chunks: Chunk<[Option<number>, number]>
chunks)13)14/*15Output:16{17 _id: 'Chunk',18 values: [19 [ { _id: 'Option', _tag: 'None' }, 1, [length]: 2 ],20 [ { _id: 'Option', _tag: 'Some', value: 1 }, 2, [length]: 2 ],21 [ { _id: 'Option', _tag: 'Some', value: 2 }, 3, [length]: 2 ],22 [ { _id: 'Option', _tag: 'Some', value: 3 }, 4, [length]: 2 ],23 [length]: 424 ]25}26*/27
28import Effect
Effect.const runPromise: <Chunk<[number, Option<number>]>, never>(effect: Effect.Effect<Chunk<[number, Option<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, Option<number>], never, never>(self: Stream.Stream<[number, Option<number>], never, never>) => Effect.Effect<Chunk<[number, Option<number>]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s2: Stream.Stream<[number, Option<number>], never, never>
s2)).(method) Promise<Chunk<[number, Option<number>]>>.then<void, never>(onfulfilled?: ((value: Chunk<[number, Option<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(((parameter) chunks: Chunk<[number, Option<number>]>
chunks) =>29 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("%o", (parameter) chunks: Chunk<[number, Option<number>]>
chunks)30)31/*32Output:33{34 _id: 'Chunk',35 values: [36 [ 1, { _id: 'Option', _tag: 'Some', value: 2 }, [length]: 2 ],37 [ 2, { _id: 'Option', _tag: 'Some', value: 3 }, [length]: 2 ],38 [ 3, { _id: 'Option', _tag: 'Some', value: 4 }, [length]: 2 ],39 [ 4, { _id: 'Option', _tag: 'None' }, [length]: 2 ],40 [length]: 441 ]42}43*/44
45import Effect
Effect.const runPromise: <Chunk<[Option<number>, number, Option<number>]>, never>(effect: Effect.Effect<Chunk<[Option<number>, number, Option<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: <[Option<number>, number, Option<number>], never, never>(self: Stream.Stream<[Option<number>, number, Option<number>], never, never>) => Effect.Effect<...>
Runs the stream and collects all of its elements to a chunk.
runCollect(const s3: Stream.Stream<[Option<number>, number, Option<number>], never, never>
s3)).(method) Promise<Chunk<[Option<number>, number, Option<number>]>>.then<void, never>(onfulfilled?: ((value: Chunk<[Option<number>, number, Option<number>]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(((parameter) chunks: Chunk<[Option<number>, number, Option<number>]>
chunks) =>46 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("%o", (parameter) chunks: Chunk<[Option<number>, number, Option<number>]>
chunks)47)48/*49Output:50{51 _id: 'Chunk',52 values: [53 [54 { _id: 'Option', _tag: 'None' },55 1,56 { _id: 'Option', _tag: 'Some', value: 2 },57 [length]: 358 ],59 [60 { _id: 'Option', _tag: 'Some', value: 1 },61 2,62 { _id: 'Option', _tag: 'Some', value: 3 },63 [length]: 364 ],65 [66 { _id: 'Option', _tag: 'Some', value: 2 },67 3,68 { _id: 'Option', _tag: 'Some', value: 4 },69 [length]: 370 ],71 [72 { _id: 'Option', _tag: 'Some', value: 3 },73 4,74 { _id: 'Option', _tag: 'None' },75 [length]: 376 ],77 [length]: 478 ]79}80*/
Another handy operator is Stream.zipWithIndex
, which indexes each element of a stream by pairing it with its respective index. This is especially useful when you need to keep track of the position of elements within the stream.
Here’s an example of indexing elements in a stream:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<string, never, never>
stream = import Stream
Stream.const make: <[string, string, string, string]>(as_0: string, as_1: string, as_2: string, as_3: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("Mary", "James", "Robert", "Patricia")4
5const const indexedStream: Stream.Stream<[string, number], never, never>
indexedStream = import Stream
Stream.const zipWithIndex: <string, never, never>(self: Stream.Stream<string, never, never>) => Stream.Stream<[string, number], never, never>
Zips this stream together with the index of elements.
zipWithIndex(const stream: Stream.Stream<string, never, never>
stream)6
7import Effect
Effect.const runPromise: <Chunk<[string, number]>, never>(effect: Effect.Effect<Chunk<[string, number]>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <[string, number], never, never>(self: Stream.Stream<[string, number], never, never>) => Effect.Effect<Chunk<[string, number]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const indexedStream: Stream.Stream<[string, number], never, never>
indexedStream)).(method) Promise<Chunk<[string, number]>>.then<void, never>(onfulfilled?: ((value: Chunk<[string, number]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)8/*9Output:10{11 _id: 'Chunk',12 values: [13 [ 'Mary', 0 ],14 [ 'James', 1 ],15 [ 'Robert', 2 ],16 [ 'Patricia', 3 ]17 ]18}19*/
The Stream module introduces a powerful feature: the ability to compute the Cartesian Product of two streams. This operation allows you to generate combinations of elements from two separate streams. Let’s explore this concept further:
Imagine you have two sets of items, and you want to generate all possible pairs by taking one item from each set. This process is known as finding the Cartesian Product of the sets. In the context of streams, it means creating combinations of elements from two streams.
To achieve this, the Stream module provides the Stream.cross
operator, along with its variants. These operators take two streams and generate a new stream containing all possible combinations of elements from the original streams.
Here’s a practical example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3)4const const s2: Stream.Stream<string, never, never>
s2 = import Stream
Stream.const make: <[string, string]>(as_0: string, as_1: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("a", "b")5
6const const product: Stream.Stream<[number, string], never, never>
product = import Stream
Stream.const cross: <number, never, never, string, never, never>(left: Stream.Stream<number, never, never>, right: Stream.Stream<string, never, never>) => Stream.Stream<[number, string], never, never> (+1 overload)
Composes this stream with the specified stream to create a cartesian
product of elements. The `right` stream would be run multiple times, for
every element in the `left` stream.
See also `Stream.zip` for the more common point-wise variant.
cross(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<string, never, never>
s2)7
8import Effect
Effect.const runPromise: <Chunk<[number, string]>, never>(effect: Effect.Effect<Chunk<[number, string]>, 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, string], never, never>(self: Stream.Stream<[number, string], never, never>) => Effect.Effect<Chunk<[number, string]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const product: Stream.Stream<[number, string], never, never>
product)).(method) Promise<Chunk<[number, string]>>.then<void, never>(onfulfilled?: ((value: Chunk<[number, string]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{12 _id: 'Chunk',13 values: [14 [ 1, 'a' ],15 [ 1, 'b' ],16 [ 2, 'a' ],17 [ 2, 'b' ],18 [ 3, 'a' ],19 [ 3, 'b' ]20 ]21}22*/
It’s important to note that the right-hand side stream (s2
in this case) will be iterated multiple times, once for each element in the left-hand side stream (s1
). This means that if the right-hand side stream involves expensive or side-effectful operations, they will be executed multiple times.
Partitioning a stream means dividing it into two separate streams based on a specified condition. The Stream module provides two helpful functions for achieving this: Stream.partition
and Stream.partitionEither
. Let’s explore how these functions work and when to use them.
The Stream.partition
function takes a predicate as input and splits the original stream into two substreams: one containing elements that satisfy the predicate (evaluate to true
), and the other containing elements that do not (evaluate to false
). Additionally, these substreams are wrapped within a Scope
type.
Here’s an example where we partition a stream of numbers into even and odd numbers:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const partition: Effect.Effect<[excluded: Stream.Stream<number, never, never>, satisfying: Stream.Stream<number, never, never>], never, Scope>
partition = 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, 9).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Effect.Effect<[excluded: Stream.Stream<number, never, never>, satisfying: Stream.Stream<number, never, never>], never, Scope>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(4 import Stream
Stream.const partition: <number>(predicate: Predicate<number>, options?: {
bufferSize?: number | undefined;
} | undefined) => <E, R>(self: Stream.Stream<number, E, R>) => Effect.Effect<...> (+3 overloads)
Partition a stream using a predicate. The first stream will contain all
element evaluated to true and the second one will contain all element
evaluated to false. The faster stream may advance by up to buffer elements
further than the slower one.
partition(((parameter) n: number
n) => (parameter) n: number
n % 2 === 0, { (property) bufferSize?: number | undefined
bufferSize: 5 })5)6
7import Effect
Effect.const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<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(8 import Effect
Effect.const scoped: <void, never, Scope>(effect: Effect.Effect<void, never, Scope>) => Effect.Effect<void, never, never>
Scopes all resources used in this workflow to the lifetime of the workflow,
ensuring that their finalizers are run as soon as this workflow completes
execution, whether by success, failure, or interruption.
scoped(9 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<[excluded: Stream.Stream<number, never, never>, satisfying: Stream.Stream<number, never, never>], never, Scope>> | YieldWrap<...>, void>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen(function* () {10 const [const evens: Stream.Stream<number, never, never>
evens, const odds: Stream.Stream<number, never, never>
odds] = yield* const partition: Effect.Effect<[excluded: Stream.Stream<number, never, never>, satisfying: Stream.Stream<number, never, never>], never, Scope>
partition11 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(yield* 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 evens: Stream.Stream<number, never, never>
evens))12 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(yield* 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 odds: Stream.Stream<number, never, never>
odds))13 })14 )15)16/*17Output:18{ _id: 'Chunk', values: [ 2, 4, 6, 8 ] }19{ _id: 'Chunk', values: [ 1, 3, 5, 7, 9 ] }20*/
In this example, we use the Stream.partition
function with a predicate to split the stream into even and odd numbers. The bufferSize
option controls how much the faster stream can advance beyond the slower one.
Sometimes, you may need to partition a stream using an effectful predicate. For such cases, the Stream.partitionEither
function is available. This function accepts an effectful predicate and divides the stream into two substreams based on the result of the predicate: elements that yield Either.left
values go to one substream, while elements yielding Either.right
values go to the other.
Here’s an example where we use Stream.partitionEither
to partition a stream of numbers based on an effectful condition:
1import { import Stream
Stream, import Effect
Effect, import Either
Either } from "effect"2
3const const partition: Effect.Effect<[left: Stream.Stream<number, never, never>, right: Stream.Stream<number, never, never>], never, Scope>
partition = 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, 9).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Effect.Effect<[left: Stream.Stream<number, never, never>, right: Stream.Stream<number, never, never>], never, Scope>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(4 import Stream
Stream.const partitionEither: <number, number, number, never, never>(predicate: (a: number) => Effect.Effect<Either.Either<number, number>, never, never>, options?: {
readonly bufferSize?: number | undefined;
} | undefined) => <E, R>(self: Stream.Stream<...>) => Effect.Effect<...> (+1 overload)
Split a stream by an effectful predicate. The faster stream may advance by
up to buffer elements further than the slower one.
partitionEither(5 ((parameter) n: number
n) => import Effect
Effect.const succeed: <Either.Either<never, number> | Either.Either<number, never>>(value: Either.Either<never, number> | Either.Either<number, never>) => Effect.Effect<...>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed((parameter) n: number
n % 2 === 0 ? import Either
Either.const left: <number>(left: number) => Either.Either<never, number>
Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this
structure.
left((parameter) n: number
n) : import Either
Either.const right: <number>(right: number) => Either.Either<number, never>
Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias
of this structure.
right((parameter) n: number
n)),6 { (property) bufferSize?: number | undefined
bufferSize: 5 }7 )8)9
10import Effect
Effect.const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<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(11 import Effect
Effect.const scoped: <void, never, Scope>(effect: Effect.Effect<void, never, Scope>) => Effect.Effect<void, never, never>
Scopes all resources used in this workflow to the lifetime of the workflow,
ensuring that their finalizers are run as soon as this workflow completes
execution, whether by success, failure, or interruption.
scoped(12 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<[left: Stream.Stream<number, never, never>, right: Stream.Stream<number, never, never>], never, Scope>> | YieldWrap<...>, void>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen(function* () {13 const [const evens: Stream.Stream<number, never, never>
evens, const odds: Stream.Stream<number, never, never>
odds] = yield* const partition: Effect.Effect<[left: Stream.Stream<number, never, never>, right: Stream.Stream<number, never, never>], never, Scope>
partition14 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(yield* 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 evens: Stream.Stream<number, never, never>
evens))15 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(yield* 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 odds: Stream.Stream<number, never, never>
odds))16 })17 )18)19/*20Output:21{ _id: 'Chunk', values: [ 2, 4, 6, 8 ] }22{ _id: 'Chunk', values: [ 1, 3, 5, 7, 9 ] }23*/
In this case, the Stream.partitionEither
function splits the stream into two substreams: one containing values that are less than 5 (doubled using Either.left
), and the other containing values greater than or equal to 5 (using Either.right
).
When working with streams of data, you may often need to group elements based on certain criteria. The Stream module provides two functions for achieving this: groupByKey
and groupBy
. Let’s explore how these functions work and when to use them.
The Stream.groupByKey
function allows you to partition a stream by a simple function of type (a: A) => K
, where A
represents the type of elements in your stream, and K
represents the keys by which the stream should be partitioned.
This function is not effectful, it simply groups elements by applying the provided function.
The Stream.groupByKey
function returns a new data type called GroupBy
.
This GroupBy
type represents a grouped stream.
To work with the groups, you can use the GroupBy.evaluate
function, which takes a function of type (key: K, stream: Stream<V, E>) => Stream.Stream<...>
. This function runs across all groups and merges them in a non-deterministic fashion.
In the example below, we use groupByKey
to group exam results by the tens place of their scores and count the number of results in each group:
1import { import Stream
Stream, import GroupBy
GroupBy, import Effect
Effect, import Chunk
Chunk } from "effect"2
3class class Exam
Exam {4 constructor(readonly (property) Exam.person: string
person: string, readonly (property) Exam.score: number
score: number) {}5}6
7const const examResults: Exam[]
examResults = [8 new constructor Exam(person: string, score: number): Exam
Exam("Alex", 64),9 new constructor Exam(person: string, score: number): Exam
Exam("Michael", 97),10 new constructor Exam(person: string, score: number): Exam
Exam("Bill", 77),11 new constructor Exam(person: string, score: number): Exam
Exam("John", 78),12 new constructor Exam(person: string, score: number): Exam
Exam("Bobby", 71)13]14
15const const groupByKeyResult: GroupBy.GroupBy<number, Exam, never, never>
groupByKeyResult = import Stream
Stream.const fromIterable: <Exam>(iterable: Iterable<Exam>) => Stream.Stream<Exam, never, never>
Creates a new `Stream` from an iterable collection of values.
fromIterable(const examResults: Exam[]
examResults).(method) Pipeable.pipe<Stream.Stream<Exam, never, never>, GroupBy.GroupBy<number, Exam, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<Exam, never, never>) => GroupBy.GroupBy<...>): GroupBy.GroupBy<...> (+21 overloads)
pipe(16 import Stream
Stream.const groupByKey: <Exam, number>(f: (a: Exam) => number, options?: {
readonly bufferSize?: number | undefined;
}) => <E, R>(self: Stream.Stream<Exam, E, R>) => GroupBy.GroupBy<...> (+1 overload)
Partition a stream using a function and process each stream individually.
This returns a data structure that can be used to further filter down which
groups shall be processed.
After calling apply on the GroupBy object, the remaining groups will be
processed in parallel and the resulting streams merged in a
nondeterministic fashion.
Up to `buffer` elements may be buffered in any group stream before the
producer is backpressured. Take care to consume from all streams in order
to prevent deadlocks.
For example, to collect the first 2 words for every starting letter from a
stream of words:
```ts
import * as GroupBy from "./GroupBy"
import * as Stream from "./Stream"
import { pipe } from "./Function"
pipe(
Stream.fromIterable(["hello", "world", "hi", "holla"]),
Stream.groupByKey((word) => word[0]),
GroupBy.evaluate((key, stream) =>
pipe(
stream,
Stream.take(2),
Stream.map((words) => [key, words] as const)
)
)
)
```
groupByKey(((parameter) exam: Exam
exam) => var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.(method) Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
floor((parameter) exam: Exam
exam.(property) Exam.score: number
score / 10) * 10)17)18
19const const stream: Stream.Stream<readonly [number, number], never, never>
stream = import GroupBy
GroupBy.const evaluate: <number, Exam, never, never, readonly [number, number], never, never>(self: GroupBy.GroupBy<number, Exam, never, never>, f: (key: number, stream: Stream.Stream<Exam, never, never>) => Stream.Stream<...>, options?: {
readonly bufferSize?: number | undefined;
} | undefined) => Stream.Stream<...> (+1 overload)
Run the function across all groups, collecting the results in an
arbitrary order.
evaluate(const groupByKeyResult: GroupBy.GroupBy<number, Exam, never, never>
groupByKeyResult, ((parameter) key: number
key, (parameter) stream: Stream.Stream<Exam, never, never>
stream) =>20 import Stream
Stream.const fromEffect: <readonly [number, number], never, never>(effect: Effect.Effect<readonly [number, number], never, never>) => Stream.Stream<readonly [number, number], never, never>
Either emits the success value of this effect or terminates the stream
with the failure value of this effect.
fromEffect(21 import Stream
Stream.const runCollect: <Exam, never, never>(self: Stream.Stream<Exam, never, never>) => Effect.Effect<Chunk.Chunk<Exam>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect((parameter) stream: Stream.Stream<Exam, never, never>
stream).(method) Pipeable.pipe<Effect.Effect<Chunk.Chunk<Exam>, never, never>, Effect.Effect<readonly [number, number], never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<Chunk.Chunk<Exam>, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(22 import Effect
Effect.const andThen: <Chunk.Chunk<Exam>, readonly [number, number]>(f: (a: Chunk.Chunk<Exam>) => readonly [number, number]) => <E, R>(self: Effect.Effect<Chunk.Chunk<Exam>, E, R>) => 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) chunk: Chunk.Chunk<Exam>
chunk) => [(parameter) key: number
key, import Chunk
Chunk.const size: <Exam>(self: Chunk.Chunk<Exam>) => number
Retireves the size of the chunk
size((parameter) chunk: Chunk.Chunk<Exam>
chunk)] as type const = readonly [number, number]
const)23 )24 )25)26
27import Effect
Effect.const runPromise: <Chunk.Chunk<readonly [number, number]>, never>(effect: Effect.Effect<Chunk.Chunk<readonly [number, 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: <readonly [number, number], never, never>(self: Stream.Stream<readonly [number, number], never, never>) => Effect.Effect<Chunk.Chunk<readonly [number, number]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<readonly [number, number], never, never>
stream)).(method) Promise<Chunk<readonly [number, number]>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<readonly [number, 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)28/*29Output:30{ _id: 'Chunk', values: [ [ 60, 1 ], [ 90, 1 ], [ 70, 3 ] ] }31*/
In this example, we partition the exam results into groups based on the tens place of their scores (e.g., 60, 90, 70). The groupByKey
function is ideal for simple, non-effectful partitioning.
In more complex scenarios where partitioning involves effects, you can turn to the Stream.groupBy
function. This function takes an effectful partitioning function and generates a GroupBy
data type, representing a grouped stream. You can then use GroupBy.evaluate
in a similar fashion as before to process the groups.
In the following example, we group names by their first character and count the number of names in each group. Note that the partitioning operation itself is simulated as effectful:
1import { import Stream
Stream, import GroupBy
GroupBy, import Effect
Effect, import Chunk
Chunk } from "effect"2
3const const groupByKeyResult: GroupBy.GroupBy<string, string, never, never>
groupByKeyResult = import Stream
Stream.const fromIterable: <string>(iterable: Iterable<string>) => Stream.Stream<string, never, never>
Creates a new `Stream` from an iterable collection of values.
fromIterable([4 "Mary",5 "James",6 "Robert",7 "Patricia",8 "John",9 "Jennifer",10 "Rebecca",11 "Peter"12]).(method) Pipeable.pipe<Stream.Stream<string, never, never>, GroupBy.GroupBy<string, string, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, never>) => GroupBy.GroupBy<string, string, never, never>): GroupBy.GroupBy<...> (+21 overloads)
pipe(13 import Stream
Stream.const groupBy: <string, string, string, never, never>(f: (a: string) => Effect.Effect<readonly [string, string], never, never>, options?: {
readonly bufferSize?: number | undefined;
} | undefined) => <E, R>(self: Stream.Stream<...>) => GroupBy.GroupBy<...> (+1 overload)
More powerful version of `Stream.groupByKey`.
groupBy(((parameter) name: string
name) => import Effect
Effect.const succeed: <[string, string]>(value: [string, string]) => Effect.Effect<[string, 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([(parameter) name: string
name.(method) String.substring(start: number, end?: number): string
Returns the substring at the specified location within a String object.
substring(0, 1), (parameter) name: string
name]))14)15
16const const stream: Stream.Stream<readonly [string, number], never, never>
stream = import GroupBy
GroupBy.const evaluate: <string, string, never, never, readonly [string, number], never, never>(self: GroupBy.GroupBy<string, string, never, never>, f: (key: string, stream: Stream.Stream<string, never, never>) => Stream.Stream<...>, options?: {
readonly bufferSize?: number | undefined;
} | undefined) => Stream.Stream<...> (+1 overload)
Run the function across all groups, collecting the results in an
arbitrary order.
evaluate(const groupByKeyResult: GroupBy.GroupBy<string, string, never, never>
groupByKeyResult, ((parameter) key: string
key, (parameter) stream: Stream.Stream<string, never, never>
stream) =>17 import Stream
Stream.const fromEffect: <readonly [string, number], never, never>(effect: Effect.Effect<readonly [string, number], never, never>) => Stream.Stream<readonly [string, number], never, never>
Either emits the success value of this effect or terminates the stream
with the failure value of this effect.
fromEffect(18 import Stream
Stream.const runCollect: <string, never, never>(self: Stream.Stream<string, never, never>) => Effect.Effect<Chunk.Chunk<string>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect((parameter) stream: Stream.Stream<string, never, never>
stream).(method) Pipeable.pipe<Effect.Effect<Chunk.Chunk<string>, never, never>, Effect.Effect<readonly [string, number], never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<Chunk.Chunk<string>, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(19 import Effect
Effect.const andThen: <Chunk.Chunk<string>, readonly [string, number]>(f: (a: Chunk.Chunk<string>) => readonly [string, number]) => <E, R>(self: Effect.Effect<Chunk.Chunk<string>, E, R>) => 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) chunk: Chunk.Chunk<string>
chunk) => [(parameter) key: string
key, import Chunk
Chunk.const size: <string>(self: Chunk.Chunk<string>) => number
Retireves the size of the chunk
size((parameter) chunk: Chunk.Chunk<string>
chunk)] as type const = readonly [string, number]
const)20 )21 )22)23
24import Effect
Effect.const runPromise: <Chunk.Chunk<readonly [string, number]>, never>(effect: Effect.Effect<Chunk.Chunk<readonly [string, number]>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <readonly [string, number], never, never>(self: Stream.Stream<readonly [string, number], never, never>) => Effect.Effect<Chunk.Chunk<readonly [string, number]>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<readonly [string, number], never, never>
stream)).(method) Promise<Chunk<readonly [string, number]>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<readonly [string, number]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)25/*26Output:27{28 _id: 'Chunk',29 values: [ [ 'M', 1 ], [ 'J', 3 ], [ 'R', 2 ], [ 'P', 2 ] ]30}31*/
When working with streams, you may encounter situations where you need to group elements in a more structured manner. The Stream module provides two helpful functions for achieving this: grouped
and groupedWithin
. In this section, we’ll explore how these functions work and when to use them.
The Stream.grouped
function is perfect for partitioning stream results into chunks of a specified size. It’s especially useful when you want to work with data in smaller, more manageable pieces.
Here’s an example that demonstrates the use of Stream.grouped
:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<Chunk<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(0, 8).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<Chunk<number>, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<Chunk<number>, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const grouped: (chunkSize: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk<A>, E, R> (+1 overload)
Partitions the stream with specified `chunkSize`.
grouped(3))4
5import 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: <Chunk<number>, never, never>(self: Stream.Stream<Chunk<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<Chunk<number>, never, never>
stream)).(method) Promise<Chunk<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(((parameter) chunks: Chunk<Chunk<number>>
chunks) =>6 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log("%o", (parameter) chunks: Chunk<Chunk<number>>
chunks)7)8/*9Output:10{11 _id: 'Chunk',12 values: [13 { _id: 'Chunk', values: [ 0, 1, 2, [length]: 3 ] },14 { _id: 'Chunk', values: [ 3, 4, 5, [length]: 3 ] },15 { _id: 'Chunk', values: [ 6, 7, 8, [length]: 3 ] },16 [length]: 317 ]18}19*/
In this example, we take a stream of numbers from 0 to 9 and use Stream.grouped(3)
to divide it into chunks of size 3.
The Stream.groupedWithin
function provides more flexibility by allowing you to group events based on time intervals or chunk size, whichever condition is satisfied first. This is particularly useful when you want to group data based on time constraints.
1import { import Stream
Stream, import Schedule
Schedule, import Effect
Effect, import Chunk
Chunk } from "effect"2
3const const stream: Stream.Stream<Chunk.Chunk<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(0, 9).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<Chunk.Chunk<number>, never, never>, Stream.Stream<Chunk.Chunk<number>, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const repeat: <number, never>(schedule: Schedule.Schedule<number, unknown, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+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 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")),5 import Stream
Stream.const groupedWithin: (chunkSize: number, duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R> (+1 overload)
Partitions the stream with the specified `chunkSize` or until the specified
`duration` has passed, whichever is satisfied first.
groupedWithin(18, "1.5 seconds"),6 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(3)7)8
9import Effect
Effect.const runPromise: <Chunk.Chunk<Chunk.Chunk<number>>, never>(effect: Effect.Effect<Chunk.Chunk<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: <Chunk.Chunk<number>, never, never>(self: Stream.Stream<Chunk.Chunk<number>, never, never>) => Effect.Effect<Chunk.Chunk<Chunk.Chunk<number>>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<Chunk.Chunk<number>, never, never>
stream)).(method) Promise<Chunk<Chunk<number>>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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(((parameter) chunks: Chunk.Chunk<Chunk.Chunk<number>>
chunks) =>10 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(import Chunk
Chunk.const toArray: <Chunk.Chunk<Chunk.Chunk<number>>>(self: Chunk.Chunk<Chunk.Chunk<number>>) => Chunk.Chunk<number>[]
Converts a `Chunk` into an `Array`. If the provided `Chunk` is non-empty
(`NonEmptyChunk`), the function will return a `NonEmptyArray`, ensuring the
non-empty property is preserved.
toArray((parameter) chunks: Chunk.Chunk<Chunk.Chunk<number>>
chunks))11)12/*13Output:14[15 {16 _id: 'Chunk',17 values: [18 0, 1, 2, 3, 4, 5, 6,19 7, 8, 9, 0, 1, 2, 3,20 4, 5, 6, 721 ]22 },23 {24 _id: 'Chunk',25 values: [26 8, 9, 0, 1, 2,27 3, 4, 5, 6, 7,28 8, 929 ]30 },31 {32 _id: 'Chunk',33 values: [34 0, 1, 2, 3, 4, 5, 6,35 7, 8, 9, 0, 1, 2, 3,36 4, 5, 6, 737 ]38 }39]40*/
In this example, we use Stream.groupedWithin(18, "1.5 seconds")
to create chunks of data. The grouping operation occurs either when 18 elements are reached or when 1.5 seconds have passed since the last chunk was created. This is particularly useful when dealing with time-sensitive data or when you want to control the chunk size dynamically.
In stream processing, there are scenarios where you may want to combine the contents of multiple streams. The Stream module provides several operators for achieving this, including Stream.concat
, Stream.concatAll
, and Stream.flatMap
. Let’s explore these operators and understand how to use them effectively.
The Stream.concat
operator is a straightforward way to concatenate two streams. It returns a new stream that emits elements from the left-hand stream followed by elements from the right-hand stream. This is useful when you want to combine two streams in a sequential manner.
Here’s an example of using Stream.concat
:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3)4const const s2: Stream.Stream<number, never, never>
s2 = import Stream
Stream.const make: <[number, number]>(as_0: number, as_1: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(4, 5)5
6const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const concat: <number, never, never, number, never, never>(self: Stream.Stream<number, never, never>, that: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never> (+1 overload)
Concatenates the specified stream with this stream, resulting in a stream
that emits the elements from this stream and then the elements from the
specified stream.
concat(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2)7
8import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{ _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }12*/
Sometimes you may have multiple streams that you want to concatenate together. Instead of manually chaining Stream.concat
operations, you can use Stream.concatAll
to concatenate a Chunk
of streams.
Here’s an example:
1import { import Stream
Stream, import Effect
Effect, import Chunk
Chunk } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3)4const const s2: Stream.Stream<number, never, never>
s2 = import Stream
Stream.const make: <[number, number]>(as_0: number, as_1: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(4, 5)5const const s3: Stream.Stream<number, never, never>
s3 = 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(6, 7, 8)6
7const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const concatAll: <number, never, never>(streams: Chunk.Chunk<Stream.Stream<number, never, never>>) => Stream.Stream<number, never, never>
Concatenates all of the streams in the chunk to one stream.
concatAll(import Chunk
Chunk.const make: <[Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>]>(as_0: Stream.Stream<number, never, never>, as_1: Stream.Stream<...>, as_2: Stream.Stream<...>) => Chunk.NonEmptyChunk<...>
Builds a `NonEmptyChunk` from an non-empty collection of elements.
make(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2, const s3: Stream.Stream<number, never, never>
s3))8
9import 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)10/*11Output:12{13 _id: 'Chunk',14 values: [15 1, 2, 3, 4,16 5, 6, 7, 817 ]18}19*/
The Stream.flatMap
operator allows you to create a stream whose elements are generated by applying a function of type (a: A) => Stream<...>
to each output of the source stream. It concatenates all of the results.
Here’s an example of using Stream.flatMap
:
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).(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(4 import Stream
Stream.const flatMap: <number, number, never, never>(f: (a: number) => Stream.Stream<number, never, never>, options?: {
readonly concurrency?: number | "unbounded" | undefined;
readonly bufferSize?: number | undefined;
readonly switch?: boolean | undefined;
} | undefined) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+1 overload)
Returns a stream made of the concatenation in strict order of all the
streams produced by passing each element of this stream to `f0`
flatMap(((parameter) a: number
a) => import Stream
Stream.const repeatValue: <number>(value: number) => Stream.Stream<number, never, never>
Repeats the provided value infinitely.
repeatValue((parameter) a: number
a).(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(4)))5)6
7import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)8/*9Output:10{11 _id: 'Chunk',12 values: [13 1, 1, 1, 1, 2,14 2, 2, 2, 3, 3,15 3, 316 ]17}18*/
If we need to do the flatMap
concurrently, we can use the concurrency
option, and also if the order of concatenation is not important for us, we can use the switch
option.
Sometimes we need to interleave the emission of two streams and create another stream. In these cases, we can’t use the Stream.concat
operation because the concat operation waits for the first stream to finish and then consumes the second stream. So we need a way of picking elements from different sources. Effect Stream’s merge operations does this for us. Let’s discuss some variants of this operation:
The Stream.merge
operation allows us to pick elements from different source streams and merge them into a single stream. Unlike Stream.concat
, which waits for the first stream to finish before moving to the second, Stream.merge
interleaves elements from both streams as they become available.
Here’s an example:
1import { import Schedule
Schedule, import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("100 millis"))5)6const const s2: Stream.Stream<number, never, never>
s2 = 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(4, 5, 6).(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(7 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("200 millis"))8)9
10const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const merge: <number, never, never, number, never, never>(self: Stream.Stream<number, never, never>, that: Stream.Stream<number, never, never>, options?: {
readonly haltStrategy?: HaltStrategyInput | undefined;
} | undefined) => Stream.Stream<...> (+1 overload)
Merges this stream and the specified stream together.
New produced stream will terminate when both specified stream terminate if
no termination strategy is specified.
merge(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2)11
12import 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)13/*14Output:15{ _id: 'Chunk', values: [ 1, 4, 2, 3, 5, 6 ] }16*/
When merging two streams, we should consider their termination strategy. Each stream has its own lifetime, some may finish quickly, while others may continue indefinitely. By default, when using Stream.merge
, the resulting stream terminates only when both specified streams terminate.
However, you can define the termination strategy to align with your requirements. Stream offers four different termination strategies using the haltStrategy
option:
"left"
. The resulting stream will terminate when the left-hand side stream terminates."right"
. The resulting stream will terminate when the right-hand side stream finishes."both"
. The resulting stream will terminate when both streams finish."either"
. The resulting stream will terminate when one of the streams finishes.
Here’s an example of specifying a termination strategy:
1import { import Stream
Stream, import Schedule
Schedule, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = 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).(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(4 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("100 millis"))5)6const const s2: Stream.Stream<number, never, never>
s2 = import Stream
Stream.const repeatValue: <number>(value: number) => Stream.Stream<number, never, never>
Repeats the provided value infinitely.
repeatValue(0).(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(7 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("200 millis"))8)9
10const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const merge: <number, never, never, number, never, never>(self: Stream.Stream<number, never, never>, that: Stream.Stream<number, never, never>, options?: {
readonly haltStrategy?: HaltStrategyInput | undefined;
} | undefined) => Stream.Stream<...> (+1 overload)
Merges this stream and the specified stream together.
New produced stream will terminate when both specified stream terminate if
no termination strategy is specified.
merge(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2, { (property) haltStrategy?: HaltStrategyInput | undefined
haltStrategy: "left" })11
12import 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)13/*14Output:15{16 _id: 'Chunk',17 values: [18 1, 0, 2, 3,19 0, 4, 520 ]21}22*/
In this example, we use haltStrategy: "left"
to make the resulting stream terminate when the left-hand stream (s1
) finishes.
In some cases, we not only want to merge two streams but also transform and unify their elements into new types. This is where Stream.mergeWith
comes into play. It allows us to specify transformation functions for both source streams.
Here’s an example:
1import { import Schedule
Schedule, import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<string, never, never>
s1 = import Stream
Stream.const make: <[string, string, string]>(as_0: string, as_1: string, as_2: string) => Stream.Stream<string, never, never>
Creates a stream from an sequence of values.
make("1", "2", "3").(method) Pipeable.pipe<Stream.Stream<string, never, never>, Stream.Stream<string, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, never>) => Stream.Stream<string, never, never>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const schedule: <number, string, never, string>(schedule: Schedule.Schedule<number, string, never>) => <E, R>(self: Stream.Stream<string, E, R>) => Stream.Stream<string, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("100 millis"))5)6const const s2: Stream.Stream<number, never, never>
s2 = 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(4.1, 5.3, 6.2).(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(7 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("200 millis"))8)9
10const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const mergeWith: <string, never, never, number, never, never, number, number>(self: Stream.Stream<string, never, never>, other: Stream.Stream<number, never, never>, options: {
readonly onSelf: (a: string) => number;
readonly onOther: (a2: number) => number;
readonly haltStrategy?: HaltStrategyInput | undefined;
}) => Stream.Stream<...> (+1 overload)
Merges this stream and the specified stream together to a common element
type with the specified mapping functions.
New produced stream will terminate when both specified stream terminate if
no termination strategy is specified.
mergeWith(const s1: Stream.Stream<string, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2, {11 (property) onSelf: (a: string) => number
onSelf: ((parameter) s: string
s) => function parseInt(string: string, radix?: number): number
Converts a string to an integer.
parseInt((parameter) s: string
s),12 (property) onOther: (a2: number) => number
onOther: ((parameter) n: number
n) => var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.(method) Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
floor((parameter) n: number
n)13})14
15import 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)16/*17Output:18{ _id: 'Chunk', values: [ 1, 4, 2, 3, 5, 6 ] }19*/
In this example, we use Stream.mergeWith
to merge s1
and s2
while converting string elements from s1
to integers and rounding decimal elements from s2
.
The Stream.interleave
operator allows us to pull one element at a time from each of two streams, creating a new interleaved stream. Once one of the streams is exhausted, the remaining values from the other stream are pulled.
Here’s an example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3)4const const s2: Stream.Stream<number, never, never>
s2 = 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(4, 5, 6)5
6const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const interleave: <number, never, never, number, never, never>(self: Stream.Stream<number, never, never>, that: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never> (+1 overload)
Interleaves this stream and the specified stream deterministically by
alternating pulling values from this stream and the specified stream. When
one stream is exhausted all remaining values in the other stream will be
pulled.
interleave(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2)7
8import Effect
Effect.const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<number, never, never>
stream)).(method) Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)9/*10Output:11{ _id: 'Chunk', values: [ 1, 4, 2, 5, 3, 6 ] }12*/
For more advanced interleaving logic, Stream.interleaveWith
provides additional flexibility. It allows you to specify the interleaving logic using a third stream of boolean
values. When the boolean stream emits true
, it chooses elements from the left-hand stream; otherwise, it selects elements from the right-hand stream.
Here’s an example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const s1: Stream.Stream<number, never, never>
s1 = import Stream
Stream.const make: <[number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 3, 5, 7, 9)4const const s2: Stream.Stream<number, never, never>
s2 = import Stream
Stream.const make: <[number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(2, 4, 6, 8, 10)5
6const const booleanStream: Stream.Stream<boolean, never, never>
booleanStream = import Stream
Stream.const make: <[boolean, boolean, boolean]>(as_0: boolean, as_1: boolean, as_2: boolean) => Stream.Stream<boolean, never, never>
Creates a stream from an sequence of values.
make(true, false, false).(method) Pipeable.pipe<Stream.Stream<boolean, never, never>, Stream.Stream<boolean, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<boolean, never, never>) => Stream.Stream<boolean, never, never>): Stream.Stream<...> (+21 overloads)
pipe(import Stream
Stream.const forever: <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>
Repeats this stream forever.
forever)7
8const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const interleaveWith: <number, never, never, number, never, never, never, never>(self: Stream.Stream<number, never, never>, that: Stream.Stream<number, never, never>, decider: Stream.Stream<boolean, never, never>) => Stream.Stream<...> (+1 overload)
Combines this stream and the specified stream deterministically using the
stream of boolean values `pull` to control which stream to pull from next.
A value of `true` indicates to pull from this stream and a value of `false`
indicates to pull from the specified stream. Only consumes as many elements
as requested by the `pull` stream. If either this stream or the specified
stream are exhausted further requests for values from that stream will be
ignored.
interleaveWith(const s1: Stream.Stream<number, never, never>
s1, const s2: Stream.Stream<number, never, never>
s2, const booleanStream: Stream.Stream<boolean, never, never>
booleanStream)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{14 _id: 'Chunk',15 values: [16 1, 2, 4, 3, 6,17 8, 5, 10, 7, 918 ]19}20*/
In this example, booleanStream
decides which source stream to choose for interleaving. When true
, it picks elements from s1
, and when false
, it selects elements from s2
.
Interspersing is a technique that allows you to add separators in a stream. This can be especially useful when you want to format or structure the data in your streams.
The Stream.intersperse
operator lets you intersperse a delimiter element between the elements of a stream. This delimiter can be any value you choose. It’s added between each pair of elements in the original stream.
Here’s an example:
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, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5).(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 intersperse: <number>(element: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)
Intersperse stream with provided `element`.
intersperse(0))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/*7Output:8{9 _id: 'Chunk',10 values: [11 1, 0, 2, 0, 3,12 0, 4, 0, 513 ]14}15*/
In this example, we have a stream stream
with numbers from 1 to 5, and we use Stream.intersperse(0)
to add zeros between them.
For more advanced interspersing needs, Stream.intersperseAffixes
provides greater control. It allows you to specify different affixes for the start, middle, and end of your stream. These affixes can be strings or any other values you want.
Here’s an example:
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3const const stream: Stream.Stream<string | number, never, never>
stream = import Stream
Stream.const make: <[number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<string | number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<string | number, never, never>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const intersperseAffixes: <string, string, string>(options: {
readonly start: string;
readonly middle: string;
readonly end: string;
}) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<string | A, E, R> (+1 overload)
Intersperse the specified element, also adding a prefix and a suffix.
intersperseAffixes({5 (property) start: string
start: "[",6 (property) middle: string
middle: "-",7 (property) end: string
end: "]"8 })9)10
11import Effect
Effect.const runPromise: <Chunk<string | number>, never>(effect: Effect.Effect<Chunk<string | number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(import Stream
Stream.const runCollect: <string | number, never, never>(self: Stream.Stream<string | number, never, never>) => Effect.Effect<Chunk<string | number>, never, never>
Runs the stream and collects all of its elements to a chunk.
runCollect(const stream: Stream.Stream<string | number, never, never>
stream)).(method) Promise<Chunk<string | number>>.then<void, never>(onfulfilled?: ((value: Chunk<string | number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)12/*13Output:14{15 _id: 'Chunk',16 values: [17 '[', 1, '-', 2, '-',18 3, '-', 4, '-', 5,19 ']'20 ]21}22*/
In this example, we use Stream.intersperseAffixes
to enclose the numbers from 1 to 5 within square brackets, separating them with hyphens.
Broadcasting a stream is a way to create multiple streams that contain the same elements as the source stream. This operation allows you to send each element to multiple downstream streams simultaneously. However, the upstream stream can emit events only up to a certain limit, which is determined by the maximumLag
parameter. Once this limit is reached, the upstream stream slows down to match the speed of the slowest downstream stream.
Let’s take a closer look at how broadcasting works in the following example. Here, we are broadcasting a stream of numbers to two downstream streams. One of them calculates the maximum number in the stream, while the other performs some logging with an additional delay. The upstream stream adjusts its speed based on the slower logging stream:
1import { import Effect
Effect, import Stream
Stream, import Console
Console, import Schedule
Schedule, import Fiber
Fiber } from "effect"2
3const const numbers: Effect.Effect<Chunk<void>, never, never>
numbers = import Effect
Effect.const scoped: <Chunk<void>, never, never>(effect: Effect.Effect<Chunk<void>, never, never>) => Effect.Effect<Chunk<void>, never, never>
Scopes all resources used in this workflow to the lifetime of the workflow,
ensuring that their finalizers are run as soon as this workflow completes
execution, whether by success, failure, or interruption.
scoped(4 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, 20).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Effect.Effect<[Stream.Stream<number, never, never>, Stream.Stream<number, never, never>], never, Scope>, Stream.Stream<...>, Effect.Effect<...>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Effect.Effect<...>, cd: (_: Effect.Effect<...>) => Stream.Stream<...>, de: (_: Stream.Stream<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(5 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) =>6 import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`Emit ${(parameter) n: number
n} element before broadcasting`)7 ),8 import Stream
Stream.const broadcast: <2>(n: 2, maximumLag: number | {
readonly capacity: "unbounded";
readonly replay?: number | undefined;
} | {
readonly capacity: number;
readonly strategy?: "sliding" | "dropping" | "suspend" | undefined;
readonly replay?: number | undefined;
}) => <A, E, R>(self: Stream.Stream<...>) => Effect.Effect<...> (+1 overload)
Fan out the stream, producing a list of streams that have the same elements
as this stream. The driver stream will only ever advance the `maximumLag`
chunks before the slowest downstream stream.
broadcast(2, 5),9 import Stream
Stream.const flatMap: <[Stream.Stream<number, never, never>, Stream.Stream<number, never, never>], void, never, never>(f: (a: [Stream.Stream<number, never, never>, Stream.Stream<number, never, never>]) => Stream.Stream<...>, options?: {
readonly concurrency?: number | "unbounded" | undefined;
readonly bufferSize?: number | undefined;
readonly switch?: boolean | undefined;
} | undefined) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+1 overload)
Returns a stream made of the concatenation in strict order of all the
streams produced by passing each element of this stream to `f0`
flatMap(([(parameter) first: Stream.Stream<number, never, never>
first, (parameter) second: Stream.Stream<number, never, never>
second]) =>10 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<Fiber.RuntimeFiber<void, never>, never, never>> | YieldWrap<Effect.Effect<[void, void], never, never>>, void>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen(function* () {11 const const fiber1: Fiber.RuntimeFiber<void, never>
fiber1 = yield* import Stream
Stream.const runFold: <number, never, never, number>(self: Stream.Stream<number, never, never>, s: number, f: (s: number, a: number) => number) => Effect.Effect<number, never, never> (+1 overload)
Executes a pure fold over the stream of values - reduces all elements in
the stream to a value of type `S`.
runFold((parameter) first: Stream.Stream<number, never, never>
first, 0, ((parameter) acc: number
acc, (parameter) e: number
e) =>12 var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.(method) Math.max(...values: number[]): number
Returns the larger of a set of supplied numeric expressions.
max((parameter) acc: number
acc, (parameter) e: number
e)13 ).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<void, never, never>, Effect.Effect<Fiber.RuntimeFiber<void, never>, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(14 import Effect
Effect.const andThen: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => 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) max: number
max) => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`Maximum: ${(parameter) max: number
max}`)),15 import Effect
Effect.const fork: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>
Returns an effect that forks this effect into its own separate fiber,
returning the fiber immediately, without waiting for it to begin executing
the effect.
You can use the `fork` method whenever you want to execute an effect in a
new fiber, concurrently and without "blocking" the fiber executing other
effects. Using fibers can be tricky, so instead of using this method
directly, consider other higher-level methods, such as `raceWith`,
`zipPar`, and so forth.
The fiber returned by this method has methods to interrupt the fiber and to
wait for it to finish executing the effect. See `Fiber` for more
information.
Whenever you use this method to launch a new fiber, the new fiber is
attached to the parent fiber's scope. This means when the parent fiber
terminates, the child fiber will be terminated as well, ensuring that no
fibers leak. This behavior is called "auto supervision", and if this
behavior is not desired, you may use the `forkDaemon` or `forkIn` methods.
fork16 )17 const const fiber2: Fiber.RuntimeFiber<void, never>
fiber2 = yield* (parameter) second: Stream.Stream<number, never, never>
second.(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Effect.Effect<void, never, never>, Effect.Effect<Fiber.RuntimeFiber<void, never>, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Effect.Effect<...>, cd: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(18 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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")),19 import Stream
Stream.const runForEach: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Effect.Effect<void, E, R> (+1 overload)
Consumes all elements of the stream, passing them to the specified
callback.
runForEach(((parameter) n: number
n) =>20 import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`Logging to the Console: ${(parameter) n: number
n}`)21 ),22 import Effect
Effect.const fork: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>
Returns an effect that forks this effect into its own separate fiber,
returning the fiber immediately, without waiting for it to begin executing
the effect.
You can use the `fork` method whenever you want to execute an effect in a
new fiber, concurrently and without "blocking" the fiber executing other
effects. Using fibers can be tricky, so instead of using this method
directly, consider other higher-level methods, such as `raceWith`,
`zipPar`, and so forth.
The fiber returned by this method has methods to interrupt the fiber and to
wait for it to finish executing the effect. See `Fiber` for more
information.
Whenever you use this method to launch a new fiber, the new fiber is
attached to the parent fiber's scope. This means when the parent fiber
terminates, the child fiber will be terminated as well, ensuring that no
fibers leak. This behavior is called "auto supervision", and if this
behavior is not desired, you may use the `forkDaemon` or `forkIn` methods.
fork23 )24 yield* import Fiber
Fiber.const join: <void, never>(self: Fiber.Fiber<void, never>) => Effect.Effect<void, never, never>
Joins the fiber, which suspends the joining fiber until the result of the
fiber has been determined. Attempting to join a fiber that has erred will
result in a catchable error. Joining an interrupted fiber will result in an
"inner interruption" of this fiber, unlike interruption triggered by
another fiber, "inner interruption" can be caught and recovered.
join(const fiber1: Fiber.RuntimeFiber<void, never>
fiber1).(method) Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<[void, void], never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<[void, void], never, never>): Effect.Effect<...> (+21 overloads)
pipe(25 import Effect
Effect.const zip: <void, never, never>(that: Effect.Effect<void, never, never>, options?: {
readonly concurrent?: boolean | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
} | undefined) => <A, E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)
The `Effect.zip` function allows you to combine two effects into a single
effect. This combined effect yields a tuple containing the results of both
input effects once they succeed.
Note that `Effect.zip` processes effects sequentially: it first completes the
effect on the left and then the effect on the right.
If you want to run the effects concurrently, you can use the `concurrent` option.
zip(import Fiber
Fiber.const join: <void, never>(self: Fiber.Fiber<void, never>) => Effect.Effect<void, never, never>
Joins the fiber, which suspends the joining fiber until the result of the
fiber has been determined. Attempting to join a fiber that has erred will
result in a catchable error. Joining an interrupted fiber will result in an
"inner interruption" of this fiber, unlike interruption triggered by
another fiber, "inner interruption" can be caught and recovered.
join(const fiber2: Fiber.RuntimeFiber<void, never>
fiber2), { (property) concurrent?: boolean | undefined
concurrent: true })26 )27 })28 ),29 import Stream
Stream.const runCollect: <A, E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<Chunk<A>, E, Exclude<R, Scope>>
Runs the stream and collects all of its elements to a chunk.
runCollect30 )31)32
33import 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(const numbers: Effect.Effect<Chunk<void>, never, never>
numbers).(method) Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<void>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)34/*35Output:36Emit 1 element before broadcasting37Emit 2 element before broadcasting38Emit 3 element before broadcasting39Emit 4 element before broadcasting40Emit 5 element before broadcasting41Emit 6 element before broadcasting42Emit 7 element before broadcasting43Emit 8 element before broadcasting44Emit 9 element before broadcasting45Emit 10 element before broadcasting46Emit 11 element before broadcasting47Logging to the Console: 148Logging to the Console: 249Logging to the Console: 350Logging to the Console: 451Logging to the Console: 552Emit 12 element before broadcasting53Emit 13 element before broadcasting54Emit 14 element before broadcasting55Emit 15 element before broadcasting56Emit 16 element before broadcasting57Logging to the Console: 658Logging to the Console: 759Logging to the Console: 860Logging to the Console: 961Logging to the Console: 1062Emit 17 element before broadcasting63Emit 18 element before broadcasting64Emit 19 element before broadcasting65Emit 20 element before broadcasting66Logging to the Console: 1167Logging to the Console: 1268Logging to the Console: 1369Logging to the Console: 1470Logging to the Console: 1571Maximum: 2072Logging to the Console: 1673Logging to the Console: 1774Logging to the Console: 1875Logging to the Console: 1976Logging to the Console: 2077{ _id: 'Chunk', values: [ undefined ] }78*/
Effect streams operate in a pull-based manner, which means downstream consumers can request elements at their own pace without needing to signal the upstream to slow down. However, there are scenarios where you might need to handle producers and consumers independently, especially when there’s a speed mismatch between them. This is where buffering comes into play, allowing you to manage communication between a faster producer and a slower consumer effectively. Effect streams provide a built-in Stream.buffer
operator to assist with this.
The Stream.buffer
operator is designed to facilitate scenarios where a faster producer needs to work independently of a slower consumer. It achieves this by buffering elements in a queue, allowing the producer to continue working even if the consumer lags behind. You can specify the maximum buffer capacity using the capacity
option.
Let’s walk through an example to see how it works:
1import { import Stream
Stream, import Console
Console, import Schedule
Schedule, import Effect
Effect } from "effect"2
3const 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, 10).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<...>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>, de: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(4 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`before buffering: ${(parameter) n: number
n}`)),5 import Stream
Stream.const buffer: (options: {
readonly capacity: "unbounded";
} | {
readonly capacity: number;
readonly strategy?: "dropping" | "sliding" | "suspend" | undefined;
}) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Allows a faster producer to progress independently of a slower consumer by
buffering up to `capacity` elements in a queue.
Note: This combinator destroys the chunking structure. It's recommended to
use rechunk afterwards. Additionally, prefer capacities that are powers
of 2 for better performance.
buffer({ (property) capacity: number
capacity: 4 }),6 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`after buffering: ${(parameter) n: number
n}`)),7 import Stream
Stream.const schedule: <number, number, never, number>(schedule: Schedule.Schedule<number, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
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("5 seconds"))8)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) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)11/*12Output:13before buffering: 114before buffering: 215before buffering: 316before buffering: 417before buffering: 518before buffering: 619after buffering: 120after buffering: 221before buffering: 722after buffering: 323before buffering: 824after buffering: 425before buffering: 926after buffering: 527before buffering: 1028...29*/
In this example, we create a stream of numbers from 1 to 11. We use Stream.buffer({ capacity: 4 })
to buffer up to 4 elements at a time. As you can see, the Stream.tap
operator allows us to log each element before and after buffering. We’ve also introduced a 5-second delay between each emission to illustrate the lag between producing and consuming messages.
You can choose from different buffering options based on the type of underlying queue you need:
- Bounded Queue:
{ capacity: number }
- Unbounded Queue:
{ capacity: "unbounded" }
- Sliding Queue:
{ capacity: number, strategy: "sliding" }
- Dropping Queue:
{ capacity: number, strategy: "dropping" }
Debouncing in programming is used to ensure that a function doesn’t fire too frequently. This can be especially useful in scenarios where a stream emits values in rapid succession but you only need to react after a pause in activity.
The Stream.debounce
function in the Effect library exemplifies this by delaying the emission of stream values.
It waits for a specified duration to pass without any new values before emitting the latest value.
If a new value arrives during this waiting period, the current value is discarded and the timer resets with the new value.
1import { import Stream
Stream, import Effect
Effect } from "effect"2
3let let last: number
last = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()4const const log: (message: string) => Effect.Effect<void, never, never>
log = ((parameter) message: string
message: string) =>5 import Effect
Effect.const sync: <void>(thunk: LazyArg<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents a synchronous side-effectful computation.
The provided function (`thunk`) should not throw errors; if it does, the error is treated as a defect.
Use `Effect.sync` when you are certain the operation will not fail.
sync(() => {6 const const end: number
end = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(`${(parameter) message: string
message} after ${const end: number
end - let last: number
last}ms`)8 let last: number
last = const end: number
end9 })10
11const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<...>, Stream.Stream<...>, Stream.Stream<...>, Stream.Stream<...>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>, de: (_: Stream.Stream<...>) => Stream.Stream<...>, ef: (_: Stream.Stream<...>) => Stream.Stream<...>, fg: (_: Stream.Stream<...>) => Stream.Stream<...>, gh: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(12 import Stream
Stream.const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)
Concatenates the specified stream with this stream, resulting in a stream
that emits the elements from this stream and then the elements from the
specified stream.
concat(13 // Emit the value 4 after 200 ms14 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 Effect
Effect.const sleep: (duration: DurationInput) => Effect.Effect<void>
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
sleep("200 millis").(method) Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)
This function maps the success value of an `Effect` value to a specified
constant value.
as(4)))15 ),16 import Stream
Stream.const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)
Concatenates the specified stream with this stream, resulting in a stream
that emits the elements from this stream and then the elements from the
specified stream.
concat(import Stream
Stream.const make: <[number, number]>(as_0: number, as_1: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(5, 6)), // Continue with more rapid values17 import Stream
Stream.const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)
Concatenates the specified stream with this stream, resulting in a stream
that emits the elements from this stream and then the elements from the
specified stream.
concat(18 // Emit 7 after 150 ms19 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 Effect
Effect.const sleep: (duration: DurationInput) => Effect.Effect<void>
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
sleep("150 millis").(method) Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)
This function maps the success value of an `Effect` value to a specified
constant value.
as(7)))20 ),21 import Stream
Stream.const concat: <number, never, never>(that: Stream.Stream<number, never, never>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<number | A, E, R> (+1 overload)
Concatenates the specified stream with this stream, resulting in a stream
that emits the elements from this stream and then the elements from the
specified stream.
concat(import Stream
Stream.const make: <[number]>(as_0: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(8)),22 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`Received ${(parameter) n: number
n}`)),23 // Only emit values after a pause of at least 100 milliseconds24 import Stream
Stream.const debounce: (duration: DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)
Delays the emission of values by holding new values for a set duration. If
no new values arrive during that time the value is emitted, however if a
new value is received during the holding period the previous value is
discarded and the process is repeated with the new value.
This operator is useful if you have a stream of "bursty" events which
eventually settle down and you only need the final event of the burst. For
example, a search engine may only want to initiate a search after a user
has paused typing so as to not prematurely recommend results.
debounce("100 millis"),25 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`> Emitted ${(parameter) n: number
n}`))26)27
28import 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)29/*30Example Output:31Received 1 after 5ms32Received 2 after 2ms33Received 3 after 0ms34> Emitted 3 after 104ms35Received 4 after 99ms36Received 5 after 1ms37Received 6 after 0ms38> Emitted 6 after 101ms39Received 7 after 50ms40Received 8 after 1ms41> Emitted 8 after 101ms42{ _id: 'Chunk', values: [ 3, 6, 8 ] }43*/
Throttling is a technique employed to regulate the rate at which elements are emitted from a stream. It is useful for maintaining a steady pace of data output, which is especially valuable in scenarios where data processing needs to occur at a consistent rate.
The Stream.throttle
function controls the rate of this stream’s chunks by utilizing the token bucket algorithm.
Example of Throttle Configuration
1Stream.throttle({2 cost: () => 1,3 duration: "100 millis",4 units: 15})
In this configuration:
- Each chunk processed uses one token (
cost = () => 1
). - Tokens are replenished at a rate of one token (
units: 1
) every 100 milliseconds (duration: "100 millis"
).
The “shape” strategy moderates data flow by delaying chunk emissions until they comply with specified bandwidth constraints. This strategy ensures that data throughput does not exceed defined limits, allowing for steady and controlled data emission.
1import { import Stream
Stream, import Effect
Effect, import Schedule
Schedule, import Chunk
Chunk } from "effect"2
3let let last: number
last = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()4const const log: (message: string) => Effect.Effect<void, never, never>
log = ((parameter) message: string
message: string) =>5 import Effect
Effect.const sync: <void>(thunk: LazyArg<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents a synchronous side-effectful computation.
The provided function (`thunk`) should not throw errors; if it does, the error is treated as a defect.
Use `Effect.sync` when you are certain the operation will not fail.
sync(() => {6 const const end: number
end = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(`${(parameter) message: string
message} after ${const end: number
end - let last: number
last}ms`)8 let last: number
last = const end: number
end9 })10
11const 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(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("50 millis")).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<...>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>, de: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(12 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(6),13 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`Received ${(parameter) n: number
n}`)),14 import Stream
Stream.const throttle: <number>(options: {
readonly cost: (chunk: Chunk.Chunk<number>) => number;
readonly units: number;
readonly duration: DurationInput;
readonly burst?: number | undefined;
readonly strategy?: "enforce" | "shape" | undefined;
}) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+1 overload)
Delays the chunks of this stream according to the given bandwidth
parameters using the token bucket algorithm. Allows for burst in the
processing of elements by allowing the token bucket to accumulate tokens up
to a `units + burst` threshold. The weight of each chunk is determined by
the `cost` function.
If using the "enforce" strategy, chunks that do not meet the bandwidth
constraints are dropped. If using the "shape" strategy, chunks are delayed
until they can be emitted without exceeding the bandwidth constraints.
Defaults to the "shape" strategy.
throttle({15 (property) cost: (chunk: Chunk.Chunk<number>) => number
cost: import Chunk
Chunk.const size: <A>(self: Chunk.Chunk<A>) => number
Retireves the size of the chunk
size,16 (property) duration: DurationInput
duration: "100 millis",17 (property) units: number
units: 118 }),19 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`> Emitted ${(parameter) n: number
n}`))20)21
22import 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)23/*24Example Output:25Received 0 after 56ms26> Emitted 0 after 0ms27Received 1 after 52ms28> Emitted 1 after 48ms29Received 2 after 52ms30> Emitted 2 after 49ms31Received 3 after 52ms32> Emitted 3 after 48ms33Received 4 after 52ms34> Emitted 4 after 47ms35Received 5 after 52ms36> Emitted 5 after 49ms37{ _id: 'Chunk', values: [ 0, 1, 2, 3, 4, 5 ] }38*/
The “enforce” strategy strictly regulates data flow by discarding chunks that exceed bandwidth constraints.
1import { import Stream
Stream, import Effect
Effect, import Schedule
Schedule, import Chunk
Chunk } from "effect"2
3let let last: number
last = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()4const const log: (message: string) => Effect.Effect<void, never, never>
log = ((parameter) message: string
message: string) =>5 import Effect
Effect.const sync: <void>(thunk: LazyArg<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents a synchronous side-effectful computation.
The provided function (`thunk`) should not throw errors; if it does, the error is treated as a defect.
Use `Effect.sync` when you are certain the operation will not fail.
sync(() => {6 const const end: number
end = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(`${(parameter) message: string
message} after ${const end: number
end - let last: number
last}ms`)8 let last: number
last = const end: number
end9 })10
11const const stream: Stream.Stream<number, never, never>
stream = import Stream
Stream.const make: <[number, number, number, number, number, number]>(as_0: number, as_1: number, as_2: number, as_3: number, as_4: number, as_5: number) => Stream.Stream<number, never, never>
Creates a stream from an sequence of values.
make(1, 2, 3, 4, 5, 6).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<...>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>, de: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(12 import Stream
Stream.const schedule: <Duration, number, never, number>(schedule: Schedule.Schedule<Duration, number, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<...> (+1 overload)
Schedules the output of the stream using the provided `schedule`.
schedule(import Schedule
Schedule.const exponential: (base: DurationInput, factor?: number) => Schedule.Schedule<Duration>
A schedule that always recurs, but will wait a certain amount between
repetitions, given by `base * factor.pow(n)`, where `n` is the number of
repetitions so far. Returns the current duration between recurrences.
exponential("100 millis")),13 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`Received ${(parameter) n: number
n}`)),14 import Stream
Stream.const throttle: <number>(options: {
readonly cost: (chunk: Chunk.Chunk<number>) => number;
readonly units: number;
readonly duration: DurationInput;
readonly burst?: number | undefined;
readonly strategy?: "enforce" | "shape" | undefined;
}) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+1 overload)
Delays the chunks of this stream according to the given bandwidth
parameters using the token bucket algorithm. Allows for burst in the
processing of elements by allowing the token bucket to accumulate tokens up
to a `units + burst` threshold. The weight of each chunk is determined by
the `cost` function.
If using the "enforce" strategy, chunks that do not meet the bandwidth
constraints are dropped. If using the "shape" strategy, chunks are delayed
until they can be emitted without exceeding the bandwidth constraints.
Defaults to the "shape" strategy.
throttle({15 (property) cost: (chunk: Chunk.Chunk<number>) => number
cost: import Chunk
Chunk.const size: <A>(self: Chunk.Chunk<A>) => number
Retireves the size of the chunk
size,16 (property) duration: DurationInput
duration: "1 second",17 (property) units: number
units: 1,18 (property) strategy?: "enforce" | "shape" | undefined
strategy: "enforce"19 }),20 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`> Emitted ${(parameter) n: number
n}`))21)22
23import 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)24/*25Example Output:26Received 1 after 106ms27> Emitted 1 after 1ms28Received 2 after 200ms29Received 3 after 402ms30Received 4 after 801ms31> Emitted 4 after 1ms32Received 5 after 1601ms33> Emitted 5 after 1ms34Received 6 after 3201ms35> Emitted 6 after 0ms36{ _id: 'Chunk', values: [ 1, 4, 5, 6 ] }37*/
The Stream.throttle
function offers a burst option that allows for temporary increases in data throughput beyond the set rate limits.
This option is set to greater than 0 to activate burst capability (default is 0, indicating no burst support).
The burst capacity provides additional tokens in the token bucket, enabling the stream to momentarily exceed its configured rate when bursts of data occur.
1import { import Effect
Effect, import Schedule
Schedule, import Stream
Stream, import Chunk
Chunk } from "effect"2
3let let last: number
last = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()4const const log: (message: string) => Effect.Effect<void, never, never>
log = ((parameter) message: string
message: string) =>5 import Effect
Effect.const sync: <void>(thunk: LazyArg<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents a synchronous side-effectful computation.
The provided function (`thunk`) should not throw errors; if it does, the error is treated as a defect.
Use `Effect.sync` when you are certain the operation will not fail.
sync(() => {6 const const end: number
end = var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date.(method) DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now()7 namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(`${(parameter) message: string
message} after ${const end: number
end - let last: number
last}ms`)8 let last: number
last = const end: number
end9 })10
11const 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(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("10 millis")).(method) Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<number, never, never>, Stream.Stream<...>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<...>) => Stream.Stream<...>, bc: (_: Stream.Stream<...>) => Stream.Stream<...>, cd: (_: Stream.Stream<...>) => Stream.Stream<...>, de: (_: Stream.Stream<...>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe(12 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(20),13 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`Received ${(parameter) n: number
n}`)),14 import Stream
Stream.const throttle: <number>(options: {
readonly cost: (chunk: Chunk.Chunk<number>) => number;
readonly units: number;
readonly duration: DurationInput;
readonly burst?: number | undefined;
readonly strategy?: "enforce" | "shape" | undefined;
}) => <E, R>(self: Stream.Stream<...>) => Stream.Stream<...> (+1 overload)
Delays the chunks of this stream according to the given bandwidth
parameters using the token bucket algorithm. Allows for burst in the
processing of elements by allowing the token bucket to accumulate tokens up
to a `units + burst` threshold. The weight of each chunk is determined by
the `cost` function.
If using the "enforce" strategy, chunks that do not meet the bandwidth
constraints are dropped. If using the "shape" strategy, chunks are delayed
until they can be emitted without exceeding the bandwidth constraints.
Defaults to the "shape" strategy.
throttle({15 (property) cost: (chunk: Chunk.Chunk<number>) => number
cost: import Chunk
Chunk.const size: <A>(self: Chunk.Chunk<A>) => number
Retireves the size of the chunk
size,16 (property) duration: DurationInput
duration: "200 millis",17 (property) units: number
units: 5,18 (property) strategy?: "enforce" | "shape" | undefined
strategy: "enforce",19 (property) burst?: number | undefined
burst: 220 }),21 import Stream
Stream.const tap: <number, void, never, never>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Stream.Stream<number, E, R>) => Stream.Stream<number, E, R> (+1 overload)
Adds an effect to consumption of every element of the stream.
tap(((parameter) n: number
n) => const log: (message: string) => Effect.Effect<void, never, never>
log(`> Emitted ${(parameter) n: number
n}`))22)23
24import 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)25/*26Example Output:27Received 0 after 16ms28> Emitted 0 after 0ms29Received 1 after 12ms30> Emitted 1 after 0ms31Received 2 after 11ms32> Emitted 2 after 0ms33Received 3 after 11ms34> Emitted 3 after 0ms35Received 4 after 11ms36> Emitted 4 after 1ms37Received 5 after 11ms38> Emitted 5 after 0ms39Received 6 after 12ms40> Emitted 6 after 0ms41Received 7 after 11ms42Received 8 after 12ms43Received 9 after 11ms44Received 10 after 11ms45> Emitted 10 after 0ms46Received 11 after 11ms47Received 12 after 11ms48Received 13 after 12ms49> Emitted 13 after 0ms50Received 14 after 11ms51Received 15 after 12ms52Received 16 after 11ms53Received 17 after 11ms54> Emitted 17 after 0ms55Received 18 after 12ms56Received 19 after 10ms57{58 _id: 'Chunk',59 values: [60 0, 1, 2, 3, 4,61 5, 6, 10, 13, 1762 ]63}64*/
In this setup, the stream starts with a bucket containing 5 tokens, allowing the first five chunks to be emitted instantly. The additional burst capacity of 2 accommodates further emissions momentarily, allowing for handling of subsequent data more flexibly. Over time, as the bucket refills according to the throttle configuration, additional elements are emitted, demonstrating how the burst capability can manage uneven data flows effectively.