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 mand-argument pairs delimited by \xb8. Is there anyway I can take a variable with binary data and break into multiple Command instances?
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 mand-argument pairs delimited by \xb8. Is there anyway I can take a variable with binary data and break into multiple Command instances?
Share Improve this question edited Jan 19, 2012 at 5:25 Mot 29.6k24 gold badges86 silver badges122 bronze badges asked Jan 19, 2012 at 2:23 LordZardeckLordZardeck 8,28319 gold badges65 silver badges119 bronze badges 3- Are you having trouble with simply iterating over the buffer looking for \xb8? – loganfsmyth Commented Jan 19, 2012 at 3:24
- I don't know how to do anything binary with NodeJS. – LordZardeck Commented Jan 19, 2012 at 3:54
- True enough. Just remember, hex isn't magic. You can just as easily loop over everything and pare it with 216 instead of 0xD8 since they are the same. – loganfsmyth Commented Jan 19, 2012 at 15:04
2 Answers
Reset to default 6Read 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