How can I split a buffer of binary data in Node.js by a binary delimiter? For example, a socket data is sent with binary code with each field dilimited by \\xb8. How can I split that into an array?
Better yet, is there some way to write a class or something that it can be loaded into? For example, each packet sends command-argument pairs delimited by \\xb8. Is there anyway I can take a variable with binary data and break into multiple Command instances?
Read the Buffers documentation .
Iterate through each character in the buffer and create a new buffer whenever you encounter the specified character.
function splitBuffer(buf, delimiter) {
var arr = [], p = 0;
for (var i = 0, l = buf.length; i < l; i++) {
if (buf[i] !== delimiter) continue;
if (i === 0) {
p = 1;
continue; // skip if it's at the start of buffer
}
arr.push(buf.slice(p, i));
p = i + 1;
}
// add final part
if (p < l) {
arr.push(buf.slice(p, l));
}
return arr;
}
binary code with each field dilimited by \\xb8. How can I split that into an array?
Using iter-ops library, we can process a buffer as an iterable object:
import {pipe, split} from 'iter-ops';
const i = pipe(buffer, split(v => v === 0xb8));
console.log([...i]); // your arrays of data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.