Node-RED Hello, world! Example, part 2
源自於 http://developer.opto22.com/nodered/general/getting-started/node-red-hello-world-2/
Overview
The Hello, world! example is great, but we can make it more useful and interesting. We’ll add the current time to the message, and execute it every two seconds.
Step 1 - Add a Function node
First off, let’s add the current time to the message. To do that, we’ll use the Function block, which allows you to enter JavaScript code to manipulate the msg
object.
- Select a Function node and drag it out onto the flow.
- Carefully place it over the existing wire between the existing Inject and Debug nodes. Node-RED will insert the new node between the two existing nodes, and rewire the nodes together.
Step 2 - Add Code and Run
- Double-click on the Function node to open the “Edit function node” view.
Copy and paste the following JavaScript code into the Function field:
var dateNow = new Date(); var timeAsString = dateNow.toLocaleTimeString(); msg.payload = msg.payload + ' The time is ' + timeAsString + '.'; return msg;
- In the Name field, enter “Add time to msg”.
- Click Done.
- Click Deploy.
- Click the Inject node’s button.
- In the Debug tab, you should see the new output. For example, “Hello, world! The time is 4:25:29 PM”.
Step 3 - Add Two-Second Interval
Now let’s adjust the flow to automatically inject a new message every two seconds. The existing Inject node can already do that, we just need to adjust its settings.
- Double-click on the existing Inject node to open the “Edit inject node” view.
- For the Repeat field, select interval and enter 2 seconds for the period.
- Click Done.
- Click Deploy.
- In the Debug tab, you should now see your output every two seconds.
沒有留言:
張貼留言