The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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)
(the arguments are all passed to util.format()).
constcode=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() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
console.log(Cron.unsafeParse("0 4 8-14 * *"))
// Output:
// {
// _id: 'Cron',
// tz: { _id: 'Option', _tag: 'None' },
// seconds: [ 0 ],
// minutes: [ 0 ],
// hours: [ 4 ],
// days: [
// 8, 9, 10, 11,
// 12, 13, 14
// ],
// months: [],
// weekdays: []
// }
@since ― 2.0.0
unsafeParse("0 0 4 8-14 * *")
使用 match 检查日期
match 函数允许你确定给定的 Date(或任何 DateTime.Input)是否满足 cron 调度的约束。
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
console.log(Cron.unsafeParse("0 4 8-14 * *"))
// Output:
// {
// _id: 'Cron',
// tz: { _id: 'Option', _tag: 'None' },
// seconds: [ 0 ],
// minutes: [ 0 ],
// hours: [ 4 ],
// days: [
// 8, 9, 10, 11,
// 12, 13, 14
// ],
// months: [],
// weekdays: []
// }
@since ― 2.0.0
unsafeParse("0 0 4 8-14 * *")
6
7
const
constcheckDate:Date
checkDate=new
var Date:DateConstructor
new (value:number|string|Date) =>Date (+3 overloads)
Date("2025-01-08 04:00:00")
8
9
var console:Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
console.log(Cron.unsafeParse("0 4 8-14 * *"))
// Output:
// {
// _id: 'Cron',
// tz: { _id: 'Option', _tag: 'None' },
// seconds: [ 0 ],
// minutes: [ 0 ],
// hours: [ 4 ],
// days: [
// 8, 9, 10, 11,
// 12, 13, 14
// ],
// months: [],
// weekdays: []
// }
@since ― 2.0.0
unsafeParse("0 0 4 8-14 * *", "UTC")
6
7
// 指定搜索的起点
8
const
constafter:Date
after=new
var Date:DateConstructor
new (value:number|string|Date) =>Date (+3 overloads)
@throws ― IllegalArgumentException if the given DateTime.Input is invalid.
@throws ― Error if the next run date cannot be found within 10,000 iterations.
@since ― 2.0.0
next(
constcron:Cron.Cron
cron,
constafter:Date
after)
12
13
var console:Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
function (typeparameter) Ain <A>(action:Effect.Effect<A>, schedule:Schedule.Schedule<[number, number], void>):void
A>(
13
action: Effect.Effect<A, never, never>
action:
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
interfaceEffect<outA, outE=never, outR=never>
The Effect interface defines a value that describes a workflow or job,
which can succeed or fail.
Details
The Effect interface represents a computation that can model a workflow
involving various types of operations, such as synchronous, asynchronous,
concurrent, and parallel interactions. It operates within a context of type
R, and the result can either be a success with a value of type A or a
failure with an error of type E. The Effect is designed to handle complex
interactions with external resources, offering advanced features such as
fiber-based concurrency, scheduling, interruption handling, and scalability.
This makes it suitable for tasks that require fine-grained control over
concurrency and error management.
To execute an Effect value, you need a Runtime, which provides the
environment necessary to run and manage the computation.
@since ― 2.0.0
@since ― 2.0.0
Effect<
function (typeparameter) Ain <A>(action:Effect.Effect<A>, schedule:Schedule.Schedule<[number, number], void>):void
A Schedule<Out, In, R> defines a recurring schedule, which consumes values
of type In, and which returns values of type Out.
The Schedule type is structured as follows:
// ┌─── The type of output produced by the schedule
// │ ┌─── The type of input consumed by the schedule
// │ │ ┌─── Additional requirements for the schedule
// ▼ ▼ ▼
Schedule<Out, In, Requirements>
A schedule operates by consuming values of type In (such as errors in the
case of Effect.retry, or values in the case of Effect.repeat) and
producing values of type Out. It determines when to halt or continue the
execution based on input values and its internal state.
The inclusion of a Requirements parameter allows the schedule to leverage
additional services or resources as needed.
Schedules are defined as a possibly infinite set of intervals spread out over
time. Each interval defines a window in which recurrence is possible.
When schedules are used to repeat or retry effects, the starting boundary of
each interval produced by a schedule is used as the moment when the effect
will be executed again.
Schedules can be composed in different ways:
Union: Combines two schedules and recurs if either schedule wants to
continue, using the shorter delay.
Intersection: Combines two schedules and recurs only if both schedules want
to continue, using the longer delay.
Sequencing: Combines two schedules by running the first one fully, then
switching to the second.
In addition, schedule inputs and outputs can be transformed, filtered (to
terminate a schedule early in response to some input or output), and so
forth.
A variety of other operators exist for transforming and combining schedules,
and the companion object for Schedule contains all common types of
schedules, both for performing retrying, as well as performing repetition.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Repeats an effect based on a specified schedule or until the first failure.
Details
This function executes an effect repeatedly according to the given schedule.
Each repetition occurs after the initial execution of the effect, meaning
that the schedule determines the number of additional repetitions. For
example, using Schedule.once will result in the effect being executed twice
(once initially and once as part of the repetition).
If the effect succeeds, it is repeated according to the schedule. If it
fails, the repetition stops immediately, and the failure is returned.
The schedule can also specify delays between repetitions, making it useful
for tasks like retrying operations with backoff, periodic execution, or
performing a series of dependent actions.
You can combine schedules for more advanced repetition logic, such as adding
delays, limiting recursions, or dynamically adjusting based on the outcome of
each execution.
constintersect: <number, unknown, never>(that:Schedule.Schedule<number, unknown, never>) => <Out, In, R>(self:Schedule.Schedule<Out, In, R>) =>Schedule.Schedule<[Out, number], In, R> (+1overload)
Combines two schedules, continuing only if both schedules want to continue,
using the longer delay.
Details
This function takes two schedules and creates a new schedule that only
continues execution if both schedules allow it. The interval between
recurrences is determined by the longer delay between the two schedules.
The output of the resulting schedule is a tuple containing the outputs of
both schedules. The input type is the intersection of both schedules' input
types.
This is useful when coordinating multiple scheduling conditions where
execution should proceed only when both schedules permit it.
@see ― intersectWith If you need to use a custom merge function.
A schedule that recurs a fixed number of times before terminating.
Details
This schedule will continue executing until it has been stepped n times,
after which it will stop. The output of the schedule is the current count of
recurrences.
Returns a new schedule that runs the given effectful function for each output
before continuing execution.
Details
This function allows side effects to be performed on each output produced by
the schedule. It does not modify the schedule’s behavior but ensures that the
provided function f runs after each step.
new (value:number|string|Date) =>Date (+3 overloads)
Date(
typeOut: [number, number]
Out[0]), new
var Date:DateConstructor
new (value:number|string|Date) =>Date (+3 overloads)
Date(
typeOut: [number, number]
Out[1])]
31
)
32
)
33
)
34
),
35
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
constfork: <A, E, R>(self:Effect.Effect<A, E, R>) =>Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>
Creates a new fiber to run an effect concurrently.
Details
This function takes an effect and forks it into a separate fiber, allowing it
to run concurrently without blocking the original effect. The new fiber
starts execution immediately after being created, and the fiber object is
returned immediately without waiting for the effect to begin. This is useful
when you want to run tasks concurrently while continuing other tasks in the
parent fiber.
The forked fiber is attached to the parent fiber's scope. This means that
when the parent fiber terminates, the child fiber will also be terminated
automatically. This feature, known as "auto supervision," ensures that no
fibers are left running unintentionally. If you prefer not to have this auto
supervision behavior, you can use
forkDaemon
or
forkIn
.
When to Use
Use this function when you need to run an effect concurrently without
blocking the current execution flow. For example, you might use it to launch
background tasks or concurrent computations. However, working with fibers can
be complex, so before using this function directly, you might want to explore
higher-level functions like
raceWith
,
zip
, or others that can
manage concurrency for you.
Example
import { Effect } from"effect"
constfib= (n:number):Effect.Effect<number> =>
n <2
? Effect.succeed(n)
: Effect.zipWith(fib(n -1), fib(n -2), (a, b) => a + b)
Accesses a TestClock instance in the context and increments the time
by the specified duration, running any actions scheduled for on or before
the new time in order.
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.
constprovide: <TestServices, never, never>(layer:Layer<TestServices, never, never>) => <A, E, R>(self:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, Exclude<R, TestServices>> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
construnPromise: <A, E>(effect:Effect.Effect<A, E, never>, options?: {
readonlysignal?:AbortSignal|undefined;
} |undefined) =>Promise<A>
Executes an effect and returns the result as a Promise.
Details
This function runs an effect and converts its result into a Promise. If the
effect succeeds, the Promise will resolve with the successful result. If
the effect fails, the Promise will reject with an error, which includes the
failure details of the effect.
The optional options parameter allows you to pass an AbortSignal for
cancellation, enabling more fine-grained control over asynchronous tasks.
When to Use
Use this function when you need to execute an effect and work with its result
in a promise-based system, such as when integrating with third-party
libraries that expect Promise results.
Example (Running a Successful Effect as a Promise)
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
Creates a schedule that recurs based on a cron expression.
Details
This schedule automatically executes at intervals defined by a cron
expression. It triggers at the beginning of each matched interval and
produces timestamps representing the start and end of the cron window.
The cron expression is validated lazily, meaning errors may only be
detected when the schedule is executed.
@since ― 2.0.0
cron(
constcron:Cron.Cron
cron)
48
49
// 定义一个要重复的虚拟操作
50
const
constaction:Effect.Effect<void, never, never>
action=
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
constvoid:Effect.Effect<void, never, never>
export void
Represents an effect that does nothing and produces no value.
When to Use
Use this effect when you need to represent an effect that does nothing.
This is useful in scenarios where you need to satisfy an effect-based
interface or control program flow without performing any operations. For
example, it can be used in situations where you want to return an effect
from a function but do not need to compute or return any result.