解码 buffer 是一个常见的任务,例如使用转换流处理字符串输入。 当使用多字节的字符编码(比如 UTF-8)时,这是一个重要的处理。 下面的例子展示了如何使用 StringDecoder 和 [Writable] 解码多字节的字符串。

    1. const { Writable } = require('stream');
    2. const { StringDecoder } = require('string_decoder');
    3. class StringWritable extends Writable {
    4. constructor(options) {
    5. super(options);
    6. this._decoder = new StringDecoder(options && options.defaultEncoding);
    7. this.data = '';
    8. }
    9. _write(chunk, encoding, callback) {
    10. if (encoding === 'buffer') {
    11. chunk = this._decoder.write(chunk);
    12. }
    13. this.data += chunk;
    14. callback();
    15. }
    16. _final(callback) {
    17. this.data += this._decoder.end();
    18. callback();
    19. }
    20. }
    21. const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
    22. const w = new StringWritable();
    23. w.write('货币: ');
    24. w.write(euro[0]);
    25. w.end(euro[1]);
    26. console.log(w.data); // 货币: €