buffer.transcode(source, fromEnc, toEnc)
-
source<Buffer> | <Uint8Array>Buffer或Uint8Array实例。¥
source<Buffer> | <Uint8Array> ABufferorUint8Arrayinstance. -
fromEnc<string> 当前编码。¥
fromEnc<string> The current encoding. -
toEnc<string> 目标编码。¥
toEnc<string> To target encoding. -
返回:<Buffer>
¥Returns: <Buffer>
将给定的 Buffer 或 Uint8Array 实例从一种字符编码重新编码为另一种。返回新的 Buffer 实例。
¥Re-encodes the given Buffer or Uint8Array instance from one character
encoding to another. Returns a new Buffer instance.
如果 fromEnc 或 toEnc 指定无效的字符编码或不允许从 fromEnc 转换为 toEnc,则抛出错误。
¥Throws if the fromEnc or toEnc specify invalid character encodings or if
conversion from fromEnc to toEnc is not permitted.
buffer.transcode() 支持的编码有:'ascii'、'utf8'、'utf16le'、'ucs2'、'latin1' 和 'binary'。
¥Encodings supported by buffer.transcode() are: 'ascii', 'utf8',
'utf16le', 'ucs2', 'latin1', and 'binary'.
如果给定的字节序列不能在目标编码中充分表示,则转码过程将使用替换字符。例如:
¥The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance:
import { Buffer, transcode } from 'node:buffer';
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'const { Buffer, transcode } = require('node:buffer');
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'由于欧元 (€) 符号在 US-ASCII 中无法表示,因此在转码后的 Buffer 中将其替换为 ?。
¥Because the Euro (€) sign is not representable in US-ASCII, it is replaced
with ? in the transcoded Buffer.