Skip to content
This repository was archived by the owner on Aug 31, 2018. It is now read-only.

Commit eb2163a

Browse files
dicearrQard
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: nodejs/node#15369 PR-URL: nodejs/node#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 747a74b commit eb2163a

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
@@ -1510,6 +1510,47 @@ class MyWritable extends Writable {
15101510
}
15111511
```
15121512

1513+
#### Decoding buffers in a Writable Stream
1514+
1515+
Decoding buffers is a common task, for instance, when using transformers whose
1516+
input is a string. This is not a trivial process when using multi-byte
1517+
characters encoding, such as UTF-8. The following example shows how to decode
1518+
multi-byte strings using `StringDecoder` and [Writable][].
1519+
1520+
```js
1521+
const { Writable } = require('stream');
1522+
const { StringDecoder } = require('string_decoder');
1523+
1524+
class StringWritable extends Writable {
1525+
constructor(options) {
1526+
super(options);
1527+
const state = this._writableState;
1528+
this._decoder = new StringDecoder(state.defaultEncoding);
1529+
this.data = '';
1530+
}
1531+
_write(chunk, encoding, callback) {
1532+
if (encoding === 'buffer') {
1533+
chunk = this._decoder.write(chunk);
1534+
}
1535+
this.data += chunk;
1536+
callback();
1537+
}
1538+
_final(callback) {
1539+
this.data += this._decoder.end();
1540+
callback();
1541+
}
1542+
}
1543+
1544+
const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
1545+
const w = new StringWritable();
1546+
1547+
w.write('currency: ');
1548+
w.write(euro[0]);
1549+
w.end(euro[1]);
1550+
1551+
console.log(w.data); // currency: €
1552+
```
1553+
15131554
### Implementing a Readable Stream
15141555

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

0 commit comments

Comments
 (0)