@hlang-org运行时
hlang运行时:基于流的RxJS流编程。从通过指定端口连接的可读、转换和可写节点构建程序。
安装
npm install @hlang-org/runtime
相同的构建发布为 @hlang-tech/runtime。包是带有类型声明的CommonJS。ES模块可以导入其命名的导出。
例子
const { Flow, ReadableNode, TransformNode, WriteableNode, Port } = require('@hlang-org/runtime');
class Numbers extends ReadableNode {
constructor(opts) {
super(opts);
Port.O('out').attach(this);
}
_read($o) {
[1, 2, 3].forEach((n) => $o('out').send(n));
}
}
class Double extends TransformNode {
constructor(opts) {
super(opts);
Port.I('in').attach(this);
Port.O('out').attach(this);
}
_transform($i, $o) {
$i('in').receive((n) => $o('out').send(n * 2));
}
}
class Log extends WriteableNode {
constructor(opts) {
super(opts);
Port.I('in').attach(this);
}
_write($i) {
$i('in').receive((n) => console.log(n));
}
}
const numbers = new Numbers();
const double = new Double();
const log = new Log();
numbers.O('out').connect(double.I('in'));
double.O('out').connect(log.I('in'));
new Flow().run(numbers); // 2, 4, 6
节点
| 类 | 种类 | 港口 | 实现 |
|---|---|---|---|
ReadableNode | R是源 | 输出,加上 @node/error | _read($o) |
TransformNode | T | 输入和输出,加上 @node/error | _transform($i, $o) |
WriteableNode | W,水槽 | 只有输入,没有错误端口 | _write($i) |
在构造函数中创建端口 Port.I(name).attach(this) 和 Port.O(name).attach(this)。一个节点可以有任意数量的命名端口。构造函数参数存储为 this.opts。解释器和编译器通过 { nodeId, flowId, env, middleware, config, signal },节点参数为 this.opts.config.params.
运行时调用 _read, _transform,或者 _write 每个流一次。 $i(name) 和 $o(name) 返回节点的输入和输出端口。在节点内部, this.I(name), this.O(name), this.E() (错误端口)返回相同的端口。
可读和转换节点 throw(error),它发送 error 在 @node/error.
港口
一个端口封装了一个RxJS Subject.
| 方法 | 效果 |
|---|---|
send(message) | 发出 message (next)。 |
receive(listener) | 订阅 listener。返回RxJS Subscription. |
pipe(...operators) | 对端口发出的内容应用RxJS操作符。返回 { receive }. |
connect(input) | 将此输出端口连接到输入端口。抛出,除非方向是输出到输入。 |
端口是多播的:一个输出可以提供多个输入,一个输入可以从多个输出接收。
流
new Flow().run(readable) 收集可读根通过其连接可访问的节点。它首先启动可写节点,然后是转换节点,然后是可读根,因此在发送数据之前每个订阅者都存在。运行一个图的每个可读根。 run 如果其参数不是可读节点则抛出。
变换节点可以形成循环,因此图可以包含反馈循环。绑定一个反馈循环,例如用 take 或者计数器,这样就结束了。
相关的包
@hlang-org/interpreter运行一个JSON图(IGraph)与这些节点。@hlang-org/compiler编译一个JSON图形到一个ES模块。
来源、问题和文档: github.com/hlang-tech/hlang.
许可证
麻省理工学院