Answer the question
In order to leave comments, you need to log in
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
$ tail stream/temperature.txt|xxd
00000000: 2700 fd27 00f9 2701 a327 019d 2701 9b27 0105 2700 ef27 0171 2701 55
Answer the question
In order to leave comments, you need to log in
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
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
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 questionAsk a Question
731 491 924 answers to any question