What is the JavaScript equivalent of Java's ByteArrayOutputStream?

Issue

What is the alternative to the following Java code for JavaScript?

String[] strings = {"something written here", "five", "hello world", "this is a really big string", "two words"};

ByteArrayOutputStream bos = new ByteArrayOutputStream();

for (String str : strings)
{
    bos.write(str.length());
    bos.write(str.getBytes());
}

ByteBuffer buffer = ByteBuffer.wrap(bos.toByteArray());
// send buffer somewhere...

I know that I can read Java’s ByteBuffer sent over the network with the following JS code, but couldn’t figure out a way of writing a reply using JS.

let strings = [];
let bytes = Buffer.from(data);

while (bytes.length > 0) {
    let size = bytes.readInt8(0) + 1;
    strings.push(bytes.toString("UTF-8", 1, size));
    bytes = bytes.slice(size);
}

Let’s suppose I want to reply: ["hello", "how", "are you", "doing"]

Solution

The closest equivalent to a ByteArrayOutputStream would probably be a Writable stream that is backed by a growing array. I guess you’ll have to implement this yourself though, see e.g. in Convert stream into buffer?.

It’s probably simpler to directly append buffers to an array as they come in, then concat them all, to implement your growing buffer.

const strings = ["something written here", "five", "hello world", "this is a really big string", "two words"];

const output = [];

for (const str of strings) {
    const bytes = Buffer.from(str, "utf-8");
    output.push(Buffer.from([bytes.length+1]));
    output.push(bytes);
}

const buffer = Buffer.concat(output);

Btw I’m pretty sure you want to use bytes.length, not str.length, for your length-prefixed strings? Same in your Java code, you need to use str.getBytes().length not str.length().

Answered By – Bergi

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.