buffer.transcode(source, fromEnc, toEnc)


将给定的 BufferUint8Array 实例从一种字符编码重新编码为另一种字符编码。返回一个新的 Buffer 实例。

🌐 Re-encodes the given Buffer or Uint8Array instance from one character encoding to another. Returns a new Buffer instance.

如果 fromEnctoEnc 指定了无效的字符编码,或者从 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.