Node.js 中的 TextDecoder 类:解码字节数组为字符串
对不起,我刚刚给出的回答是错误的。在 Node.js 中,确实存在 TextDecoder 类。TextDecoder 是一个内置的类,用于将字节数组解码为字符串。您可以使用它来解码不同的字符编码,如 UTF-8、UTF-16 等。以下是一个示例代码,展示了如何在 Node.js 中使用 TextDecoder 类:
const { TextDecoder } = require('util');
const decoder = new TextDecoder('utf-8');
const bytes = new Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]);
const text = decoder.decode(bytes);
console.log(text); // 输出: "Hello world"
请注意,TextDecoder 类是在 Node.js 版本 12.0.0 中引入的,因此如果您的 Node.js 版本较旧,您可能需要升级到更高版本才能使用它。
原文地址: https://www.cveoy.top/t/topic/pSuT 著作权归作者所有。请勿转载和采集!