[英]What is the JavaScript equivalent of Java's ByteArrayOutputStream?
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 代碼讀取通過 .network 發送的 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"]
與ByteArrayOutputStream
最接近的等效項可能是由不斷增長的數組支持的Writable
流 。 我想您將不得不自己實現此功能 ,請參見例如在將流轉換為緩沖區中? 。
直接將緩沖區添加到數組中,然后將它們全部合並起來 ,以實現不斷增長的緩沖區可能更簡單。
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);
順便說一句,我很確定您要為長度前綴的字符串使用bytes.length
,而不是str.length
? 與您的Java代碼相同,您需要使用str.getBytes().length
而不是str.length()
。
最高分 Bergi 解決方案絕對不錯,但我不明白為什么他有代碼output.push(Buffer.from([bytes.length+1]));
, 如果我添加它,它會 go 錯誤。 當我刪除它時它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.