Java的ByteArrayOutputStream的JavaScript等效于什么?

时间:2019-09-06 21:20:36

标签: javascript node.js

以下用于JavaScript的Java代码的替代方法是什么?

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

我知道我可以使用以下JS代码读取通过网络发送的Java的ByteBuffer,但是无法找到使用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);
}

让我想回复:["hello", "how", "are you", "doing"]

1 个答案:

答案 0 :(得分:1)

ByteArrayOutputStream最接近的等效项可能是Writable stream,它由不断增长的数组支持。我猜您将不得不implement this yourself,例如在Convert stream into buffer?中。

直接将缓冲区添加到数组中可能会更简单,然后concat them all来实现不断增长的缓冲区。

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);

顺便说一句,我很确定您要对您的length-prefixed strings使用bytes.length而不是str.length吗?与您的Java代码相同,您需要使用str.getBytes().length而不是str.length()