javascript woes with substr() on msg.payload

4,162 views
Skip to first unread message

Phil Grant

unread,
Jan 10, 2016, 11:33:31 AM1/10/16
to Node-RED
Hi,
I'm struggling to get a function working and not sure why, I'm sure it'll be an easy answer but I just don't understand enough yet to get it.

I'm trying to get a section of the data sent into a function using substr() but I get an error in the debug window.

code in the function
var mac =  msg.payload.substr(14, 12);
msg
= mac;
return msg;

The payload is a UDP message set as a Buffer in the node, is this why it's failing? maybe it's not a string?? do I need to covert it?

As usual any help will be greatly appreciated, thanks
Phil

Dave C-J

unread,
Jan 10, 2016, 11:47:42 AM1/10/16
to node...@googlegroups.com
Yup - if it's a Buffer... then it's a Buffer :-)
there is an option in the udp node to output a string...
(or you can  msg.payload.toString()   it in a function if you want to... )
Message has been deleted

Phil Grant

unread,
Jan 10, 2016, 12:06:16 PM1/10/16
to Node-RED
Thanks Dave,
So this in a function should work ?
var msg =  msg.payload.toString();
return msg;

All I get is undefined in the debug.

Dave C-J

unread,
Jan 10, 2016, 12:08:08 PM1/10/16
to node...@googlegroups.com
oops no...
as Mark points out you are re-assigning msg not msg.payload... so by default debug won't show it..

try
var mac =  msg.payload.toString().substr(14, 12);
msg.payload 
= mac;
return msg;

Phil Grant

unread,
Jan 10, 2016, 12:29:14 PM1/10/16
to Node-RED
Thanks for the help, with your clues I got to this, which works a treat.
var mac =  msg.payload.toString('hex').substr(12, 12);

msg
.payload = mac;
return msg;

I just didn't understand what a buffer was and how to convert between base64 and hex.

Thanks alot.

Dave C-J

unread,
Jan 10, 2016, 12:43:05 PM1/10/16
to node...@googlegroups.com
Phew - all good.
Reply all
Reply to author
Forward
0 new messages