Reading and Writing Data Using Buffers -Nodejs & Node-Red

What is a Buffer?  -A buffer is an array of binary data. Each element in the array is 8 bit binary data.

When are buffers used?  -Buffers are used when you need low level access to data usually that has been received on the network or from the file system.

Data stored on computers and transferred between computers on networks is stored or sent as a sequence of bytes.

When you read data from a file or from the network it is read into a data buffer.

Node.js Buffer Module

To work with buffers in node-red we use the node buffer module.

You will find a list of command here.

I am going to first illustrate it using the node command line and then show how you use it in node-red function nodes.

If we take a simple file created in Notepad that contains the text hello. If we read it as a binary buffer we get.

nyte-buffer

Exploring Buffer Data

If we look at a sequence of bytes , for example, if we take 5 bytes represented as decimal as shown below:

nyte-buffer

Then what do they mean? How do we interpret them? WE could interpret them :

As Characters

If the data is text data then they need to be converted into text.

To convert them into text we need need to know the text encoding scheme that was used to encode them.

Most modern systems use utf-8. utf-8 uses 1- 4 bytes to encode a character but English characters only require a single byte.

If we decode the above binary data then we get the string.

hello

Reading Data Using the Buffer Option

Floating numbers, Integers

They could represent a floating number or integer.

Most computers use 2 bits for an integer

Data coming from a file or from the network is stored in a data buffer. It can be passed to you program as a string as in the options seen above but it will need to be decoded.

 

var b=Buffer.from(“test”)

n=Buffer.from([23,45]) //decimal

n=Buffer.from([0x23,0x45]) //hex

Buffer.toString(b)

 

https://github.com/nodejitsu/docs/blob/master/pages/articles/advanced/buffers/how-to-use-buffers/content.md

https://medium.freecodecamp.org/do-you-want-a-better-understanding-of-buffer-in-node-js-check-this-out-2e29de2968e8

https://nodejs.org/api/buffer.html

https://www.w3schools.com/nodejs/ref_buffer.asp

https://stackoverflow.com/questions/52106570/javascript-convert-bytes-into-float-in-a-clean-wayhttps://stackoverflow.com/questions/44059719/converting-byte-array-into-floathttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataViewhttps://stackoverflow.com/questions/40970739/how-to-convert-two-16bit-integer-high-word-low-word-into-32bit-float/40970862#40970862https://discourse.nodered.org/t/modbus-tcp-read-32-bit-registers/1710/2https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

 

Node-red is a node application as so its uses the same c

Please rate? And use Comments to let me know more

Leave a Reply

Your email address will not be published. Required fields are marked *