Nodejs非对称缓冲区<->字符串转换

Nodejs asymmetrical buffer <-> string conversion

在 nodejs 中,我天真地期望以下内容总是输出 true:

let buff = Buffer.allocUnsafe(20); // Essentially random contents
let str = buff.toString('utf8');
let decode = Buffer.from(str, 'utf8');
console.log(0 === buff.compare(decode));

给定一个缓冲区 buff,我如何提前检测 buff 是否正好等于 Buffer.from(buff.toString('utf8'), 'utf8')

您只需测试输入缓冲区是否包含有效的 UTF-8 数据就应该没问题:

try {
    new TextDecoder('utf-8', { fatal: true }).decode(buff);
    console.log(true);
} catch {
    console.log(false);
}

但我不会发誓 Node 在从字符串转换为缓冲区时在处理无效 UTF-8 数据方面 100% 一致。如果您想安全起见,则必须坚持使用缓冲区比较。您可以使用 transcode 使 encoding/decoding 的过程更高效一些,这不需要创建临时字符串。

import { transcode } from 'buffer';

let buff = Buffer.allocUnsafe(20);
let decode = transcode(buff, 'utf8', 'utf8');
console.log(0 === buff.compare(decode));

如果您对如何 TextDecoder 确定缓冲区是否表示有效的 utf8 字符串感兴趣,可以在 here.

中找到此过程的严格定义