buffer.transcode(source, fromEnc, toEnc)


将指定的 BufferUint8Array 从一个字符编码重新编码到另一个字符,并返回新的 Buffer。

如果 fromEnctoEnc 指定了无效的字符编码,或者无法从 fromEnc 转换为 toEnc,则抛出异常。

buffer.transcode() 支持的字符编码有 'ascii''utf8''utf16le''ucs2''latin1''binary'

如果指定的字节序列无法用目标字符编码表示,则转码过程会使用替代的字符。例如:

const buffer = require('buffer');

const newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// 打印: '?'

因为欧元符号()无法在 US-ASCII 中表示,所以在转码 Buffer 时使用 ? 代替。

该属性是在 require('buffer') 返回的 buffer 模块上,而不是在 Buffer 全局变量或 Buffer 实例上。

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

Throws if the fromEnc or toEnc specify invalid character encodings or if conversion from fromEnc to toEnc is not permitted.

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:

const buffer = require('buffer');

const newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'

Because the Euro () sign is not representable in US-ASCII, it is replaced with ? in the transcoded Buffer.

Note that this is a property on the buffer module returned by require('buffer'), not on the Buffer global or a Buffer instance.