buffer.transcode(source, fromEnc, toEnc)


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

如果 fromEnctoEnc 指定无效的字符编码或不允许从 fromEnc 转换为 toEnc,则抛出错误。

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

如果给定的字节序列不能在目标编码中充分表示,则转码过程将使用替换字符。 例如:

import { Buffer, transcode } from 'node:buffer';

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

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

由于欧元 () 符号在 US-ASCII 中无法表示,因此在转码后的 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:

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: '?'

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