如何在Node JS中进行UTF-8编码

j2qf4p5b  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(217)

我正在尝试对node js中的字符串进行UTf8编码
我试过Buffer(someString,'utf8')和utf8包,但它总是返回原始字符串。var utf8 = require('utf8');

function decrypt(enc) {
  console.log('type', typeof enc);
  enc = utf8.encode(enc);
  console.log('encoding', enc);
  return enc;
}

console.log('decrypted:', decrypt('message'));

我在这个https://mothereff.in/utf-8中使用了'message'字符串,但预期的结果并没有出现。我们如何进行编码?

yeotifhr

yeotifhr1#

尝试使用Buffer.from方法这样做,然后使用buffer.tostring('utf8')方法将编码的字符串转换回字符串:

function codUtf8(str) {
        const buffer = Buffer.from(str, 'utf8');
        const strCod = buffer.toString('utf8');
        return strCod;
       }

console.log(codUtf8('message')

);

相关问题