消息钩子允许在节点之间的消息路径中添加自定义代码。
下图显示了消息路径中可用的钩子集。
send
发送一个或多个消息。onSend
节点已调用 node.send()
发送一个或多个消息。
钩子会接收一个 SendEvent
对象的数组。这些对象中的消息与节点传递给 node.send
的消息完全相同——这意味着可能存在对同一消息对象的重复引用。
此钩子应同步完成,以避免意外行为。
如果它需要异步工作,它必须克隆并替换它收到的事件中的消息对象。它还必须将 cloneMessage
属性设置为 false
,以确保消息不会发生后续克隆。
如果钩子返回 false
,消息将不会继续。
// Example synchronous onSend hook
RED.hooks.add("onSend", (sendEvents) => {
console.log(`Sending ${sendEvents.length} messages`);
});
preRoute
消息即将被路由到其目的地。
钩子会接收一个 SendEvent
对象。
此钩子应同步完成,以避免意外行为。
如果它需要异步工作,它必须克隆并替换它收到的事件中的消息对象。它还必须将 cloneMessage
属性设置为 false
,以确保消息不会发生后续克隆。
如果钩子返回 false
,消息将不会继续。
// Example async preRoute hook
RED.hooks.add("preRoute", (sendEvent, done) => {
// As this hook needs to do async work, clone the message if needed
if (sendEvent.cloneMessage) {
sendEvent.msg = RED.util.cloneMessage(sendEvent.msg);
sendEvent.cloneMessage = false;
}
someAsyncAPI(sendEvent).then(() => {
done()
}).catch(err => {
// An error means stop processing this message
done(err);
})
});
preDeliver
消息即将被传递
钩子会接收一个 SendEvent
对象。此时,本地路由器已识别出它将发送到的节点,并设置了 SendEvent
的 destination.node
属性。
消息将根据需要进行克隆。
如果钩子返回 false
,消息将不会继续。
// Example preDeliver hook
RED.hooks.add("preDeliver", (sendEvent) => {
console.log(`About to deliver to ${sendEvent.destination.id}`);
});
postDeliver
消息已分派到其目的地。
钩子会接收一个 SendEvent
对象。消息异步传递到钩子执行。
// Example preDeliver hook
RED.hooks.add("preDeliver", (sendEvent) => {
console.log(`Message dispatched to ${sendEvent.destination.id}`);
});
onReceive
消息即将被节点接收。
钩子会接收一个 ReceiveEvent
对象。
如果钩子返回 false
,消息将不会继续。
// Example onReceive hook
RED.hooks.add("onReceive", (receiveEvent) => {
console.log(`Message about to be passed to node: ${receiveEvent.destination.id}`);
});
postReceive
消息已被节点接收。
当消息已传递给节点的 input
处理程序时,钩子会接收一个 ReceiveEvent
对象。
// Example postReceive hook
RED.hooks.add("postReceive", (receiveEvent) => {
console.log(`Message received: ${receiveEvent.msg.payload}`);
});
onComplete
节点已完成处理消息或为其记录了错误。
钩子会接收一个 CompleteEvent
对象。
// Example onComplete hook
RED.hooks.add("onComplete", (completeEvent) => {
if (completeEvent.error) {
console.log(`Message completed with error: ${completeEvent.error}`);
}
});
SendEvent
对象{
"msg": "<message object>",
"source": {
"id": "<node-id>",
"node": "<node-object>",
"port": "<index of port being sent on>",
},
"destination": {
"id": "<node-id>",
"node": undefined,
},
"cloneMessage": "true|false"
}
ReceiveEvent
对象{
"msg": "<message object>",
"destination": {
"id": "<node-id>",
"node": "<node-object>",
}
}
CompleteEvent
对象{
"msg": "<message object>",
"node": {
"id": "<node-id>",
"node": "<node-object>"
},
"error": "<error passed to done, otherwise, undefined>"
}
版权所有 OpenJS Foundation 和 Node-RED 贡献者。保留所有权利。OpenJS Foundation 已注册商标并使用商标。有关 OpenJS Foundation 商标列表,请参阅我们的商标政策和商标列表。未在OpenJS Foundation 商标列表中指明的商标和徽标是其各自持有者的商标™ 或注册® 商标。使用它们不表示与它们有任何关联或获得它们的认可。
OpenJS Foundation | 使用条款 | 隐私政策 | OpenJS Foundation 章程 | 商标政策 | 商标列表 | Cookie 政策