gpt4 book ai didi

node.js - 从 noflo 开始,从 nodejs 运行它

转载 作者:搜寻专家 更新时间:2023-10-31 23:38:40 37 4
gpt4 key购买 nike

我从 noflo 得到了一个简单的 noflo 示例。但是我没有弄清楚 noflo 应该如何与 Node 和其他代码一起工作。

起初我有这个 fbp 文件:

# In the graph we first need to define the nodes and the connections between them
Read(filesystem/ReadFile) OUT -> IN Display(core/Output)

# Start off the graph by sending a filename to the file reader
#'package.json' -> IN Read

我试过:noflo.loadFile(filepath, nodedir, function(graph)

这有效并打印到控制台。但是,如果我省略 fbp 中的最后一行,即提供 package.json 参数,我发现无法运行该图。

是否有关于如何从 nodejs 代码而不是命令行使用 noflo 的指南?

最佳答案

通常,NoFlo 组件在接收到一些输入之前不会执行任何操作,在本例中是要读取的文件路径。来自 NoFlo component docs :

A running instance of a component in a NoFlo network is called a process. Before a process has received data it should be inert, merely listening to its input ports. Processes that need to start doing something when a network is started should be triggered to do so by sending them an Initial Information Packet.

最后一行 .fbp graph definition正在将字符串 package.json 发送到 ReadFile 组件。

您还可以在将文件加载到 NoFlo 网络后以编程方式执行此操作:

noflo.loadFile(filepath, process.cwd(), function (network) {
// Now we have access to the NoFlo network instance

// Add Initial Information Packet programatically
network.graph.addInitial(someFileToRead, 'Read', 'in');

// Tell NoFlo to send the new IIPs
network.sendInitials();
});

导出的端口和子图

现在,还有一种更优雅的方法可以做到这一点,即在 NoFlo 的 ComponentLoader 中将您的 .fbp 文件公开为图形,然后像与任何其他组件交互一样与它交互。

要使您感兴趣的端口可从外部使用,您需要导出它们。在这种情况下,至少是图中的 ReadFile IN 端口。这会将您的网络定义更改为:

# Export the filename port so it can be accessed from outside
INPORT=Read.IN:FILENAME

# The rest of the graph definition follows
Read(filesystem/ReadFile) OUT -> IN Display(core/Output)

(碰巧,这正是我在 .fbp language definition 中的导出端口上使用的示例)

为了让你的图表作为一个组件可用,你需要将它保存到你的 Node.js 项目中(约定是 graphs/ 子目录)并在 package.json< 中注册它 文件:

{
"noflo": {
"graphs": {
"MyGraph": "graphs/MyGraph.fbp"
}
}
}

现在您可以将其视为任何其他组件。例如:

var loader = new noflo.ComponentLoader(__dirname);
loader.load('MyGraph', function (instance) {
// The instance is a running NoFlo subgraph with your graph definition

// Create a socket and attach it to the exported port
var filename = noflo.internalSocket.createSocket();
instance.inPorts.filename.attach(filename);

filename.send(someFileToRead);
filename.disconnect();
});

这是首选方法的一个原因是您不仅可以使用它来发送 IIP,还可以将套接字附加到导出的输出端口并在其上监听事件。通过这种方式,您可以轻松地将任何 NoFlo 图用作 JavaScript 应用程序中的异步函数。

关于node.js - 从 noflo 开始,从 nodejs 运行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24135623/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com