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.
Next Step
That’s it for the Hello, world! example.
- If using the groov View nodes, please continue on to using the groov View nodes.
- If using the PAC Control nodes, please continue on to using the PAC Control nodes.
There’s also a quick introduction to Node-RED on the official website, with tutorials for a first and second flow.