Datasets:
File size: 78,842 Bytes
545ed55 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 | # Stream#
Source: https://nodejs.org/docs/latest-v7.x/api/stream.html
Version: 7.x
```None
Stability: 2 - Stable
```
A stream is an abstract interface for working with streaming data in Node.js.
The `stream` module provides a base API that makes it easy to build objects
that implement the stream interface.
There are many stream objects provided by Node.js. For instance, a
[request to an HTTP server](http.html#http_class_http_incomingmessage) and [`process.stdout`](process.html#process_process_stdout)
are both stream instances.
Streams can be readable, writable, or both. All streams are instances of
[`EventEmitter`](events.html#events_class_eventemitter).
The `stream` module can be accessed using:
```None
const stream = require('stream');
```
While it is important for all Node.js users to understand how streams work,
the `stream` module itself is most useful for developers that are creating new
types of stream instances. Developers who are primarily *consuming* stream
objects will rarely (if ever) have need to use the `stream` module directly.
## Organization of this Document[#](#stream_organization_of_this_document)
This document is divided into two primary sections with a third section for
additional notes. The first section explains the elements of the stream API that
are required to *use* streams within an application. The second section explains
the elements of the API that are required to *implement* new types of streams.
## Types of Streams[#](#stream_types_of_streams)
There are four fundamental stream types within Node.js:
* [Readable](#stream_class_stream_readable) - streams from which data can be read (for example
[`fs.createReadStream()`](fs.html#fs_fs_createreadstream_path_options)).
* [Writable](#stream_class_stream_writable) - streams to which data can be written (for example
[`fs.createWriteStream()`](fs.html#fs_fs_createwritestream_path_options)).
* [Duplex](#stream_class_stream_duplex) - streams that are both Readable and Writable (for example
[`net.Socket`](net.html#net_class_net_socket)).
* [Transform](#stream_class_stream_transform) - Duplex streams that can modify or transform the data as it
is written and read (for example [`zlib.createDeflate()`](zlib.html#zlib_zlib_createdeflate_options)).
### Object Mode[#](#stream_object_mode)
All streams created by Node.js APIs operate exclusively on strings and `Buffer`
objects. It is possible, however, for stream implementations to work with other
types of JavaScript values (with the exception of `null`, which serves a special
purpose within streams). Such streams are considered to operate in "object
mode".
Stream instances are switched into object mode using the `objectMode` option
when the stream is created. Attempting to switch an existing stream into
object mode is not safe.
### Buffering[#](#stream_buffering)
Both [Writable](#stream_class_stream_writable) and [Readable](#stream_class_stream_readable) streams will store data in an internal
buffer that can be retrieved using `writable._writableState.getBuffer()` or
`readable._readableState.buffer`, respectively.
The amount of data potentially buffered depends on the `highWaterMark` option
passed into the streams constructor. For normal streams, the `highWaterMark`
option specifies a total number of bytes. For streams operating in object mode,
the `highWaterMark` specifies a total number of objects.
Data is buffered in Readable streams when the implementation calls
[`stream.push(chunk)`](#stream_readable_push_chunk_encoding). If the consumer of the Stream does not
call [`stream.read()`](#stream_readable_read_size), the data will sit in the internal
queue until it is consumed.
Once the total size of the internal read buffer reaches the threshold specified
by `highWaterMark`, the stream will temporarily stop reading data from the
underlying resource until the data currently buffered can be consumed (that is,
the stream will stop calling the internal `readable._read()` method that is
used to fill the read buffer).
Data is buffered in Writable streams when the
[`writable.write(chunk)`](#stream_writable_write_chunk_encoding_callback) method is called repeatedly. While the
total size of the internal write buffer is below the threshold set by
`highWaterMark`, calls to `writable.write()` will return `true`. Once
the size of the internal buffer reaches or exceeds the `highWaterMark`, `false`
will be returned.
A key goal of the `stream` API, particularly the [`stream.pipe()`](#stream_readable_pipe_destination_options) method,
is to limit the buffering of data to acceptable levels such that sources and
destinations of differing speeds will not overwhelm the available memory.
Because [Duplex](#stream_class_stream_duplex) and [Transform](#stream_class_stream_transform) streams are both Readable and Writable,
each maintain *two* separate internal buffers used for reading and writing,
allowing each side to operate independently of the other while maintaining an
appropriate and efficient flow of data. For example, [`net.Socket`](net.html#net_class_net_socket) instances
are [Duplex](#stream_class_stream_duplex) streams whose Readable side allows consumption of data received
*from* the socket and whose Writable side allows writing data *to* the socket.
Because data may be written to the socket at a faster or slower rate than data
is received, it is important for each side to operate (and buffer) independently
of the other.
## API for Stream Consumers[#](#stream_api_for_stream_consumers)
Almost all Node.js applications, no matter how simple, use streams in some
manner. The following is an example of using streams in a Node.js application
that implements an HTTP server:
```None
const http = require('http');
const server = http.createServer( (req, res) => {
// req is an http.IncomingMessage, which is a Readable Stream
// res is an http.ServerResponse, which is a Writable Stream
let body = '';
// Get the data as utf8 strings.
// If an encoding is not set, Buffer objects will be received.
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added
req.on('data', (chunk) => {
body += chunk;
});
// the end event indicates that the entire body has been received
req.on('end', () => {
try {
const data = JSON.parse(body);
// write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(1337);
// $ curl localhost:1337 -d '{}'
// object
// $ curl localhost:1337 -d '"foo"'
// string
// $ curl localhost:1337 -d 'not json'
// error: Unexpected token o
```
[Writable](#stream_class_stream_writable) streams (such as `res` in the example) expose methods such as
`write()` and `end()` that are used to write data onto the stream.
[Readable](#stream_class_stream_readable) streams use the [`EventEmitter`](events.html#events_class_eventemitter) API for notifying application
code when data is available to be read off the stream. That available data can
be read from the stream in multiple ways.
Both [Writable](#stream_class_stream_writable) and [Readable](#stream_class_stream_readable) streams use the [`EventEmitter`](events.html#events_class_eventemitter) API in
various ways to communicate the current state of the stream.
[Duplex](#stream_class_stream_duplex) and [Transform](#stream_class_stream_transform) streams are both [Writable](#stream_class_stream_writable) and [Readable](#stream_class_stream_readable).
Applications that are either writing data to or consuming data from a stream
are not required to implement the stream interfaces directly and will generally
have no reason to call `require('stream')`.
Developers wishing to implement new types of streams should refer to the
section [API for Stream Implementers](#stream_api_for_stream_implementers).
### Writable Streams[#](#stream_writable_streams)
Writable streams are an abstraction for a *destination* to which data is
written.
Examples of [Writable](#stream_class_stream_writable) streams include:
* [HTTP requests, on the client](http.html#http_class_http_clientrequest)
* [HTTP responses, on the server](http.html#http_class_http_serverresponse)
* [fs write streams](fs.html#fs_class_fs_writestream)
* [zlib streams](zlib.html)
* [crypto streams](crypto.html)
* [TCP sockets](net.html#net_class_net_socket)
* [child process stdin](child_process.html#child_process_child_stdin)
* [`process.stdout`](process.html#process_process_stdout), [`process.stderr`](process.html#process_process_stderr)
*Note*: Some of these examples are actually [Duplex](#stream_class_stream_duplex) streams that implement
the [Writable](#stream_class_stream_writable) interface.
All [Writable](#stream_class_stream_writable) streams implement the interface defined by the
`stream.Writable` class.
While specific instances of [Writable](#stream_class_stream_writable) streams may differ in various ways,
all Writable streams follow the same fundamental usage pattern as illustrated
in the example below:
```None
const myStream = getWritableStreamSomehow();
myStream.write('some data');
myStream.write('some more data');
myStream.end('done writing data');
```
#### Class: stream.Writable[#](#stream_class_stream_writable)
Added in: v0.9.4
##### Event: 'close'[#](#stream_event_close)
Added in: v0.9.4
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
that no more events will be emitted, and no further computation will occur.
Not all Writable streams will emit the `'close'` event.
##### Event: 'drain'[#](#stream_event_drain)
Added in: v0.9.4
If a call to [`stream.write(chunk)`](#stream_writable_write_chunk_encoding_callback) returns `false`, the
`'drain'` event will be emitted when it is appropriate to resume writing data
to the stream.
```None
// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
let i = 1000000;
write();
function write() {
var ok = true;
do {
i--;
if (i === 0) {
// last time!
writer.write(data, encoding, callback);
} else {
// see if we should continue, or wait
// don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding);
}
} while (i > 0 && ok);
if (i > 0) {
// had to stop early!
// write some more once it drains
writer.once('drain', write);
}
}
}
```
##### Event: 'error'[#](#stream_event_error)
Added in: v0.9.4
* [<Error>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
The `'error'` event is emitted if an error occurred while writing or piping
data. The listener callback is passed a single `Error` argument when called.
*Note*: The stream is not closed when the `'error'` event is emitted.
##### Event: 'finish'[#](#stream_event_finish)
Added in: v0.9.4
The `'finish'` event is emitted after the [`stream.end()`](#stream_writable_end_chunk_encoding_callback) method
has been called, and all data has been flushed to the underlying system.
```None
const writer = getWritableStreamSomehow();
for (var i = 0; i < 100; i ++) {
writer.write(`hello, #${i}!\n`);
}
writer.end('This is the end\n');
writer.on('finish', () => {
console.error('All writes are now complete.');
});
```
##### Event: 'pipe'[#](#stream_event_pipe)
Added in: v0.9.4
* `src` [<stream.Readable>](stream.html#stream_class_stream_readable) source stream that is piping to this writable
The `'pipe'` event is emitted when the [`stream.pipe()`](#stream_readable_pipe_destination_options) method is called on
a readable stream, adding this writable to its set of destinations.
```None
const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('pipe', (src) => {
console.error('something is piping into the writer');
assert.equal(src, reader);
});
reader.pipe(writer);
```
##### Event: 'unpipe'[#](#stream_event_unpipe)
Added in: v0.9.4
* `src` <[Readable](#stream_class_stream_readable) Stream> The source stream that
[unpiped](#stream_readable_unpipe_destination) this writable
The `'unpipe'` event is emitted when the [`stream.unpipe()`](#stream_readable_unpipe_destination) method is called
on a [Readable](#stream_class_stream_readable) stream, removing this [Writable](#stream_class_stream_writable) from its set of
destinations.
```None
const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
console.error('Something has stopped piping into the writer.');
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);
```
##### writable.cork()[#](#stream_writable_cork)
Added in: v0.11.2
The `writable.cork()` method forces all written data to be buffered in memory.
The buffered data will be flushed when either the [`stream.uncork()`](#stream_writable_uncork) or
[`stream.end()`](#stream_writable_end_chunk_encoding_callback) methods are called.
The primary intent of `writable.cork()` is to avoid a situation where writing
many small chunks of data to a stream do not cause a backup in the internal
buffer that would have an adverse impact on performance. In such situations,
implementations that implement the `writable._writev()` method can perform
buffered writes in a more optimized manner.
See also: [`writable.uncork()`](#stream_writable_uncork).
##### writable.end([chunk][, encoding][, callback])[#](#stream_writable_end_chunk_encoding_callback)
Added in: v0.9.4
* `chunk` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Buffer>](buffer.html#buffer_class_buffer) | <any> Optional data to write. For streams not operating
in object mode, `chunk` must be a string or a `Buffer`. For object mode
streams, `chunk` may be any JavaScript value other than `null`.
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding, if `chunk` is a String
* `callback` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional callback for when the stream is finished
Calling the `writable.end()` method signals that no more data will be written
to the [Writable](#stream_class_stream_writable). The optional `chunk` and `encoding` arguments allow one
final additional chunk of data to be written immediately before closing the
stream. If provided, the optional `callback` function is attached as a listener
for the [`'finish'`](#stream_event_finish) event.
Calling the [`stream.write()`](#stream_writable_write_chunk_encoding_callback) method after calling
[`stream.end()`](#stream_writable_end_chunk_encoding_callback) will raise an error.
```None
// write 'hello, ' and then end with 'world!'
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// writing more now is not allowed!
```
##### writable.setDefaultEncoding(encoding)[#](#stream_writable_setdefaultencoding_encoding)
History
| Version | Changes |
| --- | --- |
| v6.1.0 | This method now returns a reference to `writable`. |
| v0.11.15 | Added in: v0.11.15 |
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The new default encoding
* Returns: `this`
The `writable.setDefaultEncoding()` method sets the default `encoding` for a
[Writable](#stream_class_stream_writable) stream.
##### writable.uncork()[#](#stream_writable_uncork)
Added in: v0.11.2
The `writable.uncork()` method flushes all data buffered since
[`stream.cork()`](#stream_writable_cork) was called.
When using [`writable.cork()`](#stream_writable_cork) and `writable.uncork()` to manage the buffering
of writes to a stream, it is recommended that calls to `writable.uncork()` be
deferred using `process.nextTick()`. Doing so allows batching of all
`writable.write()` calls that occur within a given Node.js event loop phase.
```None
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
```
If the [`writable.cork()`](#stream_writable_cork) method is called multiple times on a stream, the same
number of calls to `writable.uncork()` must be called to flush the buffered
data.
```None
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
```
See also: [`writable.cork()`](#stream_writable_cork).
##### writable.write(chunk[, encoding][, callback])[#](#stream_writable_write_chunk_encoding_callback)
History
| Version | Changes |
| --- | --- |
| v6.0.0 | Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode. |
| v0.9.4 | Added in: v0.9.4 |
* `chunk` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Buffer>](buffer.html#buffer_class_buffer) The data to write
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding, if `chunk` is a String
* `callback` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback for when this chunk of data is flushed
* Returns: [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `false` if the stream wishes for the calling code to
wait for the `'drain'` event to be emitted before continuing to write
additional data; otherwise `true`.
The `writable.write()` method writes some data to the stream, and calls the
supplied `callback` once the data has been fully handled. If an error
occurs, the `callback` *may or may not* be called with the error as its
first argument. To reliably detect write errors, add a listener for the
`'error'` event.
The return value is `true` if the internal buffer is less than the
`highWaterMark` configured when the stream was created after admitting `chunk`.
If `false` is returned, further attempts to write data to the stream should
stop until the [`'drain'`](#stream_event_drain) event is emitted.
While a stream is not draining, calls to `write()` will buffer `chunk`, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the `'drain'` event will be emitted.
It is recommended that once write() returns false, no more chunks be written
until the `'drain'` event is emitted. While calling `write()` on a stream that
is not draining is allowed, Node.js will buffer all written chunks until
maximum memory usage occurs, at which point it will abort unconditionally.
Even before it aborts, high memory usage will cause poor garbage collector
performance and high RSS (which is not typically released back to the system,
even after the memory is no longer required). Since TCP sockets may never
drain if the remote peer does not read the data, writing a socket that is
not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
problematic for a [Transform](#stream_class_stream_transform), because the `Transform` streams are paused
by default until they are piped or an `'data'` or `'readable'` event handler
is added.
If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a [Readable](#stream_class_stream_readable) and use
[`stream.pipe()`](#stream_readable_pipe_destination_options). However, if calling `write()` is preferred, it is
possible to respect backpressure and avoid memory issues using the
[`'drain'`](#stream_event_drain) event:
```None
function write (data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb)
} else {
process.nextTick(cb)
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('write completed, do more writes now')
})
```
A Writable stream in object mode will always ignore the `encoding` argument.
### Readable Streams[#](#stream_readable_streams)
Readable streams are an abstraction for a *source* from which data is
consumed.
Examples of Readable streams include:
* [HTTP responses, on the client](http.html#http_class_http_incomingmessage)
* [HTTP requests, on the server](http.html#http_class_http_incomingmessage)
* [fs read streams](fs.html#fs_class_fs_readstream)
* [zlib streams](zlib.html)
* [crypto streams](crypto.html)
* [TCP sockets](net.html#net_class_net_socket)
* [child process stdout and stderr](child_process.html#child_process_child_stdout)
* [`process.stdin`](process.html#process_process_stdin)
All [Readable](#stream_class_stream_readable) streams implement the interface defined by the
`stream.Readable` class.
#### Two Modes[#](#stream_two_modes)
Readable streams effectively operate in one of two modes: flowing and paused.
When in flowing mode, data is read from the underlying system automatically
and provided to an application as quickly as possible using events via the
[`EventEmitter`](events.html#events_class_eventemitter) interface.
In paused mode, the [`stream.read()`](#stream_readable_read_size) method must be called
explicitly to read chunks of data from the stream.
All [Readable](#stream_class_stream_readable) streams begin in paused mode but can be switched to flowing
mode in one of the following ways:
* Adding a [`'data'`](#stream_event_data) event handler.
* Calling the [`stream.resume()`](#stream_readable_resume) method.
* Calling the [`stream.pipe()`](#stream_readable_pipe_destination_options) method to send the data to a [Writable](#stream_class_stream_writable).
The Readable can switch back to paused mode using one of the following:
* If there are no pipe destinations, by calling the
[`stream.pause()`](#stream_readable_pause) method.
* If there are pipe destinations, by removing any [`'data'`](#stream_event_data) event
handlers, and removing all pipe destinations by calling the
[`stream.unpipe()`](#stream_readable_unpipe_destination) method.
The important concept to remember is that a Readable will not generate data
until a mechanism for either consuming or ignoring that data is provided. If
the consuming mechanism is disabled or taken away, the Readable will *attempt*
to stop generating the data.
*Note*: For backwards compatibility reasons, removing [`'data'`](#stream_event_data) event
handlers will **not** automatically pause the stream. Also, if there are piped
destinations, then calling [`stream.pause()`](#stream_readable_pause) will not guarantee
that the stream will *remain* paused once those destinations drain and ask for
more data.
*Note*: If a [Readable](#stream_class_stream_readable) is switched into flowing mode and there are no
consumers available to handle the data, that data will be lost. This can occur,
for instance, when the `readable.resume()` method is called without a listener
attached to the `'data'` event, or when a `'data'` event handler is removed
from the stream.
#### Three States[#](#stream_three_states)
The "two modes" of operation for a Readable stream are a simplified abstraction
for the more complicated internal state management that is happening within the
Readable stream implementation.
Specifically, at any given point in time, every Readable is in one of three
possible states:
* `readable._readableState.flowing = null`
* `readable._readableState.flowing = false`
* `readable._readableState.flowing = true`
When `readable._readableState.flowing` is `null`, no mechanism for consuming the
streams data is provided so the stream will not generate its data.
Attaching a listener for the `'data'` event, calling the `readable.pipe()`
method, or calling the `readable.resume()` method will switch
`readable._readableState.flowing` to `true`, causing the Readable to begin
actively emitting events as data is generated.
Calling `readable.pause()`, `readable.unpipe()`, or receiving "back pressure"
will cause the `readable._readableState.flowing` to be set as `false`,
temporarily halting the flowing of events but *not* halting the generation of
data.
While `readable._readableState.flowing` is `false`, data may be accumulating
within the streams internal buffer.
#### Choose One[#](#stream_choose_one)
The Readable stream API evolved across multiple Node.js versions and provides
multiple methods of consuming stream data. In general, developers should choose
*one* of the methods of consuming data and *should never* use multiple methods
to consume data from a single stream.
Use of the `readable.pipe()` method is recommended for most users as it has been
implemented to provide the easiest way of consuming stream data. Developers that
require more fine-grained control over the transfer and generation of data can
use the [`EventEmitter`](events.html#events_class_eventemitter) and `readable.pause()`/`readable.resume()` APIs.
#### Class: stream.Readable[#](#stream_class_stream_readable)
Added in: v0.9.4
##### Event: 'close'[#](#stream_event_close_1)
Added in: v0.9.4
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
that no more events will be emitted, and no further computation will occur.
Not all [Readable](#stream_class_stream_readable) streams will emit the `'close'` event.
##### Event: 'data'[#](#stream_event_data)
Added in: v0.9.4
* `chunk` [<Buffer>](buffer.html#buffer_class_buffer) | [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | <any> The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or `Buffer`.
For streams that are in object mode, the chunk can be any JavaScript value
other than `null`.
The `'data'` event is emitted whenever the stream is relinquishing ownership of
a chunk of data to a consumer. This may occur whenever the stream is switched
in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by
attaching a listener callback to the `'data'` event. The `'data'` event will
also be emitted whenever the `readable.read()` method is called and a chunk of
data is available to be returned.
Attaching a `'data'` event listener to a stream that has not been explicitly
paused will switch the stream into flowing mode. Data will then be passed as
soon as it is available.
The listener callback will be passed the chunk of data as a string if a default
encoding has been specified for the stream using the
`readable.setEncoding()` method; otherwise the data will be passed as a
`Buffer`.
```None
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
```
##### Event: 'end'[#](#stream_event_end)
Added in: v0.9.4
The `'end'` event is emitted when there is no more data to be consumed from
the stream.
*Note*: The `'end'` event **will not be emitted** unless the data is
completely consumed. This can be accomplished by switching the stream into
flowing mode, or by calling [`stream.read()`](#stream_readable_read_size) repeatedly until
all data has been consumed.
```None
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readable.on('end', () => {
console.log('There will be no more data.');
});
```
##### Event: 'error'[#](#stream_event_error_1)
Added in: v0.9.4
* [<Error>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
The `'error'` event may be emitted by a Readable implementation at any time.
Typically, this may occur if the underlying stream in unable to generate data
due to an underlying internal failure, or when a stream implementation attempts
to push an invalid chunk of data.
The listener callback will be passed a single `Error` object.
##### Event: 'readable'[#](#stream_event_readable)
Added in: v0.9.4
The `'readable'` event is emitted when there is data available to be read from
the stream. In some cases, attaching a listener for the `'readable'` event will
cause some amount of data to be read into an internal buffer.
```None
const readable = getReadableStreamSomehow();
readable.on('readable', () => {
// there is some data to read now
});
```
The `'readable'` event will also be emitted once the end of the stream data
has been reached but before the `'end'` event is emitted.
Effectively, the `'readable'` event indicates that the stream has new
information: either new data is available or the end of the stream has been
reached. In the former case, [`stream.read()`](#stream_readable_read_size) will return the
available data. In the latter case, [`stream.read()`](#stream_readable_read_size) will return
`null`. For instance, in the following example, `foo.txt` is an empty file:
```None
const fs = require('fs');
const rr = fs.createReadStream('foo.txt');
rr.on('readable', () => {
console.log('readable:', rr.read());
});
rr.on('end', () => {
console.log('end');
});
```
The output of running this script is:
```None
$ node test.js
readable: null
end
```
*Note*: In general, the `readable.pipe()` and `'data'` event mechanisms are
preferred over the use of the `'readable'` event.
##### readable.isPaused()[#](#stream_readable_ispaused)
Added in: v0.11.14
* Returns: [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
The `readable.isPaused()` method returns the current operating state of the
Readable. This is used primarily by the mechanism that underlies the
`readable.pipe()` method. In most typical cases, there will be no reason to
use this method directly.
```None
const readable = new stream.Readable
readable.isPaused() // === false
readable.pause()
readable.isPaused() // === true
readable.resume()
readable.isPaused() // === false
```
##### readable.pause()[#](#stream_readable_pause)
Added in: v0.9.4
* Returns: `this`
The `readable.pause()` method will cause a stream in flowing mode to stop
emitting [`'data'`](#stream_event_data) events, switching out of flowing mode. Any data that
becomes available will remain in the internal buffer.
```None
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
```
##### readable.pipe(destination[, options])[#](#stream_readable_pipe_destination_options)
Added in: v0.9.4
* `destination` [<stream.Writable>](stream.html#stream_class_stream_writable) The destination for writing data
* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Pipe options
+ `end` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) End the writer when the reader ends. Defaults to `true`.
The `readable.pipe()` method attaches a [Writable](#stream_class_stream_writable) stream to the `readable`,
causing it to switch automatically into flowing mode and push all of its data
to the attached [Writable](#stream_class_stream_writable). The flow of data will be automatically managed so
that the destination Writable stream is not overwhelmed by a faster Readable
stream.
The following example pipes all of the data from the `readable` into a file
named `file.txt`:
```None
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'
readable.pipe(writable);
```
It is possible to attach multiple Writable streams to a single Readable stream.
The `readable.pipe()` method returns a reference to the *destination* stream
making it possible to set up chains of piped streams:
```None
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
```
By default, [`stream.end()`](#stream_writable_end_chunk_encoding_callback) is called on the destination Writable
stream when the source Readable stream emits [`'end'`](#stream_event_end), so that the
destination is no longer writable. To disable this default behavior, the `end`
option can be passed as `false`, causing the destination stream to remain open,
as illustrated in the following example:
```None
reader.pipe(writer, { end: false });
reader.on('end', () => {
writer.end('Goodbye\n');
});
```
One important caveat is that if the Readable stream emits an error during
processing, the Writable destination *is not closed* automatically. If an
error occurs, it will be necessary to *manually* close each stream in order
to prevent memory leaks.
*Note*: The [`process.stderr`](process.html#process_process_stderr) and [`process.stdout`](process.html#process_process_stdout) Writable streams are
never closed until the Node.js process exits, regardless of the specified
options.
##### readable.read([size])[#](#stream_readable_read_size)
Added in: v0.9.4
* `size` [<number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optional argument to specify how much data to read.
* Return [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [<Buffer>](buffer.html#buffer_class_buffer) | [<null>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
The `readable.read()` method pulls some data out of the internal buffer and
returns it. If no data available to be read, `null` is returned. By default,
the data will be returned as a `Buffer` object unless an encoding has been
specified using the `readable.setEncoding()` method or the stream is operating
in object mode.
The optional `size` argument specifies a specific number of bytes to read. If
`size` bytes are not available to be read, `null` will be returned *unless*
the stream has ended, in which case all of the data remaining in the internal
buffer will be returned (*even if it exceeds `size` bytes*).
If the `size` argument is not specified, all of the data contained in the
internal buffer will be returned.
The `readable.read()` method should only be called on Readable streams operating
in paused mode. In flowing mode, `readable.read()` is called automatically until
the internal buffer is fully drained.
```None
const readable = getReadableStreamSomehow();
readable.on('readable', () => {
var chunk;
while (null !== (chunk = readable.read())) {
console.log(`Received ${chunk.length} bytes of data.`);
}
});
```
In general, it is recommended that developers avoid the use of the `'readable'`
event and the `readable.read()` method in favor of using either
`readable.pipe()` or the `'data'` event.
A Readable stream in object mode will always return a single item from
a call to [`readable.read(size)`](#stream_readable_read_size), regardless of the value of the
`size` argument.
*Note:* If the `readable.read()` method returns a chunk of data, a `'data'`
event will also be emitted.
*Note*: Calling [`stream.read([size])`](#stream_readable_read_size) after the [`'end'`](#stream_event_end)
event has been emitted will return `null`. No runtime error will be raised.
##### readable.resume()[#](#stream_readable_resume)
Added in: v0.9.4
* Returns: `this`
The `readable.resume()` method causes an explicitly paused Readable stream to
resume emitting [`'data'`](#stream_event_data) events, switching the stream into flowing mode.
The `readable.resume()` method can be used to fully consume the data from a
stream without actually processing any of that data as illustrated in the
following example:
```None
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
```
##### readable.setEncoding(encoding)[#](#stream_readable_setencoding_encoding)
Added in: v0.9.4
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding to use.
* Returns: `this`
The `readable.setEncoding()` method sets the default character encoding for
data read from the Readable stream.
Setting an encoding causes the stream data
to be returned as string of the specified encoding rather than as `Buffer`
objects. For instance, calling `readable.setEncoding('utf8')` will cause the
output data will 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.
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.
Encoding can be disabled by calling `readable.setEncoding(null)`. This approach
is useful when working with binary data or with large multi-byte strings spread
out over multiple chunks.
```None
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);
});
```
##### readable.unpipe([destination])[#](#stream_readable_unpipe_destination)
Added in: v0.9.4
* `destination` [<stream.Writable>](stream.html#stream_class_stream_writable) Optional specific stream to unpipe
The `readable.unpipe()` method detaches a Writable stream previously attached
using the [`stream.pipe()`](#stream_readable_pipe_destination_options) method.
If the `destination` is not specified, then *all* pipes are detached.
If the `destination` is specified, but no pipe is set up for it, then
the method does nothing.
```None
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt');
readable.unpipe(writable);
console.log('Manually close the file stream');
writable.end();
}, 1000);
```
##### readable.unshift(chunk)[#](#stream_readable_unshift_chunk)
Added in: v0.9.11
* `chunk` [<Buffer>](buffer.html#buffer_class_buffer) | [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | <any> Chunk of data to unshift onto the read queue
The `readable.unshift()` method pushes a chunk of data back into the internal
buffer. This is useful in certain situations where a stream is being consumed by
code that needs to "un-consume" some amount of data that it has optimistically
pulled out of the source, so that the data can be passed on to some other party.
*Note*: The `stream.unshift(chunk)` method cannot be called after the
[`'end'`](#stream_event_end) event has been emitted or a runtime error will be thrown.
Developers using `stream.unshift()` often should consider switching to
use of a [Transform](#stream_class_stream_transform) stream instead. See the [API for Stream Implementers](#stream_api_for_stream_implementers)
section for more information.
```None
// Pull off a header delimited by \n\n
// use unshift() if we get too much
// Call the callback with (error, header, stream)
const StringDecoder = require('string_decoder').StringDecoder;
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
var header = '';
function onReadable() {
var chunk;
while (null !== (chunk = stream.read())) {
var str = decoder.write(chunk);
if (str.match(/\n\n/)) {
// found the header boundary
var split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// remove the readable listener before unshifting
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// now the body of the message can be read from the stream.
callback(null, header, stream);
} else {
// still reading the header.
header += str;
}
}
}
}
```
*Note*: Unlike [`stream.push(chunk)`](#stream_readable_push_chunk_encoding), `stream.unshift(chunk)`
will not end the reading process by resetting the internal reading state of the
stream. This can cause unexpected results if `readable.unshift()` is called
during a read (i.e. from within a [`stream._read()`](#stream_readable_read_size_1)
implementation on a custom stream). Following the call to `readable.unshift()`
with an immediate [`stream.push('')`](#stream_readable_push_chunk_encoding) will reset the reading state
appropriately, however it is best to simply avoid calling `readable.unshift()`
while in the process of performing a read.
##### readable.wrap(stream)[#](#stream_readable_wrap_stream)
Added in: v0.9.4
* `stream` [<Stream>](stream.html#stream_stream) An "old style" readable stream
Versions of Node.js prior to v0.10 had streams that did not implement the
entire `stream` module API as it is currently defined. (See [Compatibility](#stream_compatibility_with_older_node_js_versions)
for more information.)
When using an older Node.js library that emits [`'data'`](#stream_event_data) events and has a
[`stream.pause()`](#stream_readable_pause) method that is advisory only, the
`readable.wrap()` method can be used to create a [Readable](#stream_class_stream_readable) stream that uses
the old stream as its data source.
It will rarely be necessary to use `readable.wrap()` but the method has been
provided as a convenience for interacting with older Node.js applications and
libraries.
For example:
```None
const OldReader = require('./old-api-module.js').OldReader;
const Readable = require('stream').Readable;
const oreader = new OldReader;
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
```
### Duplex and Transform Streams[#](#stream_duplex_and_transform_streams)
#### Class: stream.Duplex[#](#stream_class_stream_duplex)
History
| Version | Changes |
| --- | --- |
| v6.8.0 | Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`. |
| v0.9.4 | Added in: v0.9.4 |
Duplex streams are streams that implement both the [Readable](#stream_class_stream_readable) and
[Writable](#stream_class_stream_writable) interfaces.
Examples of Duplex streams include:
* [TCP sockets](net.html#net_class_net_socket)
* [zlib streams](zlib.html)
* [crypto streams](crypto.html)
#### Class: stream.Transform[#](#stream_class_stream_transform)
Added in: v0.9.4
Transform streams are [Duplex](#stream_class_stream_duplex) streams where the output is in some way
related to the input. Like all [Duplex](#stream_class_stream_duplex) streams, Transform streams
implement both the [Readable](#stream_class_stream_readable) and [Writable](#stream_class_stream_writable) interfaces.
Examples of Transform streams include:
* [zlib streams](zlib.html)
* [crypto streams](crypto.html)
## API for Stream Implementers[#](#stream_api_for_stream_implementers)
The `stream` module API has been designed to make it possible to easily
implement streams using JavaScript's prototypal inheritance model.
First, a stream developer would declare a new JavaScript class that extends one
of the four basic stream classes (`stream.Writable`, `stream.Readable`,
`stream.Duplex`, or `stream.Transform`), making sure they call the appropriate
parent class constructor:
```None
const Writable = require('stream').Writable;
class MyWritable extends Writable {
constructor(options) {
super(options);
}
}
```
The new stream class must then implement one or more specific methods, depending
on the type of stream being created, as detailed in the chart below:
| Use-case | Class | Method(s) to implement |
| --- | --- | --- |
| Reading only | [Readable](#stream_class_stream_readable) | `_read` |
| Writing only | [Writable](#stream_class_stream_writable) | `_write`, `_writev` |
| Reading and writing | [Duplex](#stream_class_stream_duplex) | `_read`, `_write`, `_writev` |
| Operate on written data, then read the result | [Transform](#stream_class_stream_transform) | `_transform`, `_flush` |
*Note*: The implementation code for a stream should *never* call the "public"
methods of a stream that are intended for use by consumers (as described in
the [API for Stream Consumers](#stream_api_for_stream_consumers) section). Doing so may lead to adverse
side effects in application code consuming the stream.
### Simplified Construction[#](#stream_simplified_construction)
Added in: v1.2.0
For many simple cases, it is possible to construct a stream without relying on
inheritance. This can be accomplished by directly creating instances of the
`stream.Writable`, `stream.Readable`, `stream.Duplex` or `stream.Transform`
objects and passing appropriate methods as constructor options.
For example:
```None
const Writable = require('stream').Writable;
const myWritable = new Writable({
write(chunk, encoding, callback) {
// ...
}
});
```
### Implementing a Writable Stream[#](#stream_implementing_a_writable_stream)
The `stream.Writable` class is extended to implement a [Writable](#stream_class_stream_writable) stream.
Custom Writable streams *must* call the `new stream.Writable([options])`
constructor and implement the `writable._write()` method. The
`writable._writev()` method *may* also be implemented.
#### Constructor: new stream.Writable([options])[#](#stream_constructor_new_stream_writable_options)
* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ `highWaterMark` [<number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Buffer level when
[`stream.write()`](#stream_writable_write_chunk_encoding_callback) starts returning `false`. Defaults to
`16384` (16kb), or `16` for `objectMode` streams.
+ `decodeStrings` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether or not to decode strings into
Buffers before passing them to [`stream._write()`](#stream_writable_write_chunk_encoding_callback_1).
Defaults to `true`
+ `objectMode` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether or not the
[`stream.write(anyObj)`](#stream_writable_write_chunk_encoding_callback) is a valid operation. When set,
it becomes possible to write JavaScript values other than string or
`Buffer` if supported by the stream implementation. Defaults to `false`
+ `write` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Implementation for the
[`stream._write()`](#stream_writable_write_chunk_encoding_callback_1) method.
+ `writev` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Implementation for the
[`stream._writev()`](#stream_writable_writev_chunks_callback) method.
For example:
```None
const Writable = require('stream').Writable;
class MyWritable extends Writable {
constructor(options) {
// Calls the stream.Writable() constructor
super(options);
}
}
```
Or, when using pre-ES6 style constructors:
```None
const Writable = require('stream').Writable;
const util = require('util');
function MyWritable(options) {
if (!(this instanceof MyWritable))
return new MyWritable(options);
Writable.call(this, options);
}
util.inherits(MyWritable, Writable);
```
Or, using the Simplified Constructor approach:
```None
const Writable = require('stream').Writable;
const myWritable = new Writable({
write(chunk, encoding, callback) {
// ...
},
writev(chunks, callback) {
// ...
}
});
```
#### writable.\_write(chunk, encoding, callback)[#](#stream_writable_write_chunk_encoding_callback_1)
* `chunk` [<Buffer>](buffer.html#buffer_class_buffer) | [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | <any> The chunk to be written. Will **always**
be a buffer unless the `decodeStrings` option was set to `false`
or the stream is operating in object mode.
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If the chunk is a string, then `encoding` is the
character encoding of that string. If chunk is a `Buffer`, or if the
stream is operating in object mode, `encoding` may be ignored.
* `callback` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error
argument) when processing is complete for the supplied chunk.
All Writable stream implementations must provide a
[`writable._write()`](#stream_writable_write_chunk_encoding_callback_1) method to send data to the underlying
resource.
*Note*: [Transform](#stream_class_stream_transform) streams provide their own implementation of the
[`writable._write()`](#stream_writable_write_chunk_encoding_callback_1).
*Note*: **This function MUST NOT be called by application code directly.** It
should be implemented by child classes, and called only by the internal Writable
class methods only.
The `callback` method must be called to signal either that the write completed
successfully or failed with an error. The first argument passed to the
`callback` must be the `Error` object if the call failed or `null` if the
write succeeded.
It is important to note that all calls to `writable.write()` that occur between
the time `writable._write()` is called and the `callback` is called will cause
the written data to be buffered. Once the `callback` is invoked, the stream will
emit a [`'drain'`](#stream_event_drain) event. If a stream implementation is capable of processing
multiple chunks of data at once, the `writable._writev()` method should be
implemented.
If the `decodeStrings` property is set in the constructor options, then
`chunk` may be a string rather than a Buffer, and `encoding` will
indicate the character encoding of the string. This is to support
implementations that have an optimized handling for certain string
data encodings. If the `decodeStrings` property is explicitly set to `false`,
the `encoding` argument can be safely ignored, and `chunk` will remain the same
object that is passed to `.write()`.
The `writable._write()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### writable.\_writev(chunks, callback)[#](#stream_writable_writev_chunks_callback)
* `chunks` [<Array>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) The chunks to be written. Each chunk has following
format: `{ chunk: ..., encoding: ... }`.
* `callback` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function (optionally with an error
argument) to be invoked when processing is complete for the supplied chunks.
*Note*: **This function MUST NOT be called by application code directly.** It
should be implemented by child classes, and called only by the internal Writable
class methods only.
The `writable._writev()` method may be implemented in addition to
`writable._write()` in stream implementations that are capable of processing
multiple chunks of data at once. If implemented, the method will be called with
all chunks of data currently buffered in the write queue.
The `writable._writev()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### Errors While Writing[#](#stream_errors_while_writing)
It is recommended that errors occurring during the processing of the
`writable._write()` and `writable._writev()` methods are reported by invoking
the callback and passing the error as the first argument. This will cause an
`'error'` event to be emitted by the Writable. Throwing an Error from within
`writable._write()` can result in unexpected and inconsistent behavior depending
on how the stream is being used. Using the callback ensures consistent and
predictable handling of errors.
```None
const Writable = require('stream').Writable;
const myWritable = new Writable({
write(chunk, encoding, callback) {
if (chunk.toString().indexOf('a') >= 0) {
callback(new Error('chunk is invalid'));
} else {
callback();
}
}
});
```
#### An Example Writable Stream[#](#stream_an_example_writable_stream)
The following illustrates a rather simplistic (and somewhat pointless) custom
Writable stream implementation. While this specific Writable stream instance
is not of any real particular usefulness, the example illustrates each of the
required elements of a custom [Writable](#stream_class_stream_writable) stream instance:
```None
const Writable = require('stream').Writable;
class MyWritable extends Writable {
constructor(options) {
super(options);
}
_write(chunk, encoding, callback) {
if (chunk.toString().indexOf('a') >= 0) {
callback(new Error('chunk is invalid'));
} else {
callback();
}
}
}
```
### Implementing a Readable Stream[#](#stream_implementing_a_readable_stream)
The `stream.Readable` class is extended to implement a [Readable](#stream_class_stream_readable) stream.
Custom Readable streams *must* call the `new stream.Readable([options])`
constructor and implement the `readable._read()` method.
#### new stream.Readable([options])[#](#stream_new_stream_readable_options)
* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ `highWaterMark` [<number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum number of bytes to store in
the internal buffer before ceasing to read from the underlying
resource. Defaults to `16384` (16kb), or `16` for `objectMode` streams
+ `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If specified, then buffers will be decoded to
strings using the specified encoding. Defaults to `null`
+ `objectMode` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether this stream should behave
as a stream of objects. Meaning that [`stream.read(n)`](#stream_readable_read_size) returns
a single value instead of a Buffer of size n. Defaults to `false`
+ `read` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Implementation for the [`stream._read()`](#stream_readable_read_size_1)
method.
For example:
```None
const Readable = require('stream').Readable;
class MyReadable extends Readable {
constructor(options) {
// Calls the stream.Readable(options) constructor
super(options);
}
}
```
Or, when using pre-ES6 style constructors:
```None
const Readable = require('stream').Readable;
const util = require('util');
function MyReadable(options) {
if (!(this instanceof MyReadable))
return new MyReadable(options);
Readable.call(this, options);
}
util.inherits(MyReadable, Readable);
```
Or, using the Simplified Constructor approach:
```None
const Readable = require('stream').Readable;
const myReadable = new Readable({
read(size) {
// ...
}
});
```
#### readable.\_read(size)[#](#stream_readable_read_size_1)
* `size` [<number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read asynchronously
*Note*: **This function MUST NOT be called by application code directly.** It
should be implemented by child classes, and called only by the internal Readable
class methods only.
All Readable stream implementations must provide an implementation of the
`readable._read()` method to fetch data from the underlying resource.
When `readable._read()` is called, if data is available from the resource, the
implementation should begin pushing that data into the read queue using the
[`this.push(dataChunk)`](#stream_readable_push_chunk_encoding) method. `_read()` should continue reading
from the resource and pushing data until `readable.push()` returns `false`. Only
when `_read()` is called again after it has stopped should it resume pushing
additional data onto the queue.
*Note*: Once the `readable._read()` method has been called, it will not be
called again until the [`readable.push()`](#stream_readable_push_chunk_encoding) method is called.
The `size` argument is advisory. For implementations where a "read" is a
single operation that returns data can use the `size` argument to determine how
much data to fetch. Other implementations may ignore this argument and simply
provide data whenever it becomes available. There is no need to "wait" until
`size` bytes are available before calling [`stream.push(chunk)`](#stream_readable_push_chunk_encoding).
The `readable._read()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### readable.push(chunk[, encoding])[#](#stream_readable_push_chunk_encoding)
* `chunk` [<Buffer>](buffer.html#buffer_class_buffer) | [<null>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | <any> Chunk of data to push into the read queue
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Encoding of String chunks. Must be a valid
Buffer encoding, such as `'utf8'` or `'ascii'`
* Returns [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if additional chunks of data may continued to be
pushed; `false` otherwise.
When `chunk` is not `null`, the `chunk` of data will be added to the
internal queue for users of the stream to consume. Passing `chunk` as `null`
signals the end of the stream (EOF), after which no more data can be written.
When the Readable is operating in paused mode, the data added with
`readable.push()` can be read out by calling the
[`readable.read()`](#stream_readable_read_size) method when the [`'readable'`](#stream_event_readable) event is
emitted.
When the Readable is operating in flowing mode, the data added with
`readable.push()` will be delivered by emitting a `'data'` event.
The `readable.push()` method is designed to be as flexible as possible. For
example, when wrapping a lower-level source that provides some form of
pause/resume mechanism, and a data callback, the low-level source can be wrapped
by the custom Readable instance as illustrated in the following example:
```None
// source is an object with readStop() and readStart() methods,
// and an `ondata` member that gets called when it has data, and
// an `onend` member that gets called when the data is over.
class SourceWrapper extends Readable {
constructor(options) {
super(options);
this._source = getLowlevelSourceObject();
// Every time there's data, push it into the internal buffer.
this._source.ondata = (chunk) => {
// if push() returns false, then stop reading from source
if (!this.push(chunk))
this._source.readStop();
};
// When the source ends, push the EOF-signaling `null` chunk
this._source.onend = () => {
this.push(null);
};
}
// _read will be called when the stream wants to pull more data in
// the advisory size argument is ignored in this case.
_read(size) {
this._source.readStart();
}
}
```
*Note*: The `readable.push()` method is intended be called only by Readable
Implementers, and only from within the `readable._read()` method.
#### Errors While Reading[#](#stream_errors_while_reading)
It is recommended that errors occurring during the processing of the
`readable._read()` method are emitted using the `'error'` event rather than
being thrown. Throwing an Error from within `readable._read()` can result in
unexpected and inconsistent behavior depending on whether the stream is
operating in flowing or paused mode. Using the `'error'` event ensures
consistent and predictable handling of errors.
```None
const Readable = require('stream').Readable;
const myReadable = new Readable({
read(size) {
if (checkSomeErrorCondition()) {
process.nextTick(() => this.emit('error', err));
return;
}
// do some work
}
});
```
#### An Example Counting Stream[#](#stream_an_example_counting_stream)
The following is a basic example of a Readable stream that emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.
```None
const Readable = require('stream').Readable;
class Counter extends Readable {
constructor(opt) {
super(opt);
this._max = 1000000;
this._index = 1;
}
_read() {
var i = this._index++;
if (i > this._max)
this.push(null);
else {
var str = '' + i;
var buf = Buffer.from(str, 'ascii');
this.push(buf);
}
}
}
```
### Implementing a Duplex Stream[#](#stream_implementing_a_duplex_stream)
A [Duplex](#stream_class_stream_duplex) stream is one that implements both [Readable](#stream_class_stream_readable) and [Writable](#stream_class_stream_writable),
such as a TCP socket connection.
Because JavaScript does not have support for multiple inheritance, the
`stream.Duplex` class is extended to implement a [Duplex](#stream_class_stream_duplex) stream (as opposed
to extending the `stream.Readable` *and* `stream.Writable` classes).
*Note*: The `stream.Duplex` class prototypically inherits from `stream.Readable`
and parasitically from `stream.Writable`, but `instanceof` will work properly
for both base classes due to overriding [`Symbol.hasInstance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance)
on `stream.Writable`.
Custom Duplex streams *must* call the `new stream.Duplex([options])`
constructor and implement *both* the `readable._read()` and
`writable._write()` methods.
#### new stream.Duplex(options)[#](#stream_new_stream_duplex_options)
* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Passed to both Writable and Readable
constructors. Also has the following fields:
+ `allowHalfOpen` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Defaults to `true`. If set to `false`, then
the stream will automatically end the readable side when the
writable side ends and vice versa.
+ `readableObjectMode` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Defaults to `false`. Sets `objectMode`
for readable side of the stream. Has no effect if `objectMode`
is `true`.
+ `writableObjectMode` [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Defaults to `false`. Sets `objectMode`
for writable side of the stream. Has no effect if `objectMode`
is `true`.
For example:
```None
const Duplex = require('stream').Duplex;
class MyDuplex extends Duplex {
constructor(options) {
super(options);
}
}
```
Or, when using pre-ES6 style constructors:
```None
const Duplex = require('stream').Duplex;
const util = require('util');
function MyDuplex(options) {
if (!(this instanceof MyDuplex))
return new MyDuplex(options);
Duplex.call(this, options);
}
util.inherits(MyDuplex, Duplex);
```
Or, using the Simplified Constructor approach:
```None
const Duplex = require('stream').Duplex;
const myDuplex = new Duplex({
read(size) {
// ...
},
write(chunk, encoding, callback) {
// ...
}
});
```
#### An Example Duplex Stream[#](#stream_an_example_duplex_stream)
The following illustrates a simple example of a Duplex stream that wraps a
hypothetical lower-level source object to which data can be written, and
from which data can be read, albeit using an API that is not compatible with
Node.js streams.
The following illustrates a simple example of a Duplex stream that buffers
incoming written data via the [Writable](#stream_class_stream_writable) interface that is read back out
via the [Readable](#stream_class_stream_readable) interface.
```None
const Duplex = require('stream').Duplex;
const kSource = Symbol('source');
class MyDuplex extends Duplex {
constructor(source, options) {
super(options);
this[kSource] = source;
}
_write(chunk, encoding, callback) {
// The underlying source only deals with strings
if (Buffer.isBuffer(chunk))
chunk = chunk.toString();
this[kSource].writeSomeData(chunk);
callback();
}
_read(size) {
this[kSource].fetchSomeData(size, (data, encoding) => {
this.push(Buffer.from(data, encoding));
});
}
}
```
The most important aspect of a Duplex stream is that the Readable and Writable
sides operate independently of one another despite co-existing within a single
object instance.
#### Object Mode Duplex Streams[#](#stream_object_mode_duplex_streams)
For Duplex streams, `objectMode` can be set exclusively for either the Readable
or Writable side using the `readableObjectMode` and `writableObjectMode` options
respectively.
In the following example, for instance, a new Transform stream (which is a
type of [Duplex](#stream_class_stream_duplex) stream) is created that has an object mode Writable side
that accepts JavaScript numbers that are converted to hexadecimal strings on
the Readable side.
```None
const Transform = require('stream').Transform;
// All Transform streams are also Duplex Streams
const myTransform = new Transform({
writableObjectMode: true,
transform(chunk, encoding, callback) {
// Coerce the chunk to a number if necessary
chunk |= 0;
// Transform the chunk into something else.
const data = chunk.toString(16);
// Push the data onto the readable queue.
callback(null, '0'.repeat(data.length % 2) + data);
}
});
myTransform.setEncoding('ascii');
myTransform.on('data', (chunk) => console.log(chunk));
myTransform.write(1);
// Prints: 01
myTransform.write(10);
// Prints: 0a
myTransform.write(100);
// Prints: 64
```
### Implementing a Transform Stream[#](#stream_implementing_a_transform_stream)
A [Transform](#stream_class_stream_transform) stream is a [Duplex](#stream_class_stream_duplex) stream where the output is computed
in some way from the input. Examples include [zlib](zlib.html) streams or [crypto](crypto.html)
streams that compress, encrypt, or decrypt data.
*Note*: There is no requirement that the output be the same size as the input,
the same number of chunks, or arrive at the same time. For example, a
Hash stream will only ever have a single chunk of output which is
provided when the input is ended. A `zlib` stream will produce output
that is either much smaller or much larger than its input.
The `stream.Transform` class is extended to implement a [Transform](#stream_class_stream_transform) stream.
The `stream.Transform` class prototypically inherits from `stream.Duplex` and
implements its own versions of the `writable._write()` and `readable._read()`
methods. Custom Transform implementations *must* implement the
[`transform._transform()`](#stream_transform_transform_chunk_encoding_callback) method and *may* also implement
the [`transform._flush()`](#stream_transform_flush_callback) method.
*Note*: Care must be taken when using Transform streams in that data written
to the stream can cause the Writable side of the stream to become paused if
the output on the Readable side is not consumed.
#### new stream.Transform([options])[#](#stream_new_stream_transform_options)
* `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Passed to both Writable and Readable
constructors. Also has the following fields:
+ `transform` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Implementation for the
[`stream._transform()`](#stream_transform_transform_chunk_encoding_callback) method.
+ `flush` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Implementation for the [`stream._flush()`](#stream_transform_flush_callback)
method.
For example:
```None
const Transform = require('stream').Transform;
class MyTransform extends Transform {
constructor(options) {
super(options);
}
}
```
Or, when using pre-ES6 style constructors:
```None
const Transform = require('stream').Transform;
const util = require('util');
function MyTransform(options) {
if (!(this instanceof MyTransform))
return new MyTransform(options);
Transform.call(this, options);
}
util.inherits(MyTransform, Transform);
```
Or, using the Simplified Constructor approach:
```None
const Transform = require('stream').Transform;
const myTransform = new Transform({
transform(chunk, encoding, callback) {
// ...
}
});
```
#### Events: 'finish' and 'end'[#](#stream_events_finish_and_end)
The [`'finish'`](#stream_event_finish) and [`'end'`](#stream_event_end) events are from the `stream.Writable`
and `stream.Readable` classes, respectively. The `'finish'` event is emitted
after [`stream.end()`](#stream_writable_end_chunk_encoding_callback) is called and all chunks have been processed
by [`stream._transform()`](#stream_transform_transform_chunk_encoding_callback). The `'end'` event is emitted
after all data has been output, which occurs after the callback in
[`transform._flush()`](#stream_transform_flush_callback) has been called.
#### transform.\_flush(callback)[#](#stream_transform_flush_callback)
* `callback` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function (optionally with an error
argument and data) to be called when remaining data has been flushed.
*Note*: **This function MUST NOT be called by application code directly.** It
should be implemented by child classes, and called only by the internal Readable
class methods only.
In some cases, a transform operation may need to emit an additional bit of
data at the end of the stream. For example, a `zlib` compression stream will
store an amount of internal state used to optimally compress the output. When
the stream ends, however, that additional data needs to be flushed so that the
compressed data will be complete.
Custom [Transform](#stream_class_stream_transform) implementations *may* implement the `transform._flush()`
method. This will be called when there is no more written data to be consumed,
but before the [`'end'`](#stream_event_end) event is emitted signaling the end of the
[Readable](#stream_class_stream_readable) stream.
Within the `transform._flush()` implementation, the `readable.push()` method
may be called zero or more times, as appropriate. The `callback` function must
be called when the flush operation is complete.
The `transform._flush()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### transform.\_transform(chunk, encoding, callback)[#](#stream_transform_transform_chunk_encoding_callback)
* `chunk` [<Buffer>](buffer.html#buffer_class_buffer) | [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | <any> The chunk to be transformed. Will **always**
be a buffer unless the `decodeStrings` option was set to `false`
or the stream is operating in object mode.
* `encoding` [<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If the chunk is a string, then this is the
encoding type. If chunk is a buffer, then this is the special
value - 'buffer', ignore it in this case.
* `callback` [<Function>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function (optionally with an error
argument and data) to be called after the supplied `chunk` has been
processed.
*Note*: **This function MUST NOT be called by application code directly.** It
should be implemented by child classes, and called only by the internal Readable
class methods only.
All Transform stream implementations must provide a `_transform()`
method to accept input and produce output. The `transform._transform()`
implementation handles the bytes being written, computes an output, then passes
that output off to the readable portion using the `readable.push()` method.
The `transform.push()` method may be called zero or more times to generate
output from a single input chunk, depending on how much is to be output
as a result of the chunk.
It is possible that no output is generated from any given chunk of input data.
The `callback` function must be called only when the current chunk is completely
consumed. The first argument passed to the `callback` must be an `Error` object
if an error occurred while processing the input or `null` otherwise. If a second
argument is passed to the `callback`, it will be forwarded on to the
`readable.push()` method. In other words the following are equivalent:
```None
transform.prototype._transform = function (data, encoding, callback) {
this.push(data);
callback();
};
transform.prototype._transform = function (data, encoding, callback) {
callback(null, data);
};
```
The `transform._transform()` method is prefixed with an underscore because it
is internal to the class that defines it, and should never be called directly by
user programs.
#### Class: stream.PassThrough[#](#stream_class_stream_passthrough)
The `stream.PassThrough` class is a trivial implementation of a [Transform](#stream_class_stream_transform)
stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases where
`stream.PassThrough` is useful as a building block for novel sorts of streams.
## Additional Notes[#](#stream_additional_notes)
### Compatibility with Older Node.js Versions[#](#stream_compatibility_with_older_node_js_versions)
In versions of Node.js prior to v0.10, the Readable stream interface was
simpler, but also less powerful and less useful.
* Rather than waiting for calls the [`stream.read()`](#stream_readable_read_size) method,
[`'data'`](#stream_event_data) events would begin emitting immediately. Applications that
would need to perform some amount of work to decide how to handle data
were required to store read data into buffers so the data would not be lost.
* The [`stream.pause()`](#stream_readable_pause) method was advisory, rather than
guaranteed. This meant that it was still necessary to be prepared to receive
[`'data'`](#stream_event_data) events *even when the stream was in a paused state*.
In Node.js v0.10, the [Readable](#stream_class_stream_readable) class was added. For backwards compatibility
with older Node.js programs, Readable streams switch into "flowing mode" when a
[`'data'`](#stream_event_data) event handler is added, or when the
[`stream.resume()`](#stream_readable_resume) method is called. The effect is that, even
when not using the new [`stream.read()`](#stream_readable_read_size) method and
[`'readable'`](#stream_event_readable) event, it is no longer necessary to worry about losing
[`'data'`](#stream_event_data) chunks.
While most applications will continue to function normally, this introduces an
edge case in the following conditions:
* No [`'data'`](#stream_event_data) event listener is added.
* The [`stream.resume()`](#stream_readable_resume) method is never called.
* The stream is not piped to any writable destination.
For example, consider the following code:
```None
// WARNING! BROKEN!
net.createServer((socket) => {
// we add an 'end' method, but never consume the data
socket.on('end', () => {
// It will never get here.
socket.end('The message was received but was not processed.\n');
});
}).listen(1337);
```
In versions of Node.js prior to v0.10, the incoming message data would be
simply discarded. However, in Node.js v0.10 and beyond, the socket remains
paused forever.
The workaround in this situation is to call the
[`stream.resume()`](#stream_readable_resume) method to begin the flow of data:
```None
// Workaround
net.createServer((socket) => {
socket.on('end', () => {
socket.end('The message was received but was not processed.\n');
});
// start the flow of data, discarding it.
socket.resume();
}).listen(1337);
```
In addition to new Readable streams switching into flowing mode,
pre-v0.10 style streams can be wrapped in a Readable class using the
[`readable.wrap()`](#stream_readable_wrap_stream) method.
### `readable.read(0)`[#](#stream_readable_read_0)
There are some cases where it is necessary to trigger a refresh of the
underlying readable stream mechanisms, without actually consuming any
data. In such cases, it is possible to call `readable.read(0)`, which will
always return `null`.
If the internal read buffer is below the `highWaterMark`, and the
stream is not currently reading, then calling `stream.read(0)` will trigger
a low-level [`stream._read()`](#stream_readable_read_size_1) call.
While most applications will almost never need to do this, there are
situations within Node.js where this is done, particularly in the
Readable stream class internals.
### `readable.push('')`[#](#stream_readable_push)
Use of `readable.push('')` is not recommended.
Pushing a zero-byte string or `Buffer` to a stream that is not in object mode
has an interesting side effect. Because it *is* a call to
[`readable.push()`](#stream_readable_push_chunk_encoding), the call will end the reading process.
However, because the argument is an empty string, no data is added to the
readable buffer so there is nothing for a user to consume.
|