简体   繁体   English

如何从缓冲区数组接收字符串为 UTF-8(java 到 javascript)?

[英]How can i receive a string from buffer array as UTF-8 (java to javascript)?

i am trying to convert a small piece of code into javascript, everything is going well except for this part我正在尝试将一小段代码转换为 javascript,除了这部分之外,一切都很顺利

new String(encode, Charsets.UTF_8);

I suppose this is creating a string from encoded hash, what i have in javascript is我想这是从编码的 hash 创建一个字符串,我在 javascript 中拥有的是

const encoderUTF8 = new TextEncoder('utf-8');
const utf8 = new Uint8Array(encode.length);

const encoded = encoderUTF8.encodeInto(encode, utf8);

When i run it i get an error that says The "src" argument must be of type string. Received an instance of Buffer当我运行它时,我得到一个错误,说The "src" argument must be of type string. Received an instance of Buffer The "src" argument must be of type string. Received an instance of Buffer . The "src" argument must be of type string. Received an instance of Buffer The encode variable is a strange hash looking like this dD${��d�N��t�\���P� which is generated like so encode变量是一个奇怪的 hash 看起来像这样dD${��d�N��t�\���P�

const encode = Buffer.from(hash, 'base64');

Can someone please help me get this part together?有人可以帮我把这部分放在一起吗? All I need is to figure out that new String part.我所需要的只是找出new String部分。

I wrote one of the functions wrong, i should have base64 encoded instead of decoding it我写错了其中一个函数,我应该对 base64 进行编码而不是解码

const encode = Buffer.from(hash, 'base64');

to this对此

const encode = Buffer.from(hash).toString('base64').toString('utf-8');

Now its perfect and matches the string length and works perfectly.现在它完美并匹配字符串长度并且完美运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM