消息钩子允许在节点之间的消息路径中添加自定义代码。
下图展示了消息路径中可用的钩子集合。

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>"
}
Node-RED: 面向事件驱动应用的低代码编程平台。
版权所有 OpenJS基金会 及 Node-RED 贡献者。保留所有权利。OpenJS基金会 拥有注册商标并使用商标。有关 OpenJS基金会 的商标列表,请参阅我们的 商标政策 和 商标列表。未在 OpenJS基金会商标列表 中标注的商标™或注册®商标归其各自持有人所有。使用这些商标并不意味着与它们有任何关联或获得其认可。
The OpenJS Foundation | 使用条款 | 隐私政策 | OpenJS基金会章程 | 商标政策 | 商标列表 | Cookie政策