问题在于您的原始数据是 Base64 编码的 UTF16-BE。如果您在第一行之后查看a,您会发现它具有您在最终缓冲区中看到的那些零字节:
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").toString("utf-8");
console.log(a.length);
// 12
console.log([...a].map(ch => ch.charCodeAt(0).toString(16).padStart(2, "0")).join(" "));
// 00 41 00 42 00 43 00 61 00 62 00 63
所以问题变成了:如何从Buffer.from("AEEAQgBDAGEAYgBj", "base64") 读取缓冲区中的UTF16-BE 文本。 Node.js 的 Buffer 不直接支持 UTF16-BE(其标准库中没有 "utf16be" 编码),但您可以通过 swap16 到达那里,然后将缓冲区读取为 UTF16-LE ("utf16le" , 在 Node.js 的标准库中):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc
现在a 是一个普通的字符串。如果你想要一个包含 UTF8 内容的缓冲区,你可以使用Buffer.from(a).toString("utf8"):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc
let b = Buffer.from(a); // (Default is `"utf8"` but you could supply that explicitly)
console.log(b);
// <Buffer 41 42 43 61 62 63>