File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -1510,6 +1510,47 @@ class MyWritable extends Writable {
1510
1510
}
1511
1511
```
1512
1512
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
+
1513
1554
### Implementing a Readable Stream
1514
1555
1515
1556
The ` stream.Readable ` class is extended to implement a [ Readable] [ ] stream.
You can’t perform that action at this time.
0 commit comments