readable.setEncoding(encoding)
readable.setEncoding()
方法设置从 Readable
流中读取的数据的字符编码。
¥The readable.setEncoding()
method sets the character encoding for
data read from the Readable
stream.
默认情况下,没有分配编码,流数据将作为 Buffer
对象返回。设置编码会导致流数据作为指定编码的字符串而不是 Buffer
对象返回。例如,调用 readable.setEncoding('utf8')
将导致输出数据被解释为 UTF-8 数据,并作为字符串传递。调用 readable.setEncoding('hex')
将导致数据以十六进制字符串格式编码。
¥By default, no encoding is assigned and stream data will be returned as
Buffer
objects. Setting an encoding causes the stream data
to be returned as strings of the specified encoding rather than as Buffer
objects. For instance, calling readable.setEncoding('utf8')
will cause the
output data to be interpreted as UTF-8 data, and passed as strings. Calling
readable.setEncoding('hex')
will cause the data to be encoded in hexadecimal
string format.
Readable
流将正确处理通过流传送的多字节字符,否则如果简单地将其作为 Buffer
对象从流中提取,这些字符将无法正确解码。
¥The Readable
stream will properly handle multi-byte characters delivered
through the stream that would otherwise become improperly decoded if simply
pulled from the stream as Buffer
objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});