Reputation: 100010
Say we have a buffer b:
const b = Buffer.from('foo\nbar\nbaz');
Is there a way to split the buffer into N buffers by newline character? Without converting to a string first? So the result would be something like this:
const b1 = Buffer.from('foo');
const b2 = Buffer.from('bar');
const b3 = Buffer.from('baz');
Upvotes: 1
Views: 3630
Reputation: 25840
The example below is using library iter-ops, to process buffer as an iterable:
import {pipe, split, map} from 'iter-ops';
const i = pipe(
b, // your buffer object
split(a => a === 10), // = 0x0A code for \n
map(m => Buffer.from(m)) // remap into buffer
);
const [b1, b2, b3] = [...i]; // your 3 resulting buffers
And this will be all done in just one iteration.
Upvotes: 0
Reputation: 5289
You could use buf.indexOf to find the newline characters in the buffer and then, depending on what you are doing, you can use buf.copy to copy into new Buffer objects.
Upvotes: 4