M
M
Maxim Ivanov2016-12-15 19:31:37
Node.js
Maxim Ivanov, 2016-12-15 19:31:37

How to properly handle buffer in NodeJS?

I have a file that writes data from a usb device (thermometer)
It sends hex data
In fact, I need to read the last 2 bytes in the file (and convert this number to decimal)
But I can’t do this
1. if I try read the file, we see that all this is in its encoding

$  cat stream/temperature.txt
''''''''q'U

As I understand it, the new value is separated by a quote
2. But if the meaning is to read the file (the device sends data in hex format and saves it to my file)
$ tail stream/temperature.txt|xxd 
00000000: 2700 fd27 00f9 2701 a327 019d 2701 9b27 0105 2700 ef27 0171 2701 55

In our case, the correct values ​​are (from the end):
01 55, 0171, 00 ef, 0105, 01 9b, 019d, ..
0x155 = 341 (that is, 34.1 is the temperature)
0x0171 = 369 (36.9)
0x00ef = 239 (23.9 )
0x019b = 41

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aves, 2016-12-16
@splincodewd

To get 341, you need to read the last two bytes like this:

> b
<Buffer 01 71 27 01 55>
> b.readUInt16BE(b.length - 2)
341

M
Maxim Ivanov, 2016-12-15
@splincodewd

The toaster has a bug, it doesn't want to display the code I'm trying to describe in the post!
While I'm attaching the screenshot
db7e7fe2d09e4b7898d4b32d068b05b7.png

B
baskovsky.ru, 2021-11-25
@qertis

Try converting BUFFER to STREAM.

import Stream from 'stream'

function getBufferFromStream(buffer) {
  if (Buffer.isBuffer(bufer)) {
    const stream = new Stream.PassThrough()
    stream.end(bufer)
    return stream
  }
  throw new Error('Argument is not a buffer')
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question