注:本文的案例参考了官方文档,但创建过程略有不同,经过测试验证可行
以创建一个名为lower-case的node为例子:
将msg.payload转换成小写字母
在C:\Users\my_name\.node_red\node_modules
下新建文件夹,命名为新node的名称,如 lower-case (my_name替换为电脑的用户名)
命令行中进入C:\Users\my_name\.node_red\node_modules\lower-case
下,输入 npm init
,然后一路enter产生package.json文件
打开package.json,添加内容
"node-red" : {
"nodes": {
"lower-case": "lower-case.js"
}
}
注:If the node has any external module dependencies, they must be included in the dependencies section of its package.json file.
C:\Users\my_name\.node_red\node_modules\lower-case
中创建文件lower-case.js
,添加内容module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
node.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
});
}
RED.nodes.registerType("lower-case",LowerCaseNode);
}
lower-case.js解析说明:
The node is wrapped as a Node.js module.
The module exports a function that gets called when the runtime loads the node on start-up.
The function is called with a single argument, RED, that provides the module access to the Node-RED runtime api.
The node itself is defined by a function, LowerCaseNode that gets called whenever a new instance of the node is created. It is passed an object containing the node-specific properties set in the flow editor.
The function calls the RED.nodes.createNode function to initialize the features shared by all nodes. After that, the node-specific code lives.
In this instance, the node registers a listener to the input event which gets called whenever a message arrives at the node.
Within this listener, it changes the payload to lower case, then calls the send function to pass the message on in the flow.
Finally, the LowerCaseNode function is registered with the runtime using the name for the node, lower-case.
C:\Users\my_name\.node_red\node_modules\lower-case
中创建文件lower-case.html
,添加内容<script type="text/javascript">
RED.nodes.registerType('lower-case',{
category: 'function',
color: '#a6bbcf',
defaults: {
name: {value:""}
},
inputs:1,
outputs:1,
icon: "file.png",
label: function() {
return this.name||"lower-case";
}
});
</script>
<script type="text/html" data-template-name="lower-case">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name">
</div>
</script>
<script type="text/html" data-help-name="lower-case">
<p>A simple node that converts the message payloads into all lower-case characters</p>
</script>
A node’s HTML file provides the following things:
这时新node已经添加成功了,可以进入node-red测试
可以看到输入STRINGstring
,经过lower-case结点后进入debug结点输出信息,如右侧栏所示为stringstring
在.node_red\node_modules
下创建一个文件夹 = 一个新的结点库
需要在文件夹内创建package.json来配置,添加各项结点
一个xxx.js = 一个xxx结点的内在逻辑
一个xxx.html = 一个xxx结点的外观属性
本文章使用limfx的vscode插件快速发布