Foreign
Foreign

Reputation: 405

What is the JavaScript equivalent of Java's ByteArrayOutputStream?

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"]

Upvotes: 3

Views: 4110

Answers (2)

HarryLit
HarryLit

Reputation: 26

Highest Score Bergi solution is absolutely nice, but I don't get it why he has the code output.push(Buffer.from([bytes.length+1]));, and if I add it, it will go wrong. It will work when I remove it.

Upvotes: 0

Bergi
Bergi

Reputation: 664579

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().

Upvotes: 3

Related Questions