Skip to content

Commit 3e6da45

Browse files
dicearrMylesBorins
authored andcommitted
doc: howto decode buffers extending from Writable
Improved stream documentation with an example of how to decode buffers to strings within a custom Writable. Fixes: #15369 PR-URL: #16403 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com>
1 parent 7e9779a commit 3e6da45

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

doc/api/stream.md

+41
Original file line numberDiff line numberDiff line change
@@ -1407,6 +1407,47 @@ class MyWritable extends Writable {
14071407
}
14081408
```
14091409

1410+
#### Decoding buffers in a Writable Stream
1411+
1412+
Decoding buffers is a common task, for instance, when using transformers whose
1413+
input is a string. This is not a trivial process when using multi-byte
1414+
characters encoding, such as UTF-8. The following example shows how to decode
1415+
multi-byte strings using `StringDecoder` and [Writable][].
1416+
1417+
```js
1418+
const { Writable } = require('stream');
1419+
const { StringDecoder } = require('string_decoder');
1420+
1421+
class StringWritable extends Writable {
1422+
constructor(options) {
1423+
super(options);
1424+
const state = this._writableState;
1425+
this._decoder = new StringDecoder(state.defaultEncoding);
1426+
this.data = '';
1427+
}
1428+
_write(chunk, encoding, callback) {
1429+
if (encoding === 'buffer') {
1430+
chunk = this._decoder.write(chunk);
1431+
}
1432+
this.data += chunk;
1433+
callback();
1434+
}
1435+
_final(callback) {
1436+
this.data += this._decoder.end();
1437+
callback();
1438+
}
1439+
}
1440+
1441+
const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
1442+
const w = new StringWritable();
1443+
1444+
w.write('currency: ');
1445+
w.write(euro[0]);
1446+
w.end(euro[1]);
1447+
1448+
console.log(w.data); // currency: €
1449+
```
1450+
14101451
### Implementing a Readable Stream
14111452

14121453
The `stream.Readable` class is extended to implement a [Readable][] stream.

0 commit comments

Comments
 (0)