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 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta name="nodejs.org:node-version" content="v22.14.0">
<title>Stream | Node.js v22.14.0 Documentation</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
<link rel="stylesheet" href="assets/style.css">
<link rel="stylesheet" href="assets/hljs.css">
<link rel="canonical" href="https://nodejs.org/api/stream.html">
<script async defer src="assets/api.js" type="text/javascript"></script>
<script>
const storedTheme = localStorage.getItem('theme');
// Follow operating system theme preference
if (storedTheme === null && window.matchMedia) {
const mq = window.matchMedia('(prefers-color-scheme: dark)');
if (mq.matches) {
document.documentElement.classList.add('dark-mode');
}
} else if (storedTheme === 'dark') {
document.documentElement.classList.add('dark-mode');
}
</script>
<style>@media(max-width:718px){.with-62-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:646px){.with-53-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:558px){.with-42-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-stream">
<a href="#apicontent" class="skip-to-content">Skip to content</a>
<div id="content" class="clearfix">
<div role="navigation" id="column2" class="interior">
<div id="intro" class="interior">
<a href="/" title="Go back to the home page">
Node.js
</a>
</div>
<ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li>
<li><a href="stream.html" class="nav-stream active">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul>
</div>
<div id="column1" data-id="stream" class="interior">
<header class="header">
<div class="header-container">
<h1>Node.js v22.14.0 documentation</h1>
<button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
<svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
<path fill="none" d="M0 0h24v24H0z" />
<path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
<path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
<path d="M0 0h24v24H0z" fill="none" />
<path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
</svg>
</button>
</div>
<div id="gtoc">
<ul>
<li class="pinned-header">Node.js v22.14.0</li>
<li class="picker-header">
<a href="#toc-picker" aria-controls="toc-picker">
<span class="picker-arrow"></span>
Table of contents
</a>
<div class="picker" tabindex="-1"><div class="toc"><ul id="toc-picker">
<li><span class="stability_2"><a href="#stream">Stream</a></span>
<ul>
<li><a href="#organization-of-this-document">Organization of this document</a></li>
<li><a href="#types-of-streams">Types of streams</a>
<ul>
<li><a href="#streams-promises-api">Streams Promises API</a></li>
<li><a href="#streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li>
<li><a href="#streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li>
<li><a href="#streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li>
<li><a href="#object-mode">Object mode</a></li>
<li><a href="#buffering">Buffering</a></li>
</ul>
</li>
<li><a href="#api-for-stream-consumers">API for stream consumers</a>
<ul>
<li><a href="#writable-streams">Writable streams</a>
<ul>
<li><a href="#class-streamwritable">Class: <code>stream.Writable</code></a>
<ul>
<li><a href="#event-close">Event: <code>'close'</code></a></li>
<li><a href="#event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#event-error">Event: <code>'error'</code></a></li>
<li><a href="#event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#event-pipe">Event: <code>'pipe'</code></a></li>
<li><a href="#event-unpipe">Event: <code>'unpipe'</code></a></li>
<li><a href="#writablecork"><code>writable.cork()</code></a></li>
<li><a href="#writabledestroyerror"><code>writable.destroy([error])</code></a></li>
<li><a href="#writableclosed"><code>writable.closed</code></a></li>
<li><a href="#writabledestroyed"><code>writable.destroyed</code></a></li>
<li><a href="#writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li>
<li><a href="#writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li>
<li><a href="#writableuncork"><code>writable.uncork()</code></a></li>
<li><a href="#writablewritable"><code>writable.writable</code></a></li>
<li><span class="stability_1"><a href="#writablewritableaborted"><code>writable.writableAborted</code></a></span></li>
<li><a href="#writablewritableended"><code>writable.writableEnded</code></a></li>
<li><a href="#writablewritablecorked"><code>writable.writableCorked</code></a></li>
<li><a href="#writableerrored"><code>writable.errored</code></a></li>
<li><a href="#writablewritablefinished"><code>writable.writableFinished</code></a></li>
<li><a href="#writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li>
<li><a href="#writablewritablelength"><code>writable.writableLength</code></a></li>
<li><a href="#writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li>
<li><a href="#writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li>
<li><span class="stability_1"><a href="#writablesymbolasyncdispose"><code>writable[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#readable-streams">Readable streams</a>
<ul>
<li><a href="#two-reading-modes">Two reading modes</a></li>
<li><a href="#three-states">Three states</a></li>
<li><a href="#choose-one-api-style">Choose one API style</a></li>
<li><a href="#class-streamreadable">Class: <code>stream.Readable</code></a>
<ul>
<li><a href="#event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#event-data">Event: <code>'data'</code></a></li>
<li><a href="#event-end">Event: <code>'end'</code></a></li>
<li><a href="#event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#event-pause">Event: <code>'pause'</code></a></li>
<li><a href="#event-readable">Event: <code>'readable'</code></a></li>
<li><a href="#event-resume">Event: <code>'resume'</code></a></li>
<li><a href="#readabledestroyerror"><code>readable.destroy([error])</code></a></li>
<li><a href="#readableclosed"><code>readable.closed</code></a></li>
<li><a href="#readabledestroyed"><code>readable.destroyed</code></a></li>
<li><a href="#readableispaused"><code>readable.isPaused()</code></a></li>
<li><a href="#readablepause"><code>readable.pause()</code></a></li>
<li><a href="#readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li>
<li><a href="#readablereadsize"><code>readable.read([size])</code></a></li>
<li><a href="#readablereadable"><code>readable.readable</code></a></li>
<li><span class="stability_1"><a href="#readablereadableaborted"><code>readable.readableAborted</code></a></span></li>
<li><span class="stability_1"><a href="#readablereadabledidread"><code>readable.readableDidRead</code></a></span></li>
<li><a href="#readablereadableencoding"><code>readable.readableEncoding</code></a></li>
<li><a href="#readablereadableended"><code>readable.readableEnded</code></a></li>
<li><a href="#readableerrored"><code>readable.errored</code></a></li>
<li><a href="#readablereadableflowing"><code>readable.readableFlowing</code></a></li>
<li><a href="#readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li>
<li><a href="#readablereadablelength"><code>readable.readableLength</code></a></li>
<li><a href="#readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li>
<li><a href="#readableresume"><code>readable.resume()</code></a></li>
<li><a href="#readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li>
<li><a href="#readableunpipedestination"><code>readable.unpipe([destination])</code></a></li>
<li><a href="#readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li>
<li><a href="#readablewrapstream"><code>readable.wrap(stream)</code></a></li>
<li><a href="#readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li>
<li><span class="stability_1"><a href="#readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li>
<li><span class="stability_1"><a href="#readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#duplex-and-transform-streams">Duplex and transform streams</a>
<ul>
<li><a href="#class-streamduplex">Class: <code>stream.Duplex</code></a>
<ul>
<li><a href="#duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li>
</ul>
</li>
<li><a href="#class-streamtransform">Class: <code>stream.Transform</code></a>
<ul>
<li><a href="#transformdestroyerror"><code>transform.destroy([error])</code></a></li>
</ul>
</li>
<li><a href="#streamduplexpairoptions"><code>stream.duplexPair([options])</code></a></li>
</ul>
</li>
<li><a href="#streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li>
<li><a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li>
<li><a href="#streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li>
<li><span class="stability_1"><a href="#streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li>
<li><a href="#streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li>
<li><span class="stability_1"><a href="#streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li>
<li><a href="#streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li>
<li><span class="stability_1"><a href="#streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li>
<li><a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li>
<li><a href="#streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li>
<li><a href="#streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li>
</ul>
</li>
<li><a href="#api-for-stream-implementers">API for stream implementers</a>
<ul>
<li><a href="#simplified-construction">Simplified construction</a></li>
<li><a href="#implementing-a-writable-stream">Implementing a writable stream</a>
<ul>
<li><a href="#new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li>
<li><a href="#writable_constructcallback"><code>writable._construct(callback)</code></a></li>
<li><a href="#writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li>
<li><a href="#writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li>
<li><a href="#writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li>
<li><a href="#writable_finalcallback"><code>writable._final(callback)</code></a></li>
<li><a href="#errors-while-writing">Errors while writing</a></li>
<li><a href="#an-example-writable-stream">An example writable stream</a></li>
<li><a href="#decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li>
</ul>
</li>
<li><a href="#implementing-a-readable-stream">Implementing a readable stream</a>
<ul>
<li><a href="#new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li>
<li><a href="#readable_constructcallback"><code>readable._construct(callback)</code></a></li>
<li><a href="#readable_readsize"><code>readable._read(size)</code></a></li>
<li><a href="#readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li>
<li><a href="#readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li>
<li><a href="#errors-while-reading">Errors while reading</a></li>
<li><a href="#an-example-counting-stream">An example counting stream</a></li>
</ul>
</li>
<li><a href="#implementing-a-duplex-stream">Implementing a duplex stream</a>
<ul>
<li><a href="#new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li>
<li><a href="#an-example-duplex-stream">An example duplex stream</a></li>
<li><a href="#object-mode-duplex-streams">Object mode duplex streams</a></li>
</ul>
</li>
<li><a href="#implementing-a-transform-stream">Implementing a transform stream</a>
<ul>
<li><a href="#new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li>
<li><a href="#event-end_1">Event: <code>'end'</code></a></li>
<li><a href="#event-finish_1">Event: <code>'finish'</code></a></li>
<li><a href="#transform_flushcallback"><code>transform._flush(callback)</code></a></li>
<li><a href="#transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li>
<li><a href="#class-streampassthrough">Class: <code>stream.PassThrough</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#additional-notes">Additional notes</a>
<ul>
<li><a href="#streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a>
<ul>
<li><a href="#consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li>
<li><a href="#creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li>
<li><a href="#piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li>
</ul>
</li>
<li><a href="#compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li>
<li><a href="#readableread0"><code>readable.read(0)</code></a></li>
<li><a href="#readablepush"><code>readable.push('')</code></a></li>
<li><a href="#highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li>
</ul>
</li>
</ul>
</li>
</ul></div></div>
</li>
<li class="picker-header">
<a href="#gtoc-picker" aria-controls="gtoc-picker">
<span class="picker-arrow"></span>
Index
</a>
<div class="picker" tabindex="-1" id="gtoc-picker"><ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
<li>
<a href="index.html">Index</a>
</li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li>
<li><a href="stream.html" class="nav-stream active">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul></div>
</li>
<li class="picker-header">
<a href="#alt-docs" aria-controls="alt-docs">
<span class="picker-arrow"></span>
Other versions
</a>
<div class="picker" tabindex="-1"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v23.x/api/stream.html">23.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v22.x/api/stream.html">22.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/stream.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/stream.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/stream.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/stream.html">18.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/stream.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/stream.html">16.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v15.x/api/stream.html">15.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v14.x/api/stream.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/stream.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/stream.html">12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v11.x/api/stream.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/stream.html">10.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v9.x/api/stream.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/stream.html">8.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/stream.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/stream.html">6.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/stream.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/stream.html">4.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/stream.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/stream.html">0.10.x</a></li></ol></div>
</li>
<li class="picker-header">
<a href="#options-picker" aria-controls="options-picker">
<span class="picker-arrow"></span>
Options
</a>
<div class="picker" tabindex="-1">
<ul id="options-picker">
<li>
<a href="all.html">View on single page</a>
</li>
<li>
<a href="stream.json">View as JSON</a>
</li>
<li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/stream.md">Edit on GitHub</a></li>
</ul>
</div>
</li>
</ul>
</div>
<hr>
</header>
<details role="navigation" id="toc" open><summary>Table of contents</summary><ul>
<li><span class="stability_2"><a href="#stream">Stream</a></span>
<ul>
<li><a href="#organization-of-this-document">Organization of this document</a></li>
<li><a href="#types-of-streams">Types of streams</a>
<ul>
<li><a href="#streams-promises-api">Streams Promises API</a></li>
<li><a href="#streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li>
<li><a href="#streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li>
<li><a href="#streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li>
<li><a href="#object-mode">Object mode</a></li>
<li><a href="#buffering">Buffering</a></li>
</ul>
</li>
<li><a href="#api-for-stream-consumers">API for stream consumers</a>
<ul>
<li><a href="#writable-streams">Writable streams</a>
<ul>
<li><a href="#class-streamwritable">Class: <code>stream.Writable</code></a>
<ul>
<li><a href="#event-close">Event: <code>'close'</code></a></li>
<li><a href="#event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#event-error">Event: <code>'error'</code></a></li>
<li><a href="#event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#event-pipe">Event: <code>'pipe'</code></a></li>
<li><a href="#event-unpipe">Event: <code>'unpipe'</code></a></li>
<li><a href="#writablecork"><code>writable.cork()</code></a></li>
<li><a href="#writabledestroyerror"><code>writable.destroy([error])</code></a></li>
<li><a href="#writableclosed"><code>writable.closed</code></a></li>
<li><a href="#writabledestroyed"><code>writable.destroyed</code></a></li>
<li><a href="#writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li>
<li><a href="#writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li>
<li><a href="#writableuncork"><code>writable.uncork()</code></a></li>
<li><a href="#writablewritable"><code>writable.writable</code></a></li>
<li><span class="stability_1"><a href="#writablewritableaborted"><code>writable.writableAborted</code></a></span></li>
<li><a href="#writablewritableended"><code>writable.writableEnded</code></a></li>
<li><a href="#writablewritablecorked"><code>writable.writableCorked</code></a></li>
<li><a href="#writableerrored"><code>writable.errored</code></a></li>
<li><a href="#writablewritablefinished"><code>writable.writableFinished</code></a></li>
<li><a href="#writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li>
<li><a href="#writablewritablelength"><code>writable.writableLength</code></a></li>
<li><a href="#writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li>
<li><a href="#writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li>
<li><span class="stability_1"><a href="#writablesymbolasyncdispose"><code>writable[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#readable-streams">Readable streams</a>
<ul>
<li><a href="#two-reading-modes">Two reading modes</a></li>
<li><a href="#three-states">Three states</a></li>
<li><a href="#choose-one-api-style">Choose one API style</a></li>
<li><a href="#class-streamreadable">Class: <code>stream.Readable</code></a>
<ul>
<li><a href="#event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#event-data">Event: <code>'data'</code></a></li>
<li><a href="#event-end">Event: <code>'end'</code></a></li>
<li><a href="#event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#event-pause">Event: <code>'pause'</code></a></li>
<li><a href="#event-readable">Event: <code>'readable'</code></a></li>
<li><a href="#event-resume">Event: <code>'resume'</code></a></li>
<li><a href="#readabledestroyerror"><code>readable.destroy([error])</code></a></li>
<li><a href="#readableclosed"><code>readable.closed</code></a></li>
<li><a href="#readabledestroyed"><code>readable.destroyed</code></a></li>
<li><a href="#readableispaused"><code>readable.isPaused()</code></a></li>
<li><a href="#readablepause"><code>readable.pause()</code></a></li>
<li><a href="#readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li>
<li><a href="#readablereadsize"><code>readable.read([size])</code></a></li>
<li><a href="#readablereadable"><code>readable.readable</code></a></li>
<li><span class="stability_1"><a href="#readablereadableaborted"><code>readable.readableAborted</code></a></span></li>
<li><span class="stability_1"><a href="#readablereadabledidread"><code>readable.readableDidRead</code></a></span></li>
<li><a href="#readablereadableencoding"><code>readable.readableEncoding</code></a></li>
<li><a href="#readablereadableended"><code>readable.readableEnded</code></a></li>
<li><a href="#readableerrored"><code>readable.errored</code></a></li>
<li><a href="#readablereadableflowing"><code>readable.readableFlowing</code></a></li>
<li><a href="#readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li>
<li><a href="#readablereadablelength"><code>readable.readableLength</code></a></li>
<li><a href="#readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li>
<li><a href="#readableresume"><code>readable.resume()</code></a></li>
<li><a href="#readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li>
<li><a href="#readableunpipedestination"><code>readable.unpipe([destination])</code></a></li>
<li><a href="#readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li>
<li><a href="#readablewrapstream"><code>readable.wrap(stream)</code></a></li>
<li><a href="#readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li>
<li><span class="stability_1"><a href="#readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li>
<li><span class="stability_1"><a href="#readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#duplex-and-transform-streams">Duplex and transform streams</a>
<ul>
<li><a href="#class-streamduplex">Class: <code>stream.Duplex</code></a>
<ul>
<li><a href="#duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li>
</ul>
</li>
<li><a href="#class-streamtransform">Class: <code>stream.Transform</code></a>
<ul>
<li><a href="#transformdestroyerror"><code>transform.destroy([error])</code></a></li>
</ul>
</li>
<li><a href="#streamduplexpairoptions"><code>stream.duplexPair([options])</code></a></li>
</ul>
</li>
<li><a href="#streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li>
<li><a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li>
<li><a href="#streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li>
<li><span class="stability_1"><a href="#streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li>
<li><a href="#streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li>
<li><span class="stability_1"><a href="#streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li>
<li><a href="#streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li>
<li><span class="stability_1"><a href="#streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li>
<li><a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li>
<li><a href="#streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li>
<li><a href="#streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li>
</ul>
</li>
<li><a href="#api-for-stream-implementers">API for stream implementers</a>
<ul>
<li><a href="#simplified-construction">Simplified construction</a></li>
<li><a href="#implementing-a-writable-stream">Implementing a writable stream</a>
<ul>
<li><a href="#new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li>
<li><a href="#writable_constructcallback"><code>writable._construct(callback)</code></a></li>
<li><a href="#writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li>
<li><a href="#writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li>
<li><a href="#writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li>
<li><a href="#writable_finalcallback"><code>writable._final(callback)</code></a></li>
<li><a href="#errors-while-writing">Errors while writing</a></li>
<li><a href="#an-example-writable-stream">An example writable stream</a></li>
<li><a href="#decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li>
</ul>
</li>
<li><a href="#implementing-a-readable-stream">Implementing a readable stream</a>
<ul>
<li><a href="#new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li>
<li><a href="#readable_constructcallback"><code>readable._construct(callback)</code></a></li>
<li><a href="#readable_readsize"><code>readable._read(size)</code></a></li>
<li><a href="#readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li>
<li><a href="#readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li>
<li><a href="#errors-while-reading">Errors while reading</a></li>
<li><a href="#an-example-counting-stream">An example counting stream</a></li>
</ul>
</li>
<li><a href="#implementing-a-duplex-stream">Implementing a duplex stream</a>
<ul>
<li><a href="#new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li>
<li><a href="#an-example-duplex-stream">An example duplex stream</a></li>
<li><a href="#object-mode-duplex-streams">Object mode duplex streams</a></li>
</ul>
</li>
<li><a href="#implementing-a-transform-stream">Implementing a transform stream</a>
<ul>
<li><a href="#new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li>
<li><a href="#event-end_1">Event: <code>'end'</code></a></li>
<li><a href="#event-finish_1">Event: <code>'finish'</code></a></li>
<li><a href="#transform_flushcallback"><code>transform._flush(callback)</code></a></li>
<li><a href="#transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li>
<li><a href="#class-streampassthrough">Class: <code>stream.PassThrough</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#additional-notes">Additional notes</a>
<ul>
<li><a href="#streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a>
<ul>
<li><a href="#consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li>
<li><a href="#creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li>
<li><a href="#piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li>
</ul>
</li>
<li><a href="#compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li>
<li><a href="#readableread0"><code>readable.read(0)</code></a></li>
<li><a href="#readablepush"><code>readable.push('')</code></a></li>
<li><a href="#highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li>
</ul>
</li>
</ul>
</li>
</ul></details>
<div role="main" id="apicontent">
<h2>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/5d2feb257bcee090e57900eb51720171a6aa92f3/lib/stream.js#L55">[src]</a><span><a class="mark" href="#stream" id="stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream"></a></h2>
<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v22.14.0/lib/stream.js">lib/stream.js</a></p>
<p>A stream is an abstract interface for working with streaming data in Node.js.
The <code>node:stream</code> module provides an API for implementing the stream interface.</p>
<p>There are many stream objects provided by Node.js. For instance, a
<a href="http.html#class-httpincomingmessage">request to an HTTP server</a> and <a href="process.html#processstdout"><code>process.stdout</code></a>
are both stream instances.</p>
<p>Streams can be readable, writable, or both. All streams are instances of
<a href="events.html#class-eventemitter"><code>EventEmitter</code></a>.</p>
<p>To access the <code>node:stream</code> module:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>node:stream</code> module is useful for creating new types of stream instances.
It is usually not necessary to use the <code>node:stream</code> module to consume streams.</p>
<section><h3>Organization of this document<span><a class="mark" href="#organization-of-this-document" id="organization-of-this-document">#</a></span><a aria-hidden="true" class="legacy" id="stream_organization_of_this_document"></a></h3>
<p>This document contains two primary sections and a third section for notes. The
first section explains how to use existing streams within an application. The
second section explains how to create new types of streams.</p>
</section><section><h3>Types of streams<span><a class="mark" href="#types-of-streams" id="types-of-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_types_of_streams"></a></h3>
<p>There are four fundamental stream types within Node.js:</p>
<ul>
<li><a href="#class-streamwritable"><code>Writable</code></a>: streams to which data can be written (for example,
<a href="fs.html#fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>).</li>
<li><a href="#class-streamreadable"><code>Readable</code></a>: streams from which data can be read (for example,
<a href="fs.html#fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>).</li>
<li><a href="#class-streamduplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example,
<a href="net.html#class-netsocket"><code>net.Socket</code></a>).</li>
<li><a href="#class-streamtransform"><code>Transform</code></a>: <code>Duplex</code> streams that can modify or transform the data as it
is written and read (for example, <a href="zlib.html#zlibcreatedeflateoptions"><code>zlib.createDeflate()</code></a>).</li>
</ul>
<p>Additionally, this module includes the utility functions
<a href="#streamduplexpairoptions"><code>stream.duplexPair()</code></a>,
<a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a>,
<a href="#streamfinishedstream-options-callback"><code>stream.finished()</code></a>
<a href="#streamreadablefromiterable-options"><code>stream.Readable.from()</code></a>, and
<a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal()</code></a>.</p>
<h4>Streams Promises API<span><a class="mark" href="#streams-promises-api" id="streams-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="stream_streams_promises_api"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>stream/promises</code> API provides an alternative set of asynchronous utility
functions for streams that return <code>Promise</code> objects rather than using
callbacks. The API is accessible via <code>require('node:stream/promises')</code>
or <code>require('node:stream').promises</code>.</p>
<h4><code>stream.pipeline(source[, ...transforms], destination[, options])</code><span><a class="mark" href="#streampipelinesource-transforms-destination-options" id="streampipelinesource-transforms-destination-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_source_transforms_destination_options"></a></h4>
<h4><code>stream.pipeline(streams[, options])</code><span><a class="mark" href="#streampipelinestreams-options" id="streampipelinestreams-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_streams_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0, v17.2.0, v16.14.0</td>
<td><p>Add the <code>end</code> option, which can be set to <code>false</code> to prevent automatically closing the destination stream when the source ends.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>streams</code> <a href="stream.html#stream" class="type"><Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li>
<li><code>source</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
</ul>
</li>
<li><code>...transforms</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
</ul>
</li>
<li><code>destination</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Pipeline options
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> End the destination stream when the source stream ends.
Transform streams are always ended, even if this value is <code>false</code>.
<strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills when the pipeline is complete.</li>
</ul>
<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
zlib.<span class="hljs-title function_">createGzip</span>(),
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}
<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
<span class="hljs-title function_">createGzip</span>(),
<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre>
<p>To use an <code>AbortSignal</code>, pass it inside an options object, as the last argument.
When the signal is aborted, <code>destroy</code> will be called on the underlying pipeline,
with an <code>AbortError</code>.</p>
<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
zlib.<span class="hljs-title function_">createGzip</span>(),
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
{ signal },
);
}
<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>); <span class="hljs-comment">// AbortError</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = ac;
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
<span class="hljs-title function_">createGzip</span>(),
<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
{ signal },
);
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); <span class="hljs-comment">// AbortError</span>
}</code><button class="copy-button">copy</button></pre>
<p>The <code>pipeline</code> API also supports async generators:</p>
<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>),
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) {
source.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); <span class="hljs-comment">// Work with strings rather than `Buffer`s.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal });
}
},
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}
<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>),
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) {
source.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); <span class="hljs-comment">// Work with strings rather than `Buffer`s.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal });
}
},
<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre>
<p>Remember to handle the <code>signal</code> argument passed into the async generator.
Especially in the case where the async generator is the source for the
pipeline (i.e. first argument) or the pipeline will never complete.</p>
<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal });
<span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>;
},
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}
<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal });
<span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>;
},
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>pipeline</code> API provides <a href="#streampipelinesource-transforms-destination-callback">callback version</a>:</p>
<h4><code>stream.finished(stream[, options])</code><span><a class="mark" href="#streamfinishedstream-options" id="streamfinishedstream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_finished_stream_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0, v18.14.0</td>
<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr>
<tr><td>v19.1.0, v18.13.0</td>
<td><p>The <code>cleanup</code> option was added.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a> A readable and/or writable
stream/webstream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li>
<li><code>cleanup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> If <code>true</code>, removes the listeners registered by
this function before the promise is fulfilled. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills when the stream is no
longer readable or writable.</li>
</ul>
<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>);
}
<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);
rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> rs = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>);
}
<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);
rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><button class="copy-button">copy</button></pre>
<p>The <code>finished</code> API also provides a <a href="#streamfinishedstream-options-callback">callback version</a>.</p>
<p><code>stream.finished()</code> leaves dangling event listeners (in particular
<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after the returned promise is
resolved or rejected. The reason for this is so that unexpected <code>'error'</code>
events (due to incorrect stream implementations) do not cause unexpected
crashes. If this is unwanted behavior then <code>options.cleanup</code> should be set to
<code>true</code>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs, { <span class="hljs-attr">cleanup</span>: <span class="hljs-literal">true</span> });</code> <button class="copy-button">copy</button></pre>
<h4>Object mode<span><a class="mark" href="#object-mode" id="object-mode">#</a></span><a aria-hidden="true" class="legacy" id="stream_object_mode"></a></h4>
<p>All streams created by Node.js APIs operate exclusively on strings, <a href="buffer.html#class-buffer" class="type"><Buffer></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> objects:</p>
<ul>
<li><code>Strings</code> and <code>Buffers</code> are the most common types used with streams.</li>
<li><code>TypedArray</code> and <code>DataView</code> lets you handle binary data with types like
<code>Int32Array</code> or <code>Uint8Array</code>. When you write a TypedArray or DataView to a
stream, Node.js processes
the raw bytes.</li>
</ul>
<p>It is possible, however, for stream
implementations to work with other types of JavaScript values (with the
exception of <code>null</code>, which serves a special purpose within streams).
Such streams are considered to operate in "object mode".</p>
<p>Stream instances are switched into object mode using the <code>objectMode</code> option
when the stream is created. Attempting to switch an existing stream into
object mode is not safe.</p>
<h4>Buffering<span><a class="mark" href="#buffering" id="buffering">#</a></span><a aria-hidden="true" class="legacy" id="stream_buffering"></a></h4>
<p>Both <a href="#class-streamwritable"><code>Writable</code></a> and <a href="#class-streamreadable"><code>Readable</code></a> streams will store data in an internal
buffer.</p>
<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option
passed into the stream's constructor. For normal streams, the <code>highWaterMark</code>
option specifies a <a href="#highwatermark-discrepancy-after-calling-readablesetencoding">total number of bytes</a>. For streams operating
in object mode, the <code>highWaterMark</code> specifies a total number of objects. For
streams operating on (but not decoding) strings, the <code>highWaterMark</code> specifies
a total number of UTF-16 code units.</p>
<p>Data is buffered in <code>Readable</code> streams when the implementation calls
<a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not
call <a href="#readablereadsize"><code>stream.read()</code></a>, the data will sit in the internal
queue until it is consumed.</p>
<p>Once the total size of the internal read buffer reaches the threshold specified
by <code>highWaterMark</code>, 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 <a href="#readable_readsize"><code>readable._read()</code></a> method that is
used to fill the read buffer).</p>
<p>Data is buffered in <code>Writable</code> streams when the
<a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the
total size of the internal write buffer is below the threshold set by
<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once
the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code>
will be returned.</p>
<p>A key goal of the <code>stream</code> API, particularly the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> 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.</p>
<p>The <code>highWaterMark</code> option is a threshold, not a limit: it dictates the amount
of data that a stream buffers before it stops asking for more data. It does not
enforce a strict memory limitation in general. Specific stream implementations
may choose to enforce stricter limits but doing so is optional.</p>
<p>Because <a href="#class-streamduplex"><code>Duplex</code></a> and <a href="#class-streamtransform"><code>Transform</code></a> streams are both <code>Readable</code> and
<code>Writable</code>, each maintains <em>two</em> 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,
<a href="net.html#class-netsocket"><code>net.Socket</code></a> instances are <a href="#class-streamduplex"><code>Duplex</code></a> streams whose <code>Readable</code> side allows
consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows
writing data <em>to</em> the socket. Because data may be written to the socket at a
faster or slower rate than data is received, each side should
operate (and buffer) independently of the other.</p>
<p>The mechanics of the internal buffering are an internal implementation detail
and may be changed at any time. However, for certain advanced implementations,
the internal buffers can be retrieved using <code>writable.writableBuffer</code> or
<code>readable.readableBuffer</code>. Use of these undocumented properties is discouraged.</p>
</section><section><h3>API for stream consumers<span><a class="mark" href="#api-for-stream-consumers" id="api-for-stream-consumers">#</a></span><a aria-hidden="true" class="legacy" id="stream_api_for_stream_consumers"></a></h3>
<p>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:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
<span class="hljs-comment">// `req` is an http.IncomingMessage, which is a readable stream.</span>
<span class="hljs-comment">// `res` is an http.ServerResponse, which is a writable stream.</span>
<span class="hljs-keyword">let</span> body = <span class="hljs-string">''</span>;
<span class="hljs-comment">// Get the data as utf8 strings.</span>
<span class="hljs-comment">// If an encoding is not set, Buffer objects will be received.</span>
req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Readable streams emit 'data' events once a listener is added.</span>
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
body += chunk;
});
<span class="hljs-comment">// The 'end' event indicates that the entire body has been received.</span>
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> data = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(body);
<span class="hljs-comment">// Write back something interesting to the user:</span>
res.<span class="hljs-title function_">write</span>(<span class="hljs-keyword">typeof</span> data);
res.<span class="hljs-title function_">end</span>();
} <span class="hljs-keyword">catch</span> (er) {
<span class="hljs-comment">// uh oh! bad json!</span>
res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">400</span>;
<span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`error: <span class="hljs-subst">${er.message}</span>`</span>);
}
});
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);
<span class="hljs-comment">// $ curl localhost:1337 -d "{}"</span>
<span class="hljs-comment">// object</span>
<span class="hljs-comment">// $ curl localhost:1337 -d "\"foo\""</span>
<span class="hljs-comment">// string</span>
<span class="hljs-comment">// $ curl localhost:1337 -d "not json"</span>
<span class="hljs-comment">// error: Unexpected token 'o', "not json" is not valid JSON</span></code> <button class="copy-button">copy</button></pre>
<p><a href="#class-streamwritable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as
<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p>
<p><a href="#class-streamreadable"><code>Readable</code></a> streams use the <a href="events.html#class-eventemitter"><code>EventEmitter</code></a> 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.</p>
<p>Both <a href="#class-streamwritable"><code>Writable</code></a> and <a href="#class-streamreadable"><code>Readable</code></a> streams use the <a href="events.html#class-eventemitter"><code>EventEmitter</code></a> API in
various ways to communicate the current state of the stream.</p>
<p><a href="#class-streamduplex"><code>Duplex</code></a> and <a href="#class-streamtransform"><code>Transform</code></a> streams are both <a href="#class-streamwritable"><code>Writable</code></a> and
<a href="#class-streamreadable"><code>Readable</code></a>.</p>
<p>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 <code>require('node:stream')</code>.</p>
<p>Developers wishing to implement new types of streams should refer to the
section <a href="#api-for-stream-implementers">API for stream implementers</a>.</p>
<h4>Writable streams<span><a class="mark" href="#writable-streams" id="writable-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_streams"></a></h4>
<p>Writable streams are an abstraction for a <em>destination</em> to which data is
written.</p>
<p>Examples of <a href="#class-streamwritable"><code>Writable</code></a> streams include:</p>
<ul>
<li><a href="http.html#class-httpclientrequest">HTTP requests, on the client</a></li>
<li><a href="http.html#class-httpserverresponse">HTTP responses, on the server</a></li>
<li><a href="fs.html#class-fswritestream">fs write streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="net.html#class-netsocket">TCP sockets</a></li>
<li><a href="child_process.html#subprocessstdin">child process stdin</a></li>
<li><a href="process.html#processstdout"><code>process.stdout</code></a>, <a href="process.html#processstderr"><code>process.stderr</code></a></li>
</ul>
<p>Some of these examples are actually <a href="#class-streamduplex"><code>Duplex</code></a> streams that implement the
<a href="#class-streamwritable"><code>Writable</code></a> interface.</p>
<p>All <a href="#class-streamwritable"><code>Writable</code></a> streams implement the interface defined by the
<code>stream.Writable</code> class.</p>
<p>While specific instances of <a href="#class-streamwritable"><code>Writable</code></a> streams may differ in various ways,
all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated
in the example below:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myStream = <span class="hljs-title function_">getWritableStreamSomehow</span>();
myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data'</span>);
myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some more data'</span>);
myStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'done writing data'</span>);</code> <button class="copy-button">copy</button></pre>
<h5>Class: <code>stream.Writable</code><span><a class="mark" href="#class-streamwritable" id="class-streamwritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<h6>Event: <code>'close'</code><span><a class="mark" href="#event-close" id="event-close">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_close"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'close'</code> 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.</p>
<p>A <a href="#class-streamwritable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is
created with the <code>emitClose</code> option.</p>
<h6>Event: <code>'drain'</code><span><a class="mark" href="#event-drain" id="event-drain">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_drain"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>If a call to <a href="#writablewritechunk-encoding-callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the
<code>'drain'</code> event will be emitted when it is appropriate to resume writing data
to the stream.</p>
<pre><code class="language-js"><span class="hljs-comment">// Write the data to the supplied writable stream one million times.</span>
<span class="hljs-comment">// Be attentive to back-pressure.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">writeOneMillionTimes</span>(<span class="hljs-params">writer, data, encoding, callback</span>) {
<span class="hljs-keyword">let</span> i = <span class="hljs-number">1000000</span>;
<span class="hljs-title function_">write</span>();
<span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">let</span> ok = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">do</span> {
i--;
<span class="hljs-keyword">if</span> (i === <span class="hljs-number">0</span>) {
<span class="hljs-comment">// Last time!</span>
writer.<span class="hljs-title function_">write</span>(data, encoding, callback);
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// See if we should continue, or wait.</span>
<span class="hljs-comment">// Don't pass the callback, because we're not done yet.</span>
ok = writer.<span class="hljs-title function_">write</span>(data, encoding);
}
} <span class="hljs-keyword">while</span> (i > <span class="hljs-number">0</span> && ok);
<span class="hljs-keyword">if</span> (i > <span class="hljs-number">0</span>) {
<span class="hljs-comment">// Had to stop early!</span>
<span class="hljs-comment">// Write some more once it drains.</span>
writer.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, write);
}
}
}</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'error'</code><span><a class="mark" href="#event-error" id="event-error">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_error"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted if an error occurred while writing or piping
data. The listener callback is passed a single <code>Error</code> argument when called.</p>
<p>The stream is closed when the <code>'error'</code> event is emitted unless the
<a href="#new-streamwritableoptions"><code>autoDestroy</code></a> option was set to <code>false</code> when creating the
stream.</p>
<p>After <code>'error'</code>, no further events other than <code>'close'</code> <em>should</em> be emitted
(including <code>'error'</code> events).</p>
<h6>Event: <code>'finish'</code><span><a class="mark" href="#event-finish" id="event-finish">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'finish'</code> event is emitted after the <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> method
has been called, and all data has been flushed to the underlying system.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; i++) {
writer.<span class="hljs-title function_">write</span>(<span class="hljs-string">`hello, #<span class="hljs-subst">${i}</span>!\n`</span>);
}
writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'finish'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All writes are now complete.'</span>);
});
writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'This is the end\n'</span>);</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'pipe'</code><span><a class="mark" href="#event-pipe" id="event-pipe">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_pipe"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> source stream that is piping to this writable</li>
</ul>
<p>The <code>'pipe'</code> event is emitted when the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method is called on
a readable stream, adding this writable to its set of destinations.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>();
<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>();
writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Something is piping into the writer.'</span>);
assert.<span class="hljs-title function_">equal</span>(src, reader);
});
reader.<span class="hljs-title function_">pipe</span>(writer);</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'unpipe'</code><span><a class="mark" href="#event-unpipe" id="event-unpipe">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_unpipe"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> The source stream that
<a href="#readableunpipedestination">unpiped</a> this writable</li>
</ul>
<p>The <code>'unpipe'</code> event is emitted when the <a href="#readableunpipedestination"><code>stream.unpipe()</code></a> method is called
on a <a href="#class-streamreadable"><code>Readable</code></a> stream, removing this <a href="#class-streamwritable"><code>Writable</code></a> from its set of
destinations.</p>
<p>This is also emitted in case this <a href="#class-streamwritable"><code>Writable</code></a> stream emits an error when a
<a href="#class-streamreadable"><code>Readable</code></a> stream pipes into it.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>();
<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>();
writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unpipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Something has stopped piping into the writer.'</span>);
assert.<span class="hljs-title function_">equal</span>(src, reader);
});
reader.<span class="hljs-title function_">pipe</span>(writer);
reader.<span class="hljs-title function_">unpipe</span>(writer);</code> <button class="copy-button">copy</button></pre>
<h6><code>writable.cork()</code><span><a class="mark" href="#writablecork" id="writablecork">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_cork"></a></h6>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>The <code>writable.cork()</code> method forces all written data to be buffered in memory.
The buffered data will be flushed when either the <a href="#writableuncork"><code>stream.uncork()</code></a> or
<a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> methods are called.</p>
<p>The primary intent of <code>writable.cork()</code> is to accommodate a situation in which
several small chunks are written to the stream in rapid succession. Instead of
immediately forwarding them to the underlying destination, <code>writable.cork()</code>
buffers all the chunks until <code>writable.uncork()</code> is called, which will pass them
all to <code>writable._writev()</code>, if present. This prevents a head-of-line blocking
situation where data is being buffered while waiting for the first small chunk
to be processed. However, use of <code>writable.cork()</code> without implementing
<code>writable._writev()</code> may have an adverse effect on throughput.</p>
<p>See also: <a href="#writableuncork"><code>writable.uncork()</code></a>, <a href="#writable_writevchunks-callback"><code>writable._writev()</code></a>.</p>
<h6><code>writable.destroy([error])</code><span><a class="mark" href="#writabledestroyerror" id="writabledestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroy_error"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Optional, an error to emit with <code>'error'</code> event.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code>
event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the writable
stream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in
an <code>ERR_STREAM_DESTROYED</code> error.
This is a destructive and immediate way to destroy a stream. Previous calls to
<code>write()</code> may not have drained, and may trigger an <code>ERR_STREAM_DESTROYED</code> error.
Use <code>end()</code> instead of destroy if data should flush before close, or wait for
the <code>'drain'</code> event before destroying the stream.</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();
<span class="hljs-keyword">const</span> fooErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'foo error'</span>);
myStream.<span class="hljs-title function_">destroy</span>(fooErr);
myStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">fooErr</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(fooErr.<span class="hljs-property">message</span>)); <span class="hljs-comment">// foo error</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();
myStream.<span class="hljs-title function_">destroy</span>();
myStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">wontHappen</span>(<span class="hljs-params"></span>) {});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();
myStream.<span class="hljs-title function_">destroy</span>();
myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error.<span class="hljs-property">code</span>));
<span class="hljs-comment">// ERR_STREAM_DESTROYED</span></code> <button class="copy-button">copy</button></pre>
<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no
further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>
<p>Implementors should not override this method,
but instead implement <a href="#writable_destroyerr-callback"><code>writable._destroy()</code></a>.</p>
<h6><code>writable.closed</code><span><a class="mark" href="#writableclosed" id="writableclosed">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_closed"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> after <code>'close'</code> has been emitted.</p>
<h6><code>writable.destroyed</code><span><a class="mark" href="#writabledestroyed" id="writabledestroyed">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroyed"></a></h6>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#writabledestroyerror"><code>writable.destroy()</code></a> has been called.</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myStream.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// false</span>
myStream.<span class="hljs-title function_">destroy</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myStream.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<h6><code>writable.end([chunk[, encoding]][, callback])</code><span><a class="mark" href="#writableendchunk-encoding-callback" id="writableendchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_end_chunk_encoding_callback"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>callback</code> is invoked before 'finish' or on error.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>callback</code> is invoked if 'finish' or 'error' is emitted.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For
streams not operating in object mode, <code>chunk</code> must be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, <a href="buffer.html#class-buffer" class="type"><Buffer></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a>. For object mode streams, <code>chunk</code> may be any
JavaScript value other than <code>null</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding if <code>chunk</code> is a string</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback for when the stream is finished.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Calling the <code>writable.end()</code> method signals that no more data will be written
to the <a href="#class-streamwritable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one
final additional chunk of data to be written immediately before closing the
stream.</p>
<p>Calling the <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> method after calling
<a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> will raise an error.</p>
<pre><code class="language-js"><span class="hljs-comment">// Write 'hello, ' and then end with 'world!'.</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> file = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.txt'</span>);
file.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello, '</span>);
file.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world!'</span>);
<span class="hljs-comment">// Writing more now is not allowed!</span></code> <button class="copy-button">copy</button></pre>
<h6><code>writable.setDefaultEncoding(encoding)</code><span><a class="mark" href="#writablesetdefaultencodingencoding" id="writablesetdefaultencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_setdefaultencoding_encoding"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.1.0</td>
<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The new default encoding</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a
<a href="#class-streamwritable"><code>Writable</code></a> stream.</p>
<h6><code>writable.uncork()</code><span><a class="mark" href="#writableuncork" id="writableuncork">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_uncork"></a></h6>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>The <code>writable.uncork()</code> method flushes all data buffered since
<a href="#writablecork"><code>stream.cork()</code></a> was called.</p>
<p>When using <a href="#writablecork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering
of writes to a stream, defer calls to <code>writable.uncork()</code> using
<code>process.nextTick()</code>. Doing so allows batching of all
<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>();
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>);
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> stream.<span class="hljs-title function_">uncork</span>());</code> <button class="copy-button">copy</button></pre>
<p>If the <a href="#writablecork"><code>writable.cork()</code></a> method is called multiple times on a stream, the
same number of calls to <code>writable.uncork()</code> must be called to flush the buffered
data.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>();
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>);
stream.<span class="hljs-title function_">cork</span>();
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
stream.<span class="hljs-title function_">uncork</span>();
<span class="hljs-comment">// The data will not be flushed until uncork() is called a second time.</span>
stream.<span class="hljs-title function_">uncork</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>See also: <a href="#writablecork"><code>writable.cork()</code></a>.</p>
<h6><code>writable.writable</code><span><a class="mark" href="#writablewritable" id="writablewritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writable"></a></h6>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> if it is safe to call <a href="#writablewritechunk-encoding-callback"><code>writable.write()</code></a>, which means
the stream has not been destroyed, errored, or ended.</p>
<h6><code>writable.writableAborted</code><span><a class="mark" href="#writablewritableaborted" id="writablewritableaborted">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableaborted"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns whether the stream was destroyed or errored before emitting <code>'finish'</code>.</p>
<h6><code>writable.writableEnded</code><span><a class="mark" href="#writablewritableended" id="writablewritableended">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableended"></a></h6>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#writableendchunk-encoding-callback"><code>writable.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h6><code>writable.writableCorked</code><span><a class="mark" href="#writablewritablecorked" id="writablewritablecorked">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablecorked"></a></h6>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Number of times <a href="#writableuncork"><code>writable.uncork()</code></a> needs to be
called in order to fully uncork the stream.</p>
<h6><code>writable.errored</code><span><a class="mark" href="#writableerrored" id="writableerrored">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_errored"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Returns error if the stream has been destroyed with an error.</p>
<h6><code>writable.writableFinished</code><span><a class="mark" href="#writablewritablefinished" id="writablewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablefinished"></a></h6>
<div class="api_metadata">
<span>Added in: v12.6.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is set to <code>true</code> immediately before the <a href="#event-finish"><code>'finish'</code></a> event is emitted.</p>
<h6><code>writable.writableHighWaterMark</code><span><a class="mark" href="#writablewritablehighwatermark" id="writablewritablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablehighwatermark"></a></h6>
<div class="api_metadata">
<span>Added in: v9.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Return the value of <code>highWaterMark</code> passed when creating this <code>Writable</code>.</p>
<h6><code>writable.writableLength</code><span><a class="mark" href="#writablewritablelength" id="writablewritablelength">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablelength"></a></h6>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>This property contains the number of bytes (or objects) in the queue
ready to be written. The value provides introspection data regarding
the status of the <code>highWaterMark</code>.</p>
<h6><code>writable.writableNeedDrain</code><span><a class="mark" href="#writablewritableneeddrain" id="writablewritableneeddrain">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableneeddrain"></a></h6>
<div class="api_metadata">
<span>Added in: v15.2.0, v14.17.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> if the stream's buffer has been full and stream will emit <code>'drain'</code>.</p>
<h6><code>writable.writableObjectMode</code><span><a class="mark" href="#writablewritableobjectmode" id="writablewritableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableobjectmode"></a></h6>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Getter for the property <code>objectMode</code> of a given <code>Writable</code> stream.</p>
<h6><code>writable[Symbol.asyncDispose]()</code><span><a class="mark" href="#writablesymbolasyncdispose" id="writablesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_symbol_asyncdispose"></a></h6>
<div class="api_metadata">
<span>Added in: v22.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#writabledestroyerror"><code>writable.destroy()</code></a> with an <code>AbortError</code> and returns
a promise that fulfills when the stream is finished.</p>
<h6><code>writable.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#writablewritechunk-encoding-callback" id="writablewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_write_chunk_encoding_callback"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Passing <code>null</code> as the <code>chunk</code> parameter will always be considered invalid now, even in object mode.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For
streams not operating in object mode, <code>chunk</code> must be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, <a href="buffer.html#class-buffer" class="type"><Buffer></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a>. For object mode streams, <code>chunk</code> may be any
JavaScript value other than <code>null</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The encoding, if <code>chunk</code> is a string. <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback for when this chunk of data is flushed.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>false</code> if the stream wishes for the calling code to
wait for the <code>'drain'</code> event to be emitted before continuing to write
additional data; otherwise <code>true</code>.</li>
</ul>
<p>The <code>writable.write()</code> method writes some data to the stream, and calls the
supplied <code>callback</code> once the data has been fully handled. If an error
occurs, the <code>callback</code> will be called with the error as its
first argument. The <code>callback</code> is called asynchronously and before <code>'error'</code> is
emitted.</p>
<p>The return value is <code>true</code> if the internal buffer is less than the
<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>.
If <code>false</code> is returned, further attempts to write data to the stream should
stop until the <a href="#event-drain"><code>'drain'</code></a> event is emitted.</p>
<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the <code>'drain'</code> event will be emitted.
Once <code>write()</code> returns false, do not write more chunks
until the <code>'drain'</code> event is emitted. While calling <code>write()</code> 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.</p>
<p>Writing data while the stream is not draining is particularly
problematic for a <a href="#class-streamtransform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused
by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler
is added.</p>
<p>If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a <a href="#class-streamreadable"><code>Readable</code></a> and use
<a href="#readablepipedestination-options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is
possible to respect backpressure and avoid memory issues using the
<a href="#event-drain"><code>'drain'</code></a> event:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params">data, cb</span>) {
<span class="hljs-keyword">if</span> (!stream.<span class="hljs-title function_">write</span>(data)) {
stream.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, cb);
} <span class="hljs-keyword">else</span> {
process.<span class="hljs-title function_">nextTick</span>(cb);
}
}
<span class="hljs-comment">// Wait for cb to be called before doing any other write.</span>
<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Write completed, do more writes now.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p>
<h4>Readable streams<span><a class="mark" href="#readable-streams" id="readable-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_streams"></a></h4>
<p>Readable streams are an abstraction for a <em>source</em> from which data is
consumed.</p>
<p>Examples of <code>Readable</code> streams include:</p>
<ul>
<li><a href="http.html#class-httpincomingmessage">HTTP responses, on the client</a></li>
<li><a href="http.html#class-httpincomingmessage">HTTP requests, on the server</a></li>
<li><a href="fs.html#class-fsreadstream">fs read streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="net.html#class-netsocket">TCP sockets</a></li>
<li><a href="child_process.html#subprocessstdout">child process stdout and stderr</a></li>
<li><a href="process.html#processstdin"><code>process.stdin</code></a></li>
</ul>
<p>All <a href="#class-streamreadable"><code>Readable</code></a> streams implement the interface defined by the
<code>stream.Readable</code> class.</p>
<h5>Two reading modes<span><a class="mark" href="#two-reading-modes" id="two-reading-modes">#</a></span><a aria-hidden="true" class="legacy" id="stream_two_reading_modes"></a></h5>
<p><code>Readable</code> streams effectively operate in one of two modes: flowing and
paused. These modes are separate from <a href="#object-mode">object mode</a>.
A <a href="#class-streamreadable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether
it is in flowing mode or paused mode.</p>
<ul>
<li>
<p>In flowing mode, data is read from the underlying system automatically
and provided to an application as quickly as possible using events via the
<a href="events.html#class-eventemitter"><code>EventEmitter</code></a> interface.</p>
</li>
<li>
<p>In paused mode, the <a href="#readablereadsize"><code>stream.read()</code></a> method must be called
explicitly to read chunks of data from the stream.</p>
</li>
</ul>
<p>All <a href="#class-streamreadable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing
mode in one of the following ways:</p>
<ul>
<li>Adding a <a href="#event-data"><code>'data'</code></a> event handler.</li>
<li>Calling the <a href="#readableresume"><code>stream.resume()</code></a> method.</li>
<li>Calling the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method to send the data to a <a href="#class-streamwritable"><code>Writable</code></a>.</li>
</ul>
<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p>
<ul>
<li>If there are no pipe destinations, by calling the
<a href="#readablepause"><code>stream.pause()</code></a> method.</li>
<li>If there are pipe destinations, by removing all pipe destinations.
Multiple pipe destinations may be removed by calling the
<a href="#readableunpipedestination"><code>stream.unpipe()</code></a> method.</li>
</ul>
<p>The important concept to remember is that a <code>Readable</code> 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 <code>Readable</code> will <em>attempt</em>
to stop generating the data.</p>
<p>For backward compatibility reasons, removing <a href="#event-data"><code>'data'</code></a> event handlers will
<strong>not</strong> automatically pause the stream. Also, if there are piped destinations,
then calling <a href="#readablepause"><code>stream.pause()</code></a> will not guarantee that the
stream will <em>remain</em> paused once those destinations drain and ask for more data.</p>
<p>If a <a href="#class-streamreadable"><code>Readable</code></a> 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 <code>readable.resume()</code> method is called without a listener
attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed
from the stream.</p>
<p>Adding a <a href="#event-readable"><code>'readable'</code></a> event handler automatically makes the stream
stop flowing, and the data has to be consumed via
<a href="#readablereadsize"><code>readable.read()</code></a>. If the <a href="#event-readable"><code>'readable'</code></a> event handler is
removed, then the stream will start flowing again if there is a
<a href="#event-data"><code>'data'</code></a> event handler.</p>
<h5>Three states<span><a class="mark" href="#three-states" id="three-states">#</a></span><a aria-hidden="true" class="legacy" id="stream_three_states"></a></h5>
<p>The "two modes" of operation for a <code>Readable</code> stream are a simplified
abstraction for the more complicated internal state management that is happening
within the <code>Readable</code> stream implementation.</p>
<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three
possible states:</p>
<ul>
<li><code>readable.readableFlowing === null</code></li>
<li><code>readable.readableFlowing === false</code></li>
<li><code>readable.readableFlowing === true</code></li>
</ul>
<p>When <code>readable.readableFlowing</code> is <code>null</code>, no mechanism for consuming the
stream's data is provided. Therefore, the stream will not generate data.
While in this state, attaching a listener for the <code>'data'</code> event, calling the
<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch
<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively
emitting events as data is generated.</p>
<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure
will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>,
temporarily halting the flowing of events but <em>not</em> halting the generation of
data. While in this state, attaching a listener for the <code>'data'</code> event
will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PassThrough</span>, <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> pass = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PassThrough</span>();
<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();
pass.<span class="hljs-title function_">pipe</span>(writable);
pass.<span class="hljs-title function_">unpipe</span>(writable);
<span class="hljs-comment">// readableFlowing is now false.</span>
pass.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>()); });
<span class="hljs-comment">// readableFlowing is still false.</span>
pass.<span class="hljs-title function_">write</span>(<span class="hljs-string">'ok'</span>); <span class="hljs-comment">// Will not emit 'data'.</span>
pass.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Must be called to make stream emit 'data'.</span>
<span class="hljs-comment">// readableFlowing is now true.</span></code> <button class="copy-button">copy</button></pre>
<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating
within the stream's internal buffer.</p>
<h5>Choose one API style<span><a class="mark" href="#choose-one-api-style" id="choose-one-api-style">#</a></span><a aria-hidden="true" class="legacy" id="stream_choose_one_api_style"></a></h5>
<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides
multiple methods of consuming stream data. In general, developers should choose
<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods
to consume data from a single stream. Specifically, using a combination
of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could
lead to unintuitive behavior.</p>
<h5>Class: <code>stream.Readable</code><span><a class="mark" href="#class-streamreadable" id="class-streamreadable">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<h6>Event: <code>'close'</code><span><a class="mark" href="#event-close_1" id="event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_close_1"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'close'</code> 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.</p>
<p>A <a href="#class-streamreadable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is
created with the <code>emitClose</code> option.</p>
<h6>Event: <code>'data'</code><span><a class="mark" href="#event-data" id="event-data">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_data"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or <code>Buffer</code>.
For streams that are in object mode, the chunk can be any JavaScript value
other than <code>null</code>.</li>
</ul>
<p>The <code>'data'</code> 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 <code>readable.pipe()</code>, <code>readable.resume()</code>, or by
attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will
also be emitted whenever the <code>readable.read()</code> method is called and a chunk of
data is available to be returned.</p>
<p>Attaching a <code>'data'</code> 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.</p>
<p>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
<code>readable.setEncoding()</code> method; otherwise the data will be passed as a
<code>Buffer</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'end'</code><span><a class="mark" href="#event-end" id="event-end">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from
the stream.</p>
<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely
consumed. This can be accomplished by switching the stream into flowing mode,
or by calling <a href="#readablereadsize"><code>stream.read()</code></a> repeatedly until all data has been
consumed.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
});
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'There will be no more data.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'error'</code><span><a class="mark" href="#event-error_1" id="event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_error_1"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> implementation at any time.
Typically, this may occur if the underlying stream is unable to generate data
due to an underlying internal failure, or when a stream implementation attempts
to push an invalid chunk of data.</p>
<p>The listener callback will be passed a single <code>Error</code> object.</p>
<h6>Event: <code>'pause'</code><span><a class="mark" href="#event-pause" id="event-pause">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_pause"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'pause'</code> event is emitted when <a href="#readablepause"><code>stream.pause()</code></a> is called
and <code>readableFlowing</code> is not <code>false</code>.</p>
<h6>Event: <code>'readable'</code><span><a class="mark" href="#event-readable" id="event-readable">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_readable"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'readable'</code> event is emitted when there is data available to be read from
the stream, up to the configured high water mark (<code>state.highWaterMark</code>). Effectively,
it indicates that the stream has new information within the buffer. If data is available
within this buffer, <a href="#readablereadsize"><code>stream.read()</code></a> can be called to retrieve that data.
Additionally, the <code>'readable'</code> event may also be emitted when the end of the stream has been
reached.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// There is some data to read now.</span>
<span class="hljs-keyword">let</span> data;
<span class="hljs-keyword">while</span> ((data = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">read</span>()) !== <span class="hljs-literal">null</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
}
});</code> <button class="copy-button">copy</button></pre>
<p>If the end of the stream has been reached, calling
<a href="#readablereadsize"><code>stream.read()</code></a> will return <code>null</code> and trigger the <code>'end'</code>
event. This is also true if there never was any data to be read. For instance,
in the following example, <code>foo.txt</code> is an empty file:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> rr = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'foo.txt'</span>);
rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`readable: <span class="hljs-subst">${rr.read()}</span>`</span>);
});
rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'end'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The output of running this script is:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node test.js</span>
readable: null
end</code> <button class="copy-button">copy</button></pre>
<p>In some cases, attaching a listener for the <code>'readable'</code> event will cause some
amount of data to be read into an internal buffer.</p>
<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to
understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might
result in increased throughput.</p>
<p>If both <code>'readable'</code> and <a href="#event-data"><code>'data'</code></a> are used at the same time, <code>'readable'</code>
takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted
only when <a href="#readablereadsize"><code>stream.read()</code></a> is called. The
<code>readableFlowing</code> property would become <code>false</code>.
If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream
will start flowing, i.e. <code>'data'</code>Â events will be emitted without calling
<code>.resume()</code>.</p>
<h6>Event: <code>'resume'</code><span><a class="mark" href="#event-resume" id="event-resume">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_resume"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'resume'</code> event is emitted when <a href="#readableresume"><code>stream.resume()</code></a> is
called and <code>readableFlowing</code> is not <code>true</code>.</p>
<h6><code>readable.destroy([error])</code><span><a class="mark" href="#readabledestroyerror" id="readabledestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroy_error"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Error which will be passed as payload in <code>'error'</code> event</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code>
event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the readable
stream will release any internal resources and subsequent calls to <code>push()</code>
will be ignored.</p>
<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no
further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>
<p>Implementors should not override this method, but instead implement
<a href="#readable_destroyerr-callback"><code>readable._destroy()</code></a>.</p>
<h6><code>readable.closed</code><span><a class="mark" href="#readableclosed" id="readableclosed">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_closed"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> after <code>'close'</code> has been emitted.</p>
<h6><code>readable.destroyed</code><span><a class="mark" href="#readabledestroyed" id="readabledestroyed">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroyed"></a></h6>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#readabledestroyerror"><code>readable.destroy()</code></a> has been called.</p>
<h6><code>readable.isPaused()</code><span><a class="mark" href="#readableispaused" id="readableispaused">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_ispaused"></a></h6>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The <code>readable.isPaused()</code> method returns the current operating state of the
<code>Readable</code>. This is used primarily by the mechanism that underlies the
<code>readable.pipe()</code> method. In most typical cases, there will be no reason to
use this method directly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> stream.<span class="hljs-title class_">Readable</span>();
readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span>
readable.<span class="hljs-title function_">pause</span>();
readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === true</span>
readable.<span class="hljs-title function_">resume</span>();
readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.pause()</code><span><a class="mark" href="#readablepause" id="readablepause">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_pause"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop
emitting <a href="#event-data"><code>'data'</code></a> events, switching out of flowing mode. Any data that
becomes available will remain in the internal buffer.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
readable.<span class="hljs-title function_">pause</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'There will be no additional data for 1 second.'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Now data will start flowing again.'</span>);
readable.<span class="hljs-title function_">resume</span>();
}, <span class="hljs-number">1000</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code>
event listener.</p>
<h6><code>readable.pipe(destination[, options])</code><span><a class="mark" href="#readablepipedestination-options" id="readablepipedestination-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_pipe_destination_options"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>destination</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> The destination for writing data</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Pipe options
<ul>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> End the writer when the reader ends. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if
it is a <a href="#class-streamduplex"><code>Duplex</code></a> or a <a href="#class-streamtransform"><code>Transform</code></a> stream</li>
</ul>
<p>The <code>readable.pipe()</code> method attaches a <a href="#class-streamwritable"><code>Writable</code></a> stream to the <code>readable</code>,
causing it to switch automatically into flowing mode and push all of its data
to the attached <a href="#class-streamwritable"><code>Writable</code></a>. The flow of data will be automatically managed
so that the destination <code>Writable</code> stream is not overwhelmed by a faster
<code>Readable</code> stream.</p>
<p>The following example pipes all of the data from the <code>readable</code> into a file
named <code>file.txt</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>);
<span class="hljs-comment">// All the data from readable goes into 'file.txt'.</span>
readable.<span class="hljs-title function_">pipe</span>(writable);</code> <button class="copy-button">copy</button></pre>
<p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code>
stream.</p>
<p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream
making it possible to set up chains of piped streams:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> r = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file.txt'</span>);
<span class="hljs-keyword">const</span> z = zlib.<span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> w = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt.gz'</span>);
r.<span class="hljs-title function_">pipe</span>(z).<span class="hljs-title function_">pipe</span>(w);</code> <button class="copy-button">copy</button></pre>
<p>By default, <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> is called on the destination <code>Writable</code>
stream when the source <code>Readable</code> stream emits <a href="#event-end"><code>'end'</code></a>, so that the
destination is no longer writable. To disable this default behavior, the <code>end</code>
option can be passed as <code>false</code>, causing the destination stream to remain open:</p>
<pre><code class="language-js">reader.<span class="hljs-title function_">pipe</span>(writer, { <span class="hljs-attr">end</span>: <span class="hljs-literal">false</span> });
reader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Goodbye\n'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>One important caveat is that if the <code>Readable</code> stream emits an error during
processing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an
error occurs, it will be necessary to <em>manually</em> close each stream in order
to prevent memory leaks.</p>
<p>The <a href="process.html#processstderr"><code>process.stderr</code></a> and <a href="process.html#processstdout"><code>process.stdout</code></a> <code>Writable</code> streams are never
closed until the Node.js process exits, regardless of the specified options.</p>
<h6><code>readable.read([size])</code><span><a class="mark" href="#readablereadsize" id="readablereadsize">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_size"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional argument to specify how much data to read.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
</ul>
<p>The <code>readable.read()</code> method reads data out of the internal buffer and
returns it. If no data is available to be read, <code>null</code> is returned. By default,
the data is returned as a <code>Buffer</code> object unless an encoding has been
specified using the <code>readable.setEncoding()</code> method or the stream is operating
in object mode.</p>
<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If
<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em>
the stream has ended, in which case all of the data remaining in the internal
buffer will be returned.</p>
<p>If the <code>size</code> argument is not specified, all of the data contained in the
internal buffer will be returned.</p>
<p>The <code>size</code> argument must be less than or equal to 1 GiB.</p>
<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams
operating in paused mode. In flowing mode, <code>readable.read()</code> is called
automatically until the internal buffer is fully drained.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
<span class="hljs-comment">// 'readable' may be triggered multiple times as data is buffered in</span>
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">let</span> chunk;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is readable (new data received in buffer)'</span>);
<span class="hljs-comment">// Use a loop to make sure we read all currently available data</span>
<span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Read <span class="hljs-subst">${chunk.length}</span> bytes of data...`</span>);
}
});
<span class="hljs-comment">// 'end' will be triggered once when there is no more data available</span>
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached end of stream.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Each call to <code>readable.read()</code> returns a chunk of data or <code>null</code>, signifying
that there's no more data to read at that moment. These chunks aren't automatically
concatenated. Because a single <code>read()</code> call does not return all the data, using
a while loop may be necessary to continuously read chunks until all data is retrieved.
When reading a large file, <code>.read()</code> might return <code>null</code> temporarily, indicating
that it has consumed all buffered content but there may be more data yet to be
buffered. In such cases, a new <code>'readable'</code> event is emitted once there's more
data in the buffer, and the <code>'end'</code> event signifies the end of data transmission.</p>
<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary
to collect chunks across multiple <code>'readable'</code> events:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> chunks = [];
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">let</span> chunk;
<span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) {
chunks.<span class="hljs-title function_">push</span>(chunk);
}
});
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> content = chunks.<span class="hljs-title function_">join</span>(<span class="hljs-string">''</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>A <code>Readable</code> stream in object mode will always return a single item from
a call to <a href="#readablereadsize"><code>readable.read(size)</code></a>, regardless of the value of the
<code>size</code> argument.</p>
<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will
also be emitted.</p>
<p>Calling <a href="#readablereadsize"><code>stream.read([size])</code></a> after the <a href="#event-end"><code>'end'</code></a> event has
been emitted will return <code>null</code>. No runtime error will be raised.</p>
<h6><code>readable.readable</code><span><a class="mark" href="#readablereadable" id="readablereadable">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readable"></a></h6>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Is <code>true</code> if it is safe to call <a href="#readablereadsize"><code>readable.read()</code></a>, which means
the stream has not been destroyed or emitted <code>'error'</code> or <code>'end'</code>.</p>
<h6><code>readable.readableAborted</code><span><a class="mark" href="#readablereadableaborted" id="readablereadableaborted">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableaborted"></a></h6>
<div class="api_metadata">
<span>Added in: v16.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns whether the stream was destroyed or errored before emitting <code>'end'</code>.</p>
<h6><code>readable.readableDidRead</code><span><a class="mark" href="#readablereadabledidread" id="readablereadabledidread">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readabledidread"></a></h6>
<div class="api_metadata">
<span>Added in: v16.7.0, v14.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns whether <code>'data'</code> has been emitted.</p>
<h6><code>readable.readableEncoding</code><span><a class="mark" href="#readablereadableencoding" id="readablereadableencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableencoding"></a></h6>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
<p>Getter for the property <code>encoding</code> of a given <code>Readable</code> stream. The <code>encoding</code>
property can be set using the <a href="#readablesetencodingencoding"><code>readable.setEncoding()</code></a> method.</p>
<h6><code>readable.readableEnded</code><span><a class="mark" href="#readablereadableended" id="readablereadableended">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableended"></a></h6>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Becomes <code>true</code> when <a href="#event-end"><code>'end'</code></a> event is emitted.</p>
<h6><code>readable.errored</code><span><a class="mark" href="#readableerrored" id="readableerrored">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_errored"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>Returns error if the stream has been destroyed with an error.</p>
<h6><code>readable.readableFlowing</code><span><a class="mark" href="#readablereadableflowing" id="readablereadableflowing">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableflowing"></a></h6>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>This property reflects the current state of a <code>Readable</code> stream as described
in the <a href="#three-states">Three states</a> section.</p>
<h6><code>readable.readableHighWaterMark</code><span><a class="mark" href="#readablereadablehighwatermark" id="readablereadablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readablehighwatermark"></a></h6>
<div class="api_metadata">
<span>Added in: v9.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Returns the value of <code>highWaterMark</code> passed when creating this <code>Readable</code>.</p>
<h6><code>readable.readableLength</code><span><a class="mark" href="#readablereadablelength" id="readablereadablelength">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readablelength"></a></h6>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>This property contains the number of bytes (or objects) in the queue
ready to be read. The value provides introspection data regarding
the status of the <code>highWaterMark</code>.</p>
<h6><code>readable.readableObjectMode</code><span><a class="mark" href="#readablereadableobjectmode" id="readablereadableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableobjectmode"></a></h6>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Getter for the property <code>objectMode</code> of a given <code>Readable</code> stream.</p>
<h6><code>readable.resume()</code><span><a class="mark" href="#readableresume" id="readableresume">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_resume"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>resume()</code> has no effect if there is a <code>'readable'</code> event listening.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to
resume emitting <a href="#event-data"><code>'data'</code></a> events, switching the stream into flowing mode.</p>
<p>The <code>readable.resume()</code> method can be used to fully consume the data from a
stream without actually processing any of that data:</p>
<pre><code class="language-js"><span class="hljs-title function_">getReadableStreamSomehow</span>()
.<span class="hljs-title function_">resume</span>()
.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached the end, but did not read anything.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code>
event listener.</p>
<h6><code>readable.setEncoding(encoding)</code><span><a class="mark" href="#readablesetencodingencoding" id="readablesetencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_setencoding_encoding"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding to use.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>The <code>readable.setEncoding()</code> method sets the character encoding for
data read from the <code>Readable</code> stream.</p>
<p>By default, no encoding is assigned and stream data will be returned as
<code>Buffer</code> objects. Setting an encoding causes the stream data
to be returned as strings of the specified encoding rather than as <code>Buffer</code>
objects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the
output data to be interpreted as UTF-8 data, and passed as strings. Calling
<code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal
string format.</p>
<p>The <code>Readable</code> stream will properly handle multi-byte characters delivered
through the stream that would otherwise become improperly decoded if simply
pulled from the stream as <code>Buffer</code> objects.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-keyword">typeof</span> chunk, <span class="hljs-string">'string'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got %d characters of string data:'</span>, chunk.<span class="hljs-property">length</span>);
});</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.unpipe([destination])</code><span><a class="mark" href="#readableunpipedestination" id="readableunpipedestination">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_unpipe_destination"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>destination</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached
using the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method.</p>
<p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p>
<p>If the <code>destination</code> is specified, but no pipe is set up for it, then
the method does nothing.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>);
<span class="hljs-comment">// All the data from readable goes into 'file.txt',</span>
<span class="hljs-comment">// but only for the first second.</span>
readable.<span class="hljs-title function_">pipe</span>(writable);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stop writing to file.txt.'</span>);
readable.<span class="hljs-title function_">unpipe</span>(writable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Manually close the file stream.'</span>);
writable.<span class="hljs-title function_">end</span>();
}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.unshift(chunk[, encoding])</code><span><a class="mark" href="#readableunshiftchunk-encoding" id="readableunshiftchunk-encoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_unshift_chunk_encoding"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v0.9.11</td>
<td><p><span>Added in: v0.9.11</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Chunk of data to unshift
onto the read queue. For streams not operating in object mode, <code>chunk</code> must
be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, <a href="buffer.html#class-buffer" class="type"><Buffer></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> or <code>null</code>.
For object mode streams, <code>chunk</code> may be any JavaScript value.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Encoding of string chunks. Must be a valid
<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li>
</ul>
<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the
same as <code>readable.push(null)</code>, after which no more data can be written. The EOF
signal is put at the end of the buffer and any buffered data will still be
flushed.</p>
<p>The <code>readable.unshift()</code> 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.</p>
<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href="#event-end"><code>'end'</code></a> event
has been emitted or a runtime error will be thrown.</p>
<p>Developers using <code>stream.unshift()</code> often should consider switching to
use of a <a href="#class-streamtransform"><code>Transform</code></a> stream instead. See the <a href="#api-for-stream-implementers">API for stream implementers</a>
section for more information.</p>
<pre><code class="language-js"><span class="hljs-comment">// Pull off a header delimited by \n\n.</span>
<span class="hljs-comment">// Use unshift() if we get too much.</span>
<span class="hljs-comment">// Call the callback with (error, header, stream).</span>
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">parseHeader</span>(<span class="hljs-params">stream, callback</span>) {
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, callback);
stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, onReadable);
<span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">let</span> header = <span class="hljs-string">''</span>;
<span class="hljs-keyword">function</span> <span class="hljs-title function_">onReadable</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">let</span> chunk;
<span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = stream.<span class="hljs-title function_">read</span>())) {
<span class="hljs-keyword">const</span> str = decoder.<span class="hljs-title function_">write</span>(chunk);
<span class="hljs-keyword">if</span> (str.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'\n\n'</span>)) {
<span class="hljs-comment">// Found the header boundary.</span>
<span class="hljs-keyword">const</span> split = str.<span class="hljs-title function_">split</span>(<span class="hljs-regexp">/\n\n/</span>);
header += split.<span class="hljs-title function_">shift</span>();
<span class="hljs-keyword">const</span> remaining = split.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\n\n'</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(remaining, <span class="hljs-string">'utf8'</span>);
stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'error'</span>, callback);
<span class="hljs-comment">// Remove the 'readable' listener before unshifting.</span>
stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'readable'</span>, onReadable);
<span class="hljs-keyword">if</span> (buf.<span class="hljs-property">length</span>)
stream.<span class="hljs-title function_">unshift</span>(buf);
<span class="hljs-comment">// Now the body of the message can be read from the stream.</span>
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, header, stream);
<span class="hljs-keyword">return</span>;
}
<span class="hljs-comment">// Still reading the header.</span>
header += str;
}
}
}</code> <button class="copy-button">copy</button></pre>
<p>Unlike <a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not
end the reading process by resetting the internal reading state of the stream.
This can cause unexpected results if <code>readable.unshift()</code> is called during a
read (i.e. from within a <a href="#readable_readsize"><code>stream._read()</code></a> implementation on a
custom stream). Following the call to <code>readable.unshift()</code> with an immediate
<a href="#readablepushchunk-encoding"><code>stream.push('')</code></a> will reset the reading state appropriately,
however it is best to simply avoid calling <code>readable.unshift()</code> while in the
process of performing a read.</p>
<h6><code>readable.wrap(stream)</code><span><a class="mark" href="#readablewrapstream" id="readablewrapstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_wrap_stream"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> An "old style" readable stream</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Prior to Node.js 0.10, streams did not implement the entire <code>node:stream</code>
module API as it is currently defined. (See <a href="#compatibility-with-older-nodejs-versions">Compatibility</a> for more
information.)</p>
<p>When using an older Node.js library that emits <a href="#event-data"><code>'data'</code></a> events and has a
<a href="#readablepause"><code>stream.pause()</code></a> method that is advisory only, the
<code>readable.wrap()</code> method can be used to create a <a href="#class-streamreadable"><code>Readable</code></a> stream that uses
the old stream as its data source.</p>
<p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been
provided as a convenience for interacting with older Node.js applications and
libraries.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">OldReader</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./old-api-module.js'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> oreader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">OldReader</span>();
<span class="hljs-keyword">const</span> myReader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>().<span class="hljs-title function_">wrap</span>(oreader);
myReader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
myReader.<span class="hljs-title function_">read</span>(); <span class="hljs-comment">// etc.</span>
});</code> <button class="copy-button">copy</button></pre>
<h6><code>readable[Symbol.asyncIterator]()</code><span><a class="mark" href="#readablesymbolasynciterator" id="readablesymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_symbol_asynciterator"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to fully consume the stream.</li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">print</span>(<span class="hljs-params">readable</span>) {
readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) {
data += chunk;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
}
<span class="hljs-title function_">print</span>(fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file'</span>)).<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code> <button class="copy-button">copy</button></pre>
<p>If the loop terminates with a <code>break</code>, <code>return</code>, or a <code>throw</code>, the stream will
be destroyed. In other terms, iterating over a stream will consume the stream
fully. The stream will be read in chunks of size equal to the <code>highWaterMark</code>
option. In the code example above, data will be in a single chunk if the file
has less then 64 KiB of data because no <code>highWaterMark</code> option is provided to
<a href="fs.html#fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>.</p>
<h6><code>readable[Symbol.asyncDispose]()</code><span><a class="mark" href="#readablesymbolasyncdispose" id="readablesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_symbol_asyncdispose"></a></h6>
<div class="api_metadata">
<span>Added in: v20.4.0, v18.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#readabledestroyerror"><code>readable.destroy()</code></a> with an <code>AbortError</code> and returns
a promise that fulfills when the stream is finished.</p>
<h6><code>readable.compose(stream[, options])</code><span><a class="mark" href="#readablecomposestream-options" id="readablecomposestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_compose_stream_options"></a></h6>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamduplex" class="type"><Duplex></a> a stream composed with the stream <code>stream</code>.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">splitToWords</span>(<span class="hljs-params">source</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">const</span> words = <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> word <span class="hljs-keyword">of</span> words) {
<span class="hljs-keyword">yield</span> word;
}
}
}
<span class="hljs-keyword">const</span> wordsStream = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-string">'this is'</span>, <span class="hljs-string">'compose as operator'</span>]).<span class="hljs-title function_">compose</span>(splitToWords);
<span class="hljs-keyword">const</span> words = <span class="hljs-keyword">await</span> wordsStream.<span class="hljs-title function_">toArray</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(words); <span class="hljs-comment">// prints ['this', 'is', 'compose', 'as', 'operator']</span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#streamcomposestreams"><code>stream.compose</code></a> for more information.</p>
<h6><code>readable.iterator([options])</code><span><a class="mark" href="#readableiteratoroptions" id="readableiteratoroptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_iterator_options"></a></h6>
<div class="api_metadata">
<span>Added in: v16.3.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>destroyOnReturn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When set to <code>false</code>, calling <code>return</code> on the
async iterator, or exiting a <code>for await...of</code> iteration using a <code>break</code>,
<code>return</code>, or <code>throw</code> will not destroy the stream. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to consume the stream.</li>
</ul>
<p>The iterator created by this method gives users the option to cancel the
destruction of the stream if the <code>for await...of</code> loop is exited by <code>return</code>,
<code>break</code>, or <code>throw</code>, or if the iterator should destroy the stream if the stream
emitted an error during iteration.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">printIterator</span>(<span class="hljs-params">readable</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable.<span class="hljs-title function_">iterator</span>({ <span class="hljs-attr">destroyOnReturn</span>: <span class="hljs-literal">false</span> })) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span>
<span class="hljs-keyword">break</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// false</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable.<span class="hljs-title function_">iterator</span>({ <span class="hljs-attr">destroyOnReturn</span>: <span class="hljs-literal">false</span> })) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Will print 2 and then 3</span>
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// True, stream was totally consumed</span>
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">printSymbolAsyncIterator</span>(<span class="hljs-params">readable</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span>
<span class="hljs-keyword">break</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// true</span>
}
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">showBoth</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">printIterator</span>(<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]));
<span class="hljs-keyword">await</span> <span class="hljs-title function_">printSymbolAsyncIterator</span>(<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]));
}
<span class="hljs-title function_">showBoth</span>();</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.map(fn[, options])</code><span><a class="mark" href="#readablemapfn-options" id="readablemapfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_map_fn_options"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.7.0, v18.19.0</td>
<td><p>added <code>highWaterMark</code> in options.</p></td></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p><span>Added in: v17.4.0, v16.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to map over every chunk in the
stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> how many items to buffer while waiting for user
consumption of the mapped items. <strong>Default:</strong> <code>concurrency * 2 - 1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream mapped with the function <code>fn</code>.</li>
</ul>
<p>This method allows mapping over the stream. The <code>fn</code> function will be called
for every chunk in the stream. If the <code>fn</code> function returns a promise - that
promise will be <code>await</code>ed before being passed to the result stream.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-comment">// With a synchronous mapper.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x * <span class="hljs-number">2</span>)) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 2, 4, 6, 8</span>
}
<span class="hljs-comment">// With an asynchronous mapper, making at most 2 queries at a time.</span>
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'nodejs.org'</span>,
<span class="hljs-string">'openjsf.org'</span>,
<span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">domain</span>) =></span> resolver.<span class="hljs-title function_">resolve4</span>(domain), { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> dnsResults) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); <span class="hljs-comment">// Logs the DNS result of resolver.resolve4.</span>
}</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.filter(fn[, options])</code><span><a class="mark" href="#readablefilterfn-options" id="readablefilterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_filter_fn_options"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.7.0, v18.19.0</td>
<td><p>added <code>highWaterMark</code> in options.</p></td></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p><span>Added in: v17.4.0, v16.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to filter chunks from the stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> how many items to buffer while waiting for user
consumption of the filtered items. <strong>Default:</strong> <code>concurrency * 2 - 1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream filtered with the predicate <code>fn</code>.</li>
</ul>
<p>This method allows filtering the stream. For each chunk in the stream the <code>fn</code>
function will be called and if it returns a truthy value, the chunk will be
passed to the result stream. If the <code>fn</code> function returns a promise - that
promise will be <code>await</code>ed.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>)) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span>
}
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span>
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'nodejs.org'</span>,
<span class="hljs-string">'openjsf.org'</span>,
<span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">filter</span>(<span class="hljs-title function_">async</span> (domain) => {
<span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">return</span> address.<span class="hljs-property">ttl</span> > <span class="hljs-number">60</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> dnsResults) {
<span class="hljs-comment">// Logs domains with more than 60 seconds on the resolved dns record.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
}</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.forEach(fn[, options])</code><span><a class="mark" href="#readableforeachfn-options" id="readableforeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_foreach_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise for when the stream has finished.</li>
</ul>
<p>This method allows iterating a stream. For each chunk in the stream the
<code>fn</code> function will be called. If the <code>fn</code> function returns a promise - that
promise will be <code>await</code>ed.</p>
<p>This method is different from <code>for await...of</code> loops in that it can optionally
process chunks concurrently. In addition, a <code>forEach</code> iteration can only be
stopped by having passed a <code>signal</code> option and aborting the related
<code>AbortController</code> while <code>for await...of</code> can be stopped with <code>break</code> or
<code>return</code>. In either case the stream will be destroyed.</p>
<p>This method is different from listening to the <a href="#event-data"><code>'data'</code></a> event in that it
uses the <a href="#class-streamreadable"><code>readable</code></a> event in the underlying machinery and can limit the
number of concurrent <code>fn</code> calls.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>)) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span>
}
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span>
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'nodejs.org'</span>,
<span class="hljs-string">'openjsf.org'</span>,
<span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">map</span>(<span class="hljs-title function_">async</span> (domain) => {
<span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">return</span> address;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-keyword">await</span> dnsResults.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
<span class="hljs-comment">// Logs result, similar to `for await (const result of dnsResults)`</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.toArray([options])</code><span><a class="mark" href="#readabletoarrayoptions" id="readabletoarrayoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_toarray_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows cancelling the toArray operation if the
signal is aborted.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise containing an array with the contents of the
stream.</li>
</ul>
<p>This method allows easily obtaining the contents of a stream.</p>
<p>As this method reads the entire stream into memory, it negates the benefits of
streams. It's intended for interoperability and convenience, not as the primary
way to consume streams.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [1, 2, 3, 4]</span>
<span class="hljs-comment">// Make dns queries concurrently using .map and collect</span>
<span class="hljs-comment">// the results into an array using toArray</span>
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'nodejs.org'</span>,
<span class="hljs-string">'openjsf.org'</span>,
<span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">map</span>(<span class="hljs-title function_">async</span> (domain) => {
<span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">return</span> address;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }).<span class="hljs-title function_">toArray</span>();</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.some(fn[, options])</code><span><a class="mark" href="#readablesomefn-options" id="readablesomefn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_some_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise evaluating to <code>true</code> if <code>fn</code> returned a truthy
value for at least one of the chunks.</li>
</ul>
<p>This method is similar to <code>Array.prototype.some</code> and calls <code>fn</code> on each chunk
in the stream until the awaited return value is <code>true</code> (or any truthy value).
Once an <code>fn</code> call on a chunk awaited return value is truthy, the stream is
destroyed and the promise is fulfilled with <code>true</code>. If none of the <code>fn</code>
calls on the chunks return a truthy value, the promise is fulfilled with
<code>false</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">some</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// true</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">some</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x < <span class="hljs-number">0</span>); <span class="hljs-comment">// false</span>
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span>
<span class="hljs-keyword">const</span> anyBigFile = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'file1'</span>,
<span class="hljs-string">'file2'</span>,
<span class="hljs-string">'file3'</span>,
]).<span class="hljs-title function_">some</span>(<span class="hljs-title function_">async</span> (fileName) => {
<span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName);
<span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(anyBigFile); <span class="hljs-comment">// `true` if any file in the list is bigger than 1MB</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.find(fn[, options])</code><span><a class="mark" href="#readablefindfn-options" id="readablefindfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_find_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise evaluating to the first chunk for which <code>fn</code>
evaluated with a truthy value, or <code>undefined</code> if no element was found.</li>
</ul>
<p>This method is similar to <code>Array.prototype.find</code> and calls <code>fn</code> on each chunk
in the stream to find a chunk with a truthy value for <code>fn</code>. Once an <code>fn</code> call's
awaited return value is truthy, the stream is destroyed and the promise is
fulfilled with value for which <code>fn</code> returned a truthy value. If all of the
<code>fn</code> calls on the chunks return a falsy value, the promise is fulfilled with
<code>undefined</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">0</span>); <span class="hljs-comment">// 1</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">10</span>); <span class="hljs-comment">// undefined</span>
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span>
<span class="hljs-keyword">const</span> foundBigFile = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'file1'</span>,
<span class="hljs-string">'file2'</span>,
<span class="hljs-string">'file3'</span>,
]).<span class="hljs-title function_">find</span>(<span class="hljs-title function_">async</span> (fileName) => {
<span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName);
<span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(foundBigFile); <span class="hljs-comment">// File name of large file, if any file in the list is bigger than 1MB</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.every(fn[, options])</code><span><a class="mark" href="#readableeveryfn-options" id="readableeveryfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_every_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise evaluating to <code>true</code> if <code>fn</code> returned a truthy
value for all of the chunks.</li>
</ul>
<p>This method is similar to <code>Array.prototype.every</code> and calls <code>fn</code> on each chunk
in the stream to check if all awaited return values are truthy value for <code>fn</code>.
Once an <code>fn</code> call on a chunk awaited return value is falsy, the stream is
destroyed and the promise is fulfilled with <code>false</code>. If all of the <code>fn</code> calls
on the chunks return a truthy value, the promise is fulfilled with <code>true</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// false</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">0</span>); <span class="hljs-comment">// true</span>
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span>
<span class="hljs-keyword">const</span> allBigFiles = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'file1'</span>,
<span class="hljs-string">'file2'</span>,
<span class="hljs-string">'file3'</span>,
]).<span class="hljs-title function_">every</span>(<span class="hljs-title function_">async</span> (fileName) => {
<span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName);
<span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-comment">// `true` if all files in the list are bigger than 1MiB</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(allBigFiles);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.flatMap(fn[, options])</code><span><a class="mark" href="#readableflatmapfn-options" id="readableflatmapfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_flatmap_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor" class="type"><AsyncGeneratorFunction></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to map over
every chunk in the stream.
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream flat-mapped with the function <code>fn</code>.</li>
</ul>
<p>This method returns a new stream by applying the given callback to each
chunk of the stream and then flattening the result.</p>
<p>It is possible to return a stream or another iterable or async iterable from
<code>fn</code> and the result streams will be merged (flattened) into the returned
stream.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// With a synchronous mapper.</span>
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">flatMap</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> [x, x])) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1, 1, 2, 2, 3, 3, 4, 4</span>
}
<span class="hljs-comment">// With an asynchronous mapper, combine the contents of 4 files</span>
<span class="hljs-keyword">const</span> concatResult = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-string">'./1.mjs'</span>,
<span class="hljs-string">'./2.mjs'</span>,
<span class="hljs-string">'./3.mjs'</span>,
<span class="hljs-string">'./4.mjs'</span>,
]).<span class="hljs-title function_">flatMap</span>(<span class="hljs-function">(<span class="hljs-params">fileName</span>) =></span> <span class="hljs-title function_">createReadStream</span>(fileName));
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> concatResult) {
<span class="hljs-comment">// This will contain the contents (all chunks) of all 4 files</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
}</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.drop(limit[, options])</code><span><a class="mark" href="#readabledroplimit-options" id="readabledroplimit-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_drop_limit_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the number of chunks to drop from the readable.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream with <code>limit</code> chunks dropped.</li>
</ul>
<p>This method returns a new stream with the first <code>limit</code> chunks dropped.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">drop</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [3, 4]</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.take(limit[, options])</code><span><a class="mark" href="#readabletakelimit-options" id="readabletakelimit-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_take_limit_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the number of chunks to take from the readable.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream with <code>limit</code> chunks taken.</li>
</ul>
<p>This method returns a new stream with the first <code>limit</code> chunks.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">take</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [1, 2]</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.reduce(fn[, initial[, options]])</code><span><a class="mark" href="#readablereducefn-initial-options" id="readablereducefn-initial-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_reduce_fn_initial_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a reducer function to call over every chunk
in the stream.
<ul>
<li><code>previous</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the value obtained from the last call to <code>fn</code> or the
<code>initial</code> value if specified or the first chunk of the stream otherwise.</li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>initial</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the initial value to use in the reduction.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise for the final value of the reduction.</li>
</ul>
<p>This method calls <code>fn</code> on each chunk of the stream in order, passing it the
result from the calculation on the previous element. It returns a promise for
the final value of the reduction.</p>
<p>If no <code>initial</code> value is supplied the first chunk of the stream is used as the
initial value. If the stream is empty, the promise is rejected with a
<code>TypeError</code> with the <code>ERR_INVALID_ARGS</code> code property.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>;
<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath);
<span class="hljs-keyword">const</span> folderSize = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(filesInDir)
.<span class="hljs-title function_">reduce</span>(<span class="hljs-title function_">async</span> (totalSize, file) => {
<span class="hljs-keyword">const</span> { size } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(<span class="hljs-title function_">join</span>(directoryPath, file));
<span class="hljs-keyword">return</span> totalSize + size;
}, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre>
<p>The reducer function iterates the stream element-by-element which means that
there is no <code>concurrency</code> parameter or parallelism. To perform a <code>reduce</code>
concurrently, you can extract the async function to <a href="#readablemapfn-options"><code>readable.map</code></a> method.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>;
<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath);
<span class="hljs-keyword">const</span> folderSize = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(filesInDir)
.<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">file</span>) =></span> <span class="hljs-title function_">stat</span>(<span class="hljs-title function_">join</span>(directoryPath, file)), { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> })
.<span class="hljs-title function_">reduce</span>(<span class="hljs-function">(<span class="hljs-params">totalSize, { size }</span>) =></span> totalSize + size, <span class="hljs-number">0</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre>
<h4>Duplex and transform streams<span><a class="mark" href="#duplex-and-transform-streams" id="duplex-and-transform-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_duplex_and_transform_streams"></a></h4>
<h5>Class: <code>stream.Duplex</code><span><a class="mark" href="#class-streamduplex" id="class-streamduplex">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_duplex"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.8.0</td>
<td><p>Instances of <code>Duplex</code> now return <code>true</code> when checking <code>instanceof stream.Writable</code>.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Duplex streams are streams that implement both the <a href="#class-streamreadable"><code>Readable</code></a> and
<a href="#class-streamwritable"><code>Writable</code></a> interfaces.</p>
<p>Examples of <code>Duplex</code> streams include:</p>
<ul>
<li><a href="net.html#class-netsocket">TCP sockets</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h6><code>duplex.allowHalfOpen</code><span><a class="mark" href="#duplexallowhalfopen" id="duplexallowhalfopen">#</a></span><a aria-hidden="true" class="legacy" id="stream_duplex_allowhalfopen"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>If <code>false</code> then the stream will automatically end the writable side when the
readable side ends. Set initially by the <code>allowHalfOpen</code> constructor option,
which defaults to <code>true</code>.</p>
<p>This can be changed manually to change the half-open behavior of an existing
<code>Duplex</code> stream instance, but must be changed before the <code>'end'</code> event is
emitted.</p>
<h5>Class: <code>stream.Transform</code><span><a class="mark" href="#class-streamtransform" id="class-streamtransform">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_transform"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>Transform streams are <a href="#class-streamduplex"><code>Duplex</code></a> streams where the output is in some way
related to the input. Like all <a href="#class-streamduplex"><code>Duplex</code></a> streams, <code>Transform</code> streams
implement both the <a href="#class-streamreadable"><code>Readable</code></a> and <a href="#class-streamwritable"><code>Writable</code></a> interfaces.</p>
<p>Examples of <code>Transform</code> streams include:</p>
<ul>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h6><code>transform.destroy([error])</code><span><a class="mark" href="#transformdestroyerror" id="transformdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_destroy_error"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Destroy the stream, and optionally emit an <code>'error'</code> event. After this call, the
transform stream would release any internal resources.
Implementors should not override this method, but instead implement
<a href="#readable_destroyerr-callback"><code>readable._destroy()</code></a>.
The default implementation of <code>_destroy()</code> for <code>Transform</code> also emit <code>'close'</code>
unless <code>emitClose</code> is set in false.</p>
<p>Once <code>destroy()</code> has been called, any further calls will be a no-op and no
further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>
<h5><code>stream.duplexPair([options])</code><span><a class="mark" href="#streamduplexpairoptions" id="streamduplexpairoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplexpair_options"></a></h5>
<div class="api_metadata">
<span>Added in: v22.6.0</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A value to pass to both <a href="#class-streamduplex"><code>Duplex</code></a> constructors,
to set options such as buffering.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> of two <a href="#class-streamduplex"><code>Duplex</code></a> instances.</li>
</ul>
<p>The utility function <code>duplexPair</code> returns an Array with two items,
each being a <code>Duplex</code> stream connected to the other side:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> [ sideA, sideB ] = <span class="hljs-title function_">duplexPair</span>();</code> <button class="copy-button">copy</button></pre>
<p>Whatever is written to one stream is made readable on the other. It provides
behavior analogous to a network connection, where the data written by the client
becomes readable by the server, and vice-versa.</p>
<p>The Duplex streams are symmetrical; one or the other may be used without any
difference in behavior.</p>
<h4><code>stream.finished(stream[, options], callback)</code><span><a class="mark" href="#streamfinishedstream-options-callback" id="streamfinishedstream-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_finished_stream_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0</td>
<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr>
<tr><td>v15.11.0</td>
<td><p>The <code>signal</code> option was added.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>finished(stream, cb)</code> will wait for the <code>'close'</code> event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit <code>'close'</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Emitting <code>'close'</code> before <code>'end'</code> on a <code>Readable</code> stream will cause an <code>ERR_STREAM_PREMATURE_CLOSE</code> error.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Callback will be invoked on streams which have already finished before the call to <code>finished(stream, cb)</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a> A readable and/or writable
stream/webstream.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>false</code>, then a call to <code>emit('error', err)</code> is
not treated as finished. <strong>Default:</strong> <code>true</code>.</li>
<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When set to <code>false</code>, the callback will be called when
the stream ends even though the stream might still be readable.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When set to <code>false</code>, the callback will be called when
the stream ends even though the stream might still be writable.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows aborting the wait for the stream finish. The
underlying stream will <em>not</em> be aborted if the signal is aborted. The
callback will get called with an <code>AbortError</code>. All registered
listeners added by this function will also be removed.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error
argument.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A cleanup function which removes all registered
listeners.</li>
</ul>
<p>A function to get notified when a stream is no longer readable, writable
or has experienced an error or a premature close event.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>);
<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Stream failed.'</span>, err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>);
}
});
rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code> <button class="copy-button">copy</button></pre>
<p>Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit <code>'end'</code>
or <code>'finish'</code>.</p>
<p>The <code>finished</code> API provides <a href="#streamfinishedstream-options">promise version</a>.</p>
<p><code>stream.finished()</code> leaves dangling event listeners (in particular
<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been
invoked. The reason for this is so that unexpected <code>'error'</code> events (due to
incorrect stream implementations) do not cause unexpected crashes.
If this is unwanted behavior then the returned cleanup function needs to be
invoked in the callback:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> cleanup = <span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-title function_">cleanup</span>();
<span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.pipeline(source[, ...transforms], destination, callback)</code><span><a class="mark" href="#streampipelinesource-transforms-destination-callback" id="streampipelinesource-transforms-destination-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_source_transforms_destination_callback"></a></h4>
<h4><code>stream.pipeline(streams, callback)</code><span><a class="mark" href="#streampipelinestreams-callback" id="streampipelinestreams-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_streams_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.7.0, v18.16.0</td>
<td><p>Added support for webstreams.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>pipeline(..., cb)</code> will wait for the <code>'close'</code> event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit <code>'close'</code>.</p></td></tr>
<tr><td>v13.10.0</td>
<td><p>Add support for async generators.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>streams</code> <a href="stream.html#stream" class="type"><Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream[]></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream[]></a> | <a href="webstreams.html#class-transformstream" class="type"><TransformStream[]></a></li>
<li><code>source</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
</ul>
</li>
<li><code>...transforms</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="webstreams.html#class-transformstream" class="type"><TransformStream></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
</ul>
</li>
<li><code>destination</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the pipeline is fully done.
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li><code>val</code> Resolved value of <code>Promise</code> returned by <code>destination</code>.</li>
</ul>
</li>
<li>Returns: <a href="stream.html#stream" class="type"><Stream></a></li>
</ul>
<p>A module method to pipe between streams and generators forwarding errors and
properly cleaning up and provide a callback when the pipeline is complete.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-comment">// Use the pipeline API to easily pipe a series of streams</span>
<span class="hljs-comment">// together and get notified when the pipeline is fully done.</span>
<span class="hljs-comment">// A pipeline to gzip a potentially huge tar file efficiently:</span>
<span class="hljs-title function_">pipeline</span>(
fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
zlib.<span class="hljs-title function_">createGzip</span>(),
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Pipeline failed.'</span>, err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}
},
);</code> <button class="copy-button">copy</button></pre>
<p>The <code>pipeline</code> API provides a <a href="#streampipelinesource-transforms-destination-options">promise version</a>.</p>
<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p>
<ul>
<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li>
<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li>
</ul>
<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams
after the <code>callback</code> has been invoked. In the case of reuse of streams after
failure, this can cause event listener leaks and swallowed errors. If the last
stream is readable, dangling event listeners will be removed so that the last
stream can be consumed later.</p>
<p><code>stream.pipeline()</code> closes all the streams when an error is raised.
The <code>IncomingRequest</code> usage with <code>pipeline</code> could lead to an unexpected behavior
once it would destroy the socket without sending the expected response.
See the example below:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
<span class="hljs-keyword">const</span> fileStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./fileNotExist.txt'</span>);
<span class="hljs-title function_">pipeline</span>(fileStream, res, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err); <span class="hljs-comment">// No such file</span>
<span class="hljs-comment">// this message can't be sent once `pipeline` already destroyed the socket</span>
<span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'error!!!'</span>);
}
});
});</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.compose(...streams)</code><span><a class="mark" href="#streamcomposestreams" id="streamcomposestreams">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_compose_streams"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v21.1.0, v20.10.0</td>
<td><p>Added support for stream class.</p></td></tr>
<tr><td>v19.8.0, v18.16.0</td>
<td><p>Added support for webstreams.</p></td></tr>
<tr><td>v16.9.0</td>
<td><p><span>Added in: v16.9.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - <code>stream.compose</code> is experimental.</div><p></p>
<ul>
<li><code>streams</code> <a href="stream.html#stream" class="type"><Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream[]></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream[]></a> | <a href="webstreams.html#class-transformstream" class="type"><TransformStream[]></a> | <a href="stream.html#class-streamduplex" class="type"><Duplex[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>Combines two or more streams into a <code>Duplex</code> stream that writes to the
first stream and reads from the last. Each provided stream is piped into
the next, using <code>stream.pipeline</code>. If any of the streams error then all
are destroyed, including the outer <code>Duplex</code> stream.</p>
<p>Because <code>stream.compose</code> returns a new stream that in turn can (and
should) be piped into other streams, it enables composition. In contrast,
when passing streams to <code>stream.pipeline</code>, typically the first stream is
a readable stream and the last a writable stream, forming a closed
circuit.</p>
<p>If passed a <code>Function</code> it must be a factory method taking a <code>source</code>
<code>Iterable</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { compose, <span class="hljs-title class_">Transform</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">const</span> removeSpaces = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">replace</span>(<span class="hljs-string">' '</span>, <span class="hljs-string">''</span>));
},
});
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">toUpper</span>(<span class="hljs-params">source</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>();
}
}
<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>;
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> buf <span class="hljs-keyword">of</span> <span class="hljs-title function_">compose</span>(removeSpaces, toUpper).<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world'</span>)) {
res += buf;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// prints 'HELLOWORLD'</span></code> <button class="copy-button">copy</button></pre>
<p><code>stream.compose</code> can be used to convert async iterables, generators and
functions into streams.</p>
<ul>
<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield
<code>null</code>.</li>
<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform <code>Duplex</code>.
Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield
<code>null</code>.</li>
<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return
either <code>null</code> or <code>undefined</code>.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { compose } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-comment">// Convert AsyncIterable into readable Duplex.</span>
<span class="hljs-keyword">const</span> s1 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>*() {
<span class="hljs-keyword">yield</span> <span class="hljs-string">'Hello'</span>;
<span class="hljs-keyword">yield</span> <span class="hljs-string">'World'</span>;
}());
<span class="hljs-comment">// Convert AsyncGenerator into transform Duplex.</span>
<span class="hljs-keyword">const</span> s2 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>*(source) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
<span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>();
}
});
<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>;
<span class="hljs-comment">// Convert AsyncFunction into writable Duplex.</span>
<span class="hljs-keyword">const</span> s3 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">source</span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
res += chunk;
}
});
<span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(<span class="hljs-title function_">compose</span>(s1, s2, s3));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// prints 'HELLOWORLD'</span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#readablecomposestream-options"><code>readable.compose(stream)</code></a> for <code>stream.compose</code> as operator.</p>
<h4><code>stream.Readable.from(iterable[, options])</code><span><a class="mark" href="#streamreadablefromiterable-options" id="streamreadablefromiterable-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_from_iterable_options"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0, v10.17.0</span>
</div>
<ul>
<li><code>iterable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> Object implementing the <code>Symbol.asyncIterator</code> or
<code>Symbol.iterator</code> iterable protocol. Emits an 'error' event if a null
value is passed.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Options provided to <code>new stream.Readable([options])</code>.
By default, <code>Readable.from()</code> will set <code>options.objectMode</code> to <code>true</code>, unless
this is explicitly opted out by setting <code>options.objectMode</code> to <code>false</code>.</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<p>A utility method for creating readable streams out of iterators.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> <span class="hljs-string">'hello'</span>;
<span class="hljs-keyword">yield</span> <span class="hljs-string">'streams'</span>;
}
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>());
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
});</code> <button class="copy-button">copy</button></pre>
<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have
the strings or buffers be iterated to match the other streams semantics
for performance reasons.</p>
<p>If an <code>Iterable</code> object containing promises is passed as an argument,
it might result in unhandled rejection.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'1'</span>), <span class="hljs-number">1500</span>)),
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'2'</span>)), <span class="hljs-number">1000</span>)), <span class="hljs-comment">// Unhandled rejection</span>
]);</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.Readable.fromWeb(readableStream[, options])</code><span><a class="mark" href="#streamreadablefromwebreadablestream-options" id="streamreadablefromwebreadablestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_fromweb_readablestream_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>readableStream</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li>
</ul>
<h4><code>stream.Readable.isDisturbed(stream)</code><span><a class="mark" href="#streamreadableisdisturbedstream" id="streamreadableisdisturbedstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_isdisturbed_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v16.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
<li>Returns: <code>boolean</code></li>
</ul>
<p>Returns whether the stream has been read from or cancelled.</p>
<h4><code>stream.isErrored(stream)</code><span><a class="mark" href="#streamiserroredstream" id="streamiserroredstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_iserrored_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="stream.html#class-streamreadable" class="type"><Readable></a> | <a href="stream.html#class-streamwritable" class="type"><Writable></a> | <a href="stream.html#class-streamduplex" class="type"><Duplex></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns whether the stream has encountered an error.</p>
<h4><code>stream.isReadable(stream)</code><span><a class="mark" href="#streamisreadablestream" id="streamisreadablestream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_isreadable_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="stream.html#class-streamreadable" class="type"><Readable></a> | <a href="stream.html#class-streamduplex" class="type"><Duplex></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>Returns whether the stream is readable.</p>
<h4><code>stream.Readable.toWeb(streamReadable[, options])</code><span><a class="mark" href="#streamreadabletowebstreamreadable-options" id="streamreadabletowebstreamreadable-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_toweb_streamreadable_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamReadable</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum internal queue size (of the created
<code>ReadableStream</code>) before backpressure is applied in reading from the given
<code>stream.Readable</code>. If no value is provided, it will be taken from the
given <code>stream.Readable</code>.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that size of the given chunk of data.
If no value is provided, the size will be <code>1</code> for all the chunks.
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
</ul>
<h4><code>stream.Writable.fromWeb(writableStream[, options])</code><span><a class="mark" href="#streamwritablefromwebwritablestream-options" id="streamwritablefromwebwritablestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_writable_fromweb_writablestream_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>writableStream</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li>
</ul>
<h4><code>stream.Writable.toWeb(streamWritable)</code><span><a class="mark" href="#streamwritabletowebstreamwritable" id="streamwritabletowebstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_writable_toweb_streamwritable"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamWritable</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li>
<li>Returns: <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li>
</ul>
<h4><code>stream.Duplex.from(src)</code><span><a class="mark" href="#streamduplexfromsrc" id="streamduplexfromsrc">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_from_src"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0, v18.17.0</td>
<td><p>The <code>src</code> argument can now be a <code>ReadableStream</code> or <code>WritableStream</code>.</p></td></tr>
<tr><td>v16.8.0</td>
<td><p><span>Added in: v16.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>src</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="buffer.html#class-blob" class="type"><Blob></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor" class="type"><AsyncGeneratorFunction></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li>
</ul>
<p>A utility method for creating duplex streams.</p>
<ul>
<li><code>Stream</code> converts writable stream into writable <code>Duplex</code> and readable stream
to <code>Duplex</code>.</li>
<li><code>Blob</code> converts into readable <code>Duplex</code>.</li>
<li><code>string</code> converts into readable <code>Duplex</code>.</li>
<li><code>ArrayBuffer</code> converts into readable <code>Duplex</code>.</li>
<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield
<code>null</code>.</li>
<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform
<code>Duplex</code>. Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield
<code>null</code>.</li>
<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return
either <code>null</code> or <code>undefined</code></li>
<li><code>Object ({ writable, readable })</code> converts <code>readable</code> and
<code>writable</code> into <code>Stream</code> and then combines them into <code>Duplex</code> where the
<code>Duplex</code> will write to the <code>writable</code> and read from the <code>readable</code>.</li>
<li><code>Promise</code> converts into readable <code>Duplex</code>. Value <code>null</code> is ignored.</li>
<li><code>ReadableStream</code> converts into readable <code>Duplex</code>.</li>
<li><code>WritableStream</code> converts into writable <code>Duplex</code>.</li>
<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<p>If an <code>Iterable</code> object containing promises is passed as an argument,
it might result in unhandled rejection.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">from</span>([
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'1'</span>), <span class="hljs-number">1500</span>)),
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'2'</span>)), <span class="hljs-number">1000</span>)), <span class="hljs-comment">// Unhandled rejection</span>
]);</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.Duplex.fromWeb(pair[, options])</code><span><a class="mark" href="#streamduplexfromwebpair-options" id="streamduplexfromwebpair-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_fromweb_pair_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>pair</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>readable</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
<li><code>writable</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li>
</ul>
</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li>
</ul>
<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Duplex</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> {
<span class="hljs-title class_">ReadableStream</span>,
<span class="hljs-title class_">WritableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;
<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>);
},
});
<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
},
});
<span class="hljs-keyword">const</span> pair = {
readable,
writable,
};
<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">fromWeb</span>(pair, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>, <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span> });
duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> duplex) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, chunk);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> {
<span class="hljs-title class_">ReadableStream</span>,
<span class="hljs-title class_">WritableStream</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>);
},
});
<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
},
});
<span class="hljs-keyword">const</span> pair = {
readable,
writable,
};
<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">fromWeb</span>(pair, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>, <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span> });
duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
duplex.<span class="hljs-title function_">once</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, duplex.<span class="hljs-title function_">read</span>()));</code><button class="copy-button">copy</button></pre>
<h4><code>stream.Duplex.toWeb(streamDuplex)</code><span><a class="mark" href="#streamduplextowebstreamduplex" id="streamduplextowebstreamduplex">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_toweb_streamduplex"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamDuplex</code> <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>readable</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li>
<li><code>writable</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li>
</ul>
</li>
</ul>
<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Duplex</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({
<span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>,
<span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
},
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
<span class="hljs-title function_">callback</span>();
},
});
<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex);
writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
<span class="hljs-keyword">const</span> { value } = <span class="hljs-keyword">await</span> readable.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, value);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({
<span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>,
<span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
},
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
<span class="hljs-title function_">callback</span>();
},
});
<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex);
writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
readable.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, result.<span class="hljs-property">value</span>);
});</code><button class="copy-button">copy</button></pre>
<h4><code>stream.addAbortSignal(signal, stream)</code><span><a class="mark" href="#streamaddabortsignalsignal-stream" id="streamaddabortsignalsignal-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_addabortsignal_signal_stream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.7.0, v18.16.0</td>
<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p><span>Added in: v15.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation</li>
<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a> A stream to attach a signal
to.</li>
</ul>
<p>Attaches an AbortSignal to a readable or writeable stream. This lets code
control stream destruction using an <code>AbortController</code>.</p>
<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed
<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code>
on the stream, and <code>controller.error(new AbortError())</code> for webstreams.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> read = <span class="hljs-title function_">addAbortSignal</span>(
controller.<span class="hljs-property">signal</span>,
fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)),
);
<span class="hljs-comment">// Later, abort the operation closing the stream</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>Or using an <code>AbortSignal</code> with a readable stream as an async iterable:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> controller.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10_000</span>); <span class="hljs-comment">// set a timeout</span>
<span class="hljs-keyword">const</span> stream = <span class="hljs-title function_">addAbortSignal</span>(
controller.<span class="hljs-property">signal</span>,
fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)),
);
(<span class="hljs-title function_">async</span> () => {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">process</span>(chunk);
}
} <span class="hljs-keyword">catch</span> (e) {
<span class="hljs-keyword">if</span> (e.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
<span class="hljs-comment">// The operation was cancelled</span>
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">throw</span> e;
}
}
})();</code> <button class="copy-button">copy</button></pre>
<p>Or using an <code>AbortSignal</code> with a ReadableStream:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> rs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
<span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'hello'</span>);
controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>);
controller.<span class="hljs-title function_">close</span>();
},
});
<span class="hljs-title function_">addAbortSignal</span>(controller.<span class="hljs-property">signal</span>, rs);
<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
<span class="hljs-comment">// The operation was cancelled</span>
}
}
});
<span class="hljs-keyword">const</span> reader = rs.<span class="hljs-title function_">getReader</span>();
reader.<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">{ value, done }</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value); <span class="hljs-comment">// hello</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(done); <span class="hljs-comment">// false</span>
controller.<span class="hljs-title function_">abort</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.getDefaultHighWaterMark(objectMode)</code><span><a class="mark" href="#streamgetdefaulthighwatermarkobjectmode" id="streamgetdefaulthighwatermarkobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_getdefaulthighwatermark_objectmode"></a></h4>
<div class="api_metadata">
<span>Added in: v19.9.0, v18.17.0</span>
</div>
<ul>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
<p>Returns the default highWaterMark used by streams.
Defaults to <code>65536</code> (64 KiB), or <code>16</code> for <code>objectMode</code>.</p>
<h4><code>stream.setDefaultHighWaterMark(objectMode, value)</code><span><a class="mark" href="#streamsetdefaulthighwatermarkobjectmode-value" id="streamsetdefaulthighwatermarkobjectmode-value">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_setdefaulthighwatermark_objectmode_value"></a></h4>
<div class="api_metadata">
<span>Added in: v19.9.0, v18.17.0</span>
</div>
<ul>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> highWaterMark value</li>
</ul>
<p>Sets the default highWaterMark used by streams.</p>
</section><section><h3>API for stream implementers<span><a class="mark" href="#api-for-stream-implementers" id="api-for-stream-implementers">#</a></span><a aria-hidden="true" class="legacy" id="stream_api_for_stream_implementers"></a></h3>
<p>The <code>node:stream</code> module API has been designed to make it possible to easily
implement streams using JavaScript's prototypal inheritance model.</p>
<p>First, a stream developer would declare a new JavaScript class that extends one
of the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>,
<code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate
parent class constructor:</p>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">{ highWaterMark, ...options }</span>) {
<span class="hljs-variable language_">super</span>({ highWaterMark });
<span class="hljs-comment">// ...</span>
}
}</code> <button class="copy-button">copy</button></pre>
<p>When extending streams, keep in mind what options the user
can and should provide before forwarding these to the base constructor. For
example, if the implementation makes assumptions in regard to the
<code>autoDestroy</code> and <code>emitClose</code> options, do not allow the
user to override these. Be explicit about what
options are forwarded instead of implicitly forwarding all options.</p>
<p>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:</p>
<table><thead><tr><th>Use-case</th><th>Class</th><th>Method(s) to implement</th></tr></thead><tbody><tr><td>Reading only</td><td><a href="#class-streamreadable"><code>Readable</code></a></td><td><a href="#readable_readsize"><code>_read()</code></a></td></tr><tr><td>Writing only</td><td><a href="#class-streamwritable"><code>Writable</code></a></td><td><a href="#writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Reading and writing</td><td><a href="#class-streamduplex"><code>Duplex</code></a></td><td><a href="#readable_readsize"><code>_read()</code></a>, <a href="#writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#class-streamtransform"><code>Transform</code></a></td><td><a href="#transform_transformchunk-encoding-callback"><code>_transform()</code></a>, <a href="#transform_flushcallback"><code>_flush()</code></a>, <a href="#writable_finalcallback"><code>_final()</code></a></td></tr></tbody></table>
<p>The implementation code for a stream should <em>never</em> call the "public" methods
of a stream that are intended for use by consumers (as described in the
<a href="#api-for-stream-consumers">API for stream consumers</a> section). Doing so may lead to adverse side effects
in application code consuming the stream.</p>
<p>Avoid overriding public methods such as <code>write()</code>, <code>end()</code>, <code>cork()</code>,
<code>uncork()</code>, <code>read()</code> and <code>destroy()</code>, or emitting internal events such
as <code>'error'</code>, <code>'data'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code> through <code>.emit()</code>.
Doing so can break current and future stream invariants leading to behavior
and/or compatibility issues with other streams, stream utilities, and user
expectations.</p>
<h4>Simplified construction<span><a class="mark" href="#simplified-construction" id="simplified-construction">#</a></span><a aria-hidden="true" class="legacy" id="stream_simplified_construction"></a></h4>
<div class="api_metadata">
<span>Added in: v1.2.0</span>
</div>
<p>For many simple cases, it is possible to create a stream without relying on
inheritance. This can be accomplished by directly creating instances of the
<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code>, or <code>stream.Transform</code>
objects and passing appropriate methods as constructor options.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
<span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-comment">// Initialize state and load resources...</span>
},
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// ...</span>
},
<span class="hljs-title function_">destroy</span>(<span class="hljs-params"></span>) {
<span class="hljs-comment">// Free resources...</span>
},
});</code> <button class="copy-button">copy</button></pre>
<h4>Implementing a writable stream<span><a class="mark" href="#implementing-a-writable-stream" id="implementing-a-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_writable_stream"></a></h4>
<p>The <code>stream.Writable</code> class is extended to implement a <a href="#class-streamwritable"><code>Writable</code></a> stream.</p>
<p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code>
constructor and implement the <code>writable._write()</code> and/or <code>writable._writev()</code>
method.</p>
<h5><code>new stream.Writable([options])</code><span><a class="mark" href="#new-streamwritableoptions" id="new-streamwritableoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_writable_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.0.0</td>
<td><p>bump default highWaterMark.</p></td></tr>
<tr><td>v15.5.0</td>
<td><p>support passing in an AbortSignal.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr>
<tr><td>v11.2.0, v10.16.0</td>
<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'finish'</code> or errors.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Buffer level when
<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong>
<code>65536</code> (64 KiB), or <code>16</code> for <code>objectMode</code> streams.</li>
<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether to encode <code>string</code>s passed to
<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding
specified in the <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> call) before passing
them to <a href="#writable_writechunk-encoding-callback"><code>stream._write()</code></a>. Other types of data are not
converted (i.e. <code>Buffer</code>s are not decoded into <code>string</code>s). Setting to
false will prevent <code>string</code>s from being converted. <strong>Default:</strong> <code>true</code>.</li>
<li><code>defaultEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The default encoding that is used when no
encoding is specified as an argument to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.
<strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the
<a href="#writablewritechunk-encoding-callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set,
it becomes possible to write JavaScript values other than string, <a href="buffer.html#class-buffer" class="type"><Buffer></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> if supported by the stream implementation.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the stream should emit <code>'close'</code>
after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li>
<li><code>write</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#writable_writechunk-encoding-callback"><code>stream._write()</code></a> method.</li>
<li><code>writev</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#writable_writevchunks-callback"><code>stream._writev()</code></a> method.</li>
<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#writable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li>
<li><code>final</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#writable_finalcallback"><code>stream._final()</code></a> method.</li>
<li><code>construct</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#writable_constructcallback"><code>stream._construct()</code></a> method.</li>
<li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should automatically call
<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
<span class="hljs-comment">// Calls the stream.Writable() constructor.</span>
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-comment">// ...</span>
}
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyWritable</span>(<span class="hljs-params">options</span>) {
<span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyWritable</span>))
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyWritable</span>(options);
<span class="hljs-title class_">Writable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyWritable</span>, <span class="hljs-title class_">Writable</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// ...</span>
},
<span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) {
<span class="hljs-comment">// ...</span>
},
});</code> <button class="copy-button">copy</button></pre>
<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed
<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code>
on the writeable stream.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// ...</span>
},
<span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) {
<span class="hljs-comment">// ...</span>
},
<span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>,
});
<span class="hljs-comment">// Later, abort the operation closing the stream</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h5><code>writable._construct(callback)</code><span><a class="mark" href="#writable_constructcallback" id="writable_constructcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_construct_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error
argument) when the stream has finished initializing.</li>
</ul>
<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented
by child classes, and if so, will be called by the internal <code>Writable</code>
class methods only.</p>
<p>This optional function will be called in a tick after the stream constructor
has returned, delaying any <code>_write()</code>, <code>_final()</code> and <code>_destroy()</code> calls until
<code>callback</code> is called. This is useful to initialize state or asynchronously
initialize resources before the stream can be used.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">WriteStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) {
<span class="hljs-variable language_">super</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>;
}
<span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) {
fs.<span class="hljs-title function_">open</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span>, <span class="hljs-string">'w'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-title function_">callback</span>(err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd;
<span class="hljs-title function_">callback</span>();
}
});
}
<span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
fs.<span class="hljs-title function_">write</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, chunk, callback);
}
<span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) {
<span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) {
fs.<span class="hljs-title function_">close</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> <span class="hljs-title function_">callback</span>(er || err));
} <span class="hljs-keyword">else</span> {
<span class="hljs-title function_">callback</span>(err);
}
}
}</code> <button class="copy-button">copy</button></pre>
<h5><code>writable._write(chunk, encoding, callback)</code><span><a class="mark" href="#writable_writechunk-encoding-callback" id="writable_writechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_write_chunk_encoding_callback_1"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.11.0</td>
<td><p>_write() is optional when providing _writev().</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>Buffer</code> to be written, converted from the
<code>string</code> passed to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. If the stream's
<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode,
the chunk will not be converted & will be whatever was passed to
<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If the chunk is a string, then <code>encoding</code> is the
character encoding of that string. If chunk is a <code>Buffer</code>, or if the
stream is operating in object mode, <code>encoding</code> may be ignored.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error
argument) when processing is complete for the supplied chunk.</li>
</ul>
<p>All <code>Writable</code> stream implementations must provide a
<a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a> and/or
<a href="#writable_writevchunks-callback"><code>writable._writev()</code></a> method to send data to the underlying
resource.</p>
<p><a href="#class-streamtransform"><code>Transform</code></a> streams provide their own implementation of the
<a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a>.</p>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Writable</code> class
methods only.</p>
<p>The <code>callback</code> function must be called synchronously inside of
<code>writable._write()</code> or asynchronously (i.e. different tick) to signal either
that the write completed successfully or failed with an error.
The first argument passed to the <code>callback</code> must be the <code>Error</code> object if the
call failed or <code>null</code> if the write succeeded.</p>
<p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code>
is called and the <code>callback</code> is called will cause the written data to be
buffered. When the <code>callback</code> is invoked, the stream might emit a <a href="#event-drain"><code>'drain'</code></a>
event. If a stream implementation is capable of processing multiple chunks of
data at once, the <code>writable._writev()</code> method should be implemented.</p>
<p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor
options, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>,
and may be a string rather than a <code>Buffer</code>. This is to support implementations
that have an optimized handling for certain string data encodings. In that case,
the <code>encoding</code> argument will indicate the character encoding of the string.
Otherwise, the <code>encoding</code> argument can be safely ignored.</p>
<p>The <code>writable._write()</code> 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.</p>
<h5><code>writable._writev(chunks, callback)</code><span><a class="mark" href="#writable_writevchunks-callback" id="writable_writevchunks-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writev_chunks_callback"></a></h5>
<ul>
<li><code>chunks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> The data to be written. The value is an array of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
that each represent a discrete chunk of data to write. The properties of
these objects are:
<ul>
<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A buffer instance or string containing the data to
be written. The <code>chunk</code> will be a string if the <code>Writable</code> was created with
the <code>decodeStrings</code> option set to <code>false</code> and a string was passed to <code>write()</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The character encoding of the <code>chunk</code>. If <code>chunk</code> is
a <code>Buffer</code>, the <code>encoding</code> will be <code>'buffer'</code>.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error
argument) to be invoked when processing is complete for the supplied chunks.</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Writable</code> class
methods only.</p>
<p>The <code>writable._writev()</code> method may be implemented in addition or alternatively
to <code>writable._write()</code> in stream implementations that are capable of processing
multiple chunks of data at once. If implemented and if there is buffered data
from previous writes, <code>_writev()</code> will be called instead of <code>_write()</code>.</p>
<p>The <code>writable._writev()</code> 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.</p>
<h5><code>writable._destroy(err, callback)</code><span><a class="mark" href="#writable_destroyerr-callback" id="writable_destroyerr-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroy_err_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A possible error.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error
argument.</li>
</ul>
<p>The <code>_destroy()</code> method is called by <a href="#writabledestroyerror"><code>writable.destroy()</code></a>.
It can be overridden by child classes but it <strong>must not</strong> be called directly.</p>
<h5><code>writable._final(callback)</code><span><a class="mark" href="#writable_finalcallback" id="writable_finalcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_final_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error
argument) when finished writing any remaining data.</li>
</ul>
<p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented
by child classes, and if so, will be called by the internal <code>Writable</code>
class methods only.</p>
<p>This optional function will be called before the stream closes, delaying the
<code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources
or write buffered data before a stream ends.</p>
<h5>Errors while writing<span><a class="mark" href="#errors-while-writing" id="errors-while-writing">#</a></span><a aria-hidden="true" class="legacy" id="stream_errors_while_writing"></a></h5>
<p>Errors occurring during the processing of the <a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a>,
<a href="#writable_writevchunks-callback"><code>writable._writev()</code></a> and <a href="#writable_finalcallback"><code>writable._final()</code></a> methods must be propagated
by invoking the callback and passing the error as the first argument.
Throwing an <code>Error</code> from within these methods or manually emitting an <code>'error'</code>
event results in undefined behavior.</p>
<p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an
error, the <code>Readable</code> stream will be unpiped.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-keyword">if</span> (chunk.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'a'</span>) >= <span class="hljs-number">0</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'chunk is invalid'</span>));
} <span class="hljs-keyword">else</span> {
<span class="hljs-title function_">callback</span>();
}
},
});</code> <button class="copy-button">copy</button></pre>
<h5>An example writable stream<span><a class="mark" href="#an-example-writable-stream" id="an-example-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_writable_stream"></a></h5>
<p>The following illustrates a rather simplistic (and somewhat pointless) custom
<code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance
is not of any real particular usefulness, the example illustrates each of the
required elements of a custom <a href="#class-streamwritable"><code>Writable</code></a> stream instance:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
<span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-keyword">if</span> (chunk.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'a'</span>) >= <span class="hljs-number">0</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'chunk is invalid'</span>));
} <span class="hljs-keyword">else</span> {
<span class="hljs-title function_">callback</span>();
}
}
}</code> <button class="copy-button">copy</button></pre>
<h5>Decoding buffers in a writable stream<span><a class="mark" href="#decoding-buffers-in-a-writable-stream" id="decoding-buffers-in-a-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_decoding_buffers_in_a_writable_stream"></a></h5>
<p>Decoding buffers is a common task, for instance, when using transformers whose
input is a string. This is not a trivial process when using multi-byte
characters encoding, such as UTF-8. The following example shows how to decode
multi-byte strings using <code>StringDecoder</code> and <a href="#class-streamwritable"><code>Writable</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">StringWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(options?.<span class="hljs-property">defaultEncoding</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>;
}
<span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-keyword">if</span> (encoding === <span class="hljs-string">'buffer'</span>) {
chunk = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">write</span>(chunk);
}
<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk;
<span class="hljs-title function_">callback</span>();
}
<span class="hljs-title function_">_final</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">end</span>();
<span class="hljs-title function_">callback</span>();
}
}
<span class="hljs-keyword">const</span> euro = [[<span class="hljs-number">0xE2</span>, <span class="hljs-number">0x82</span>], [<span class="hljs-number">0xAC</span>]].<span class="hljs-title function_">map</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">from</span>);
<span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringWritable</span>();
w.<span class="hljs-title function_">write</span>(<span class="hljs-string">'currency: '</span>);
w.<span class="hljs-title function_">write</span>(euro[<span class="hljs-number">0</span>]);
w.<span class="hljs-title function_">end</span>(euro[<span class="hljs-number">1</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(w.<span class="hljs-property">data</span>); <span class="hljs-comment">// currency: €</span></code> <button class="copy-button">copy</button></pre>
<h4>Implementing a readable stream<span><a class="mark" href="#implementing-a-readable-stream" id="implementing-a-readable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_readable_stream"></a></h4>
<p>The <code>stream.Readable</code> class is extended to implement a <a href="#class-streamreadable"><code>Readable</code></a> stream.</p>
<p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code>
constructor and implement the <a href="#readable_readsize"><code>readable._read()</code></a> method.</p>
<h5><code>new stream.Readable([options])</code><span><a class="mark" href="#new-streamreadableoptions" id="new-streamreadableoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_readable_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.0.0</td>
<td><p>bump default highWaterMark.</p></td></tr>
<tr><td>v15.5.0</td>
<td><p>support passing in an AbortSignal.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr>
<tr><td>v11.2.0, v10.16.0</td>
<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'end'</code> or errors.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a>
<ul>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum <a href="#highwatermark-discrepancy-after-calling-readablesetencoding">number of bytes</a> to store
in the internal buffer before ceasing to read from the underlying resource.
<strong>Default:</strong> <code>65536</code> (64 KiB), or <code>16</code> for <code>objectMode</code> streams.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If specified, then buffers will be decoded to
strings using the specified encoding. <strong>Default:</strong> <code>null</code>.</li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should behave
as a stream of objects. Meaning that <a href="#readablereadsize"><code>stream.read(n)</code></a> returns
a single value instead of a <code>Buffer</code> of size <code>n</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the stream should emit <code>'close'</code>
after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li>
<li><code>read</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#readable_readsize"><code>stream._read()</code></a>
method.</li>
<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#readable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li>
<li><code>construct</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#readable_constructcallback"><code>stream._construct()</code></a> method.</li>
<li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should automatically call
<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyReadable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
<span class="hljs-comment">// Calls the stream.Readable(options) constructor.</span>
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-comment">// ...</span>
}
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyReadable</span>(<span class="hljs-params">options</span>) {
<span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyReadable</span>))
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyReadable</span>(options);
<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyReadable</span>, <span class="hljs-title class_">Readable</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({
<span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
<span class="hljs-comment">// ...</span>
},
});</code> <button class="copy-button">copy</button></pre>
<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed
<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code>
on the readable created.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> read = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({
<span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
<span class="hljs-comment">// ...</span>
},
<span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>,
});
<span class="hljs-comment">// Later, abort the operation closing the stream</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h5><code>readable._construct(callback)</code><span><a class="mark" href="#readable_constructcallback" id="readable_constructcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_construct_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error
argument) when the stream has finished initializing.</li>
</ul>
<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented
by child classes, and if so, will be called by the internal <code>Readable</code>
class methods only.</p>
<p>This optional function will be scheduled in the next tick by the stream
constructor, delaying any <code>_read()</code> and <code>_destroy()</code> calls until <code>callback</code> is
called. This is useful to initialize state or asynchronously initialize
resources before the stream can be used.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">ReadStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) {
<span class="hljs-variable language_">super</span>();
<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>;
}
<span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) {
fs.<span class="hljs-title function_">open</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-title function_">callback</span>(err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd;
<span class="hljs-title function_">callback</span>();
}
});
}
<span class="hljs-title function_">_read</span>(<span class="hljs-params">n</span>) {
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(n);
fs.<span class="hljs-title function_">read</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, buf, <span class="hljs-number">0</span>, n, <span class="hljs-literal">null</span>, <span class="hljs-function">(<span class="hljs-params">err, bytesRead</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(bytesRead > <span class="hljs-number">0</span> ? buf.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, bytesRead) : <span class="hljs-literal">null</span>);
}
});
}
<span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) {
<span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) {
fs.<span class="hljs-title function_">close</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> <span class="hljs-title function_">callback</span>(er || err));
} <span class="hljs-keyword">else</span> {
<span class="hljs-title function_">callback</span>(err);
}
}
}</code> <button class="copy-button">copy</button></pre>
<h5><code>readable._read(size)</code><span><a class="mark" href="#readable_readsize" id="readable_readsize">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_size_1"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of bytes to read asynchronously</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Readable</code> class
methods only.</p>
<p>All <code>Readable</code> stream implementations must provide an implementation of the
<a href="#readable_readsize"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p>
<p>When <a href="#readable_readsize"><code>readable._read()</code></a> is called, if data is available from the resource,
the implementation should begin pushing that data into the read queue using the
<a href="#readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again
after each call to <a href="#readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> once the stream is
ready to accept more data. <code>_read()</code> may continue reading from the resource and
pushing data until <code>readable.push()</code> returns <code>false</code>. Only when <code>_read()</code> is
called again after it has stopped should it resume pushing additional data into
the queue.</p>
<p>Once the <a href="#readable_readsize"><code>readable._read()</code></a> method has been called, it will not be called
again until more data is pushed through the <a href="#readablepushchunk-encoding"><code>readable.push()</code></a>
method. Empty data such as empty buffers and strings will not cause
<a href="#readable_readsize"><code>readable._read()</code></a> to be called.</p>
<p>The <code>size</code> argument is advisory. For implementations where a "read" is a
single operation that returns data can use the <code>size</code> 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
<code>size</code> bytes are available before calling <a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>.</p>
<p>The <a href="#readable_readsize"><code>readable._read()</code></a> 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.</p>
<h5><code>readable._destroy(err, callback)</code><span><a class="mark" href="#readable_destroyerr-callback" id="readable_destroyerr-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroy_err_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A possible error.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error
argument.</li>
</ul>
<p>The <code>_destroy()</code> method is called by <a href="#readabledestroyerror"><code>readable.destroy()</code></a>.
It can be overridden by child classes but it <strong>must not</strong> be called directly.</p>
<h5><code>readable.push(chunk[, encoding])</code><span><a class="mark" href="#readablepushchunk-encoding" id="readablepushchunk-encoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_push_chunk_encoding"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v22.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Chunk of data to push
into the read queue. For streams not operating in object mode, <code>chunk</code> must
be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, <a href="buffer.html#class-buffer" class="type"><Buffer></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a>. For object mode streams,
<code>chunk</code> may be any JavaScript value.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Encoding of string chunks. Must be a valid
<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if additional chunks of data may continue to be
pushed; <code>false</code> otherwise.</li>
</ul>
<p>When <code>chunk</code> is a <a href="buffer.html#class-buffer" class="type"><Buffer></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, the <code>chunk</code>
of data will be added to the internal queue for users of the stream to consume.
Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no
more data can be written.</p>
<p>When the <code>Readable</code> is operating in paused mode, the data added with
<code>readable.push()</code> can be read out by calling the
<a href="#readablereadsize"><code>readable.read()</code></a> method when the <a href="#event-readable"><code>'readable'</code></a> event is
emitted.</p>
<p>When the <code>Readable</code> is operating in flowing mode, the data added with
<code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p>
<p>The <code>readable.push()</code> 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 <code>Readable</code> instance:</p>
<pre><code class="language-js"><span class="hljs-comment">// `_source` is an object with readStop() and readStart() methods,</span>
<span class="hljs-comment">// and an `ondata` member that gets called when it has data, and</span>
<span class="hljs-comment">// an `onend` member that gets called when the data is over.</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">SourceWrapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span> = <span class="hljs-title function_">getLowLevelSourceObject</span>();
<span class="hljs-comment">// Every time there's data, push it into the internal buffer.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">ondata</span> = <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
<span class="hljs-comment">// If push() returns false, then stop reading from source.</span>
<span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(chunk))
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStop</span>();
};
<span class="hljs-comment">// When the source ends, push the EOF-signaling `null` chunk.</span>
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">onend</span> = <span class="hljs-function">() =></span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
};
}
<span class="hljs-comment">// _read() will be called when the stream wants to pull more data in.</span>
<span class="hljs-comment">// The advisory size argument is ignored in this case.</span>
<span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStart</span>();
}
}</code> <button class="copy-button">copy</button></pre>
<p>The <code>readable.push()</code> method is used to push the content
into the internal buffer. It can be driven by the <a href="#readable_readsize"><code>readable._read()</code></a> method.</p>
<p>For streams not operating in object mode, if the <code>chunk</code> parameter of
<code>readable.push()</code> is <code>undefined</code>, it will be treated as empty string or
buffer. See <a href="#readablepush"><code>readable.push('')</code></a> for more information.</p>
<h5>Errors while reading<span><a class="mark" href="#errors-while-reading" id="errors-while-reading">#</a></span><a aria-hidden="true" class="legacy" id="stream_errors_while_reading"></a></h5>
<p>Errors occurring during processing of the <a href="#readable_readsize"><code>readable._read()</code></a> must be
propagated through the <a href="#readable_destroyerr-callback"><code>readable.destroy(err)</code></a> method.
Throwing an <code>Error</code> from within <a href="#readable_readsize"><code>readable._read()</code></a> or manually emitting an
<code>'error'</code> event results in undefined behavior.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({
<span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkSomeErrorCondition</span>();
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Do some work.</span>
}
},
});</code> <button class="copy-button">copy</button></pre>
<h5>An example counting stream<span><a class="mark" href="#an-example-counting-stream" id="an-example-counting-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_counting_stream"></a></h5>
<p>The following is a basic example of a <code>Readable</code> stream that emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">opt</span>) {
<span class="hljs-variable language_">super</span>(opt);
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span> = <span class="hljs-number">1000000</span>;
<span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span> = <span class="hljs-number">1</span>;
}
<span class="hljs-title function_">_read</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> i = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span>++;
<span class="hljs-keyword">if</span> (i > <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span>)
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">else</span> {
<span class="hljs-keyword">const</span> str = <span class="hljs-title class_">String</span>(i);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(str, <span class="hljs-string">'ascii'</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(buf);
}
}
}</code> <button class="copy-button">copy</button></pre>
<h4>Implementing a duplex stream<span><a class="mark" href="#implementing-a-duplex-stream" id="implementing-a-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_duplex_stream"></a></h4>
<p>A <a href="#class-streamduplex"><code>Duplex</code></a> stream is one that implements both <a href="#class-streamreadable"><code>Readable</code></a> and
<a href="#class-streamwritable"><code>Writable</code></a>, such as a TCP socket connection.</p>
<p>Because JavaScript does not have support for multiple inheritance, the
<code>stream.Duplex</code> class is extended to implement a <a href="#class-streamduplex"><code>Duplex</code></a> stream (as opposed
to extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p>
<p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and
parasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for
both base classes due to overriding <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance"><code>Symbol.hasInstance</code></a> on
<code>stream.Writable</code>.</p>
<p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code>
constructor and implement <em>both</em> the <a href="#readable_readsize"><code>readable._read()</code></a> and
<code>writable._write()</code> methods.</p>
<h5><code>new stream.Duplex(options)</code><span><a class="mark" href="#new-streamduplexoptions" id="new-streamduplexoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_duplex_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.4.0</td>
<td><p>The <code>readableHighWaterMark</code> and <code>writableHighWaterMark</code> options are supported now.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Passed to both <code>Writable</code> and <code>Readable</code>
constructors. Also has the following fields:
<ul>
<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>false</code>, then the stream will
automatically end the writable side when the readable side ends.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets whether the <code>Duplex</code> should be readable.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets whether the <code>Duplex</code> should be writable.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>readableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets <code>objectMode</code> for readable side of the
stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>writableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets <code>objectMode</code> for writable side of the
stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>readableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets <code>highWaterMark</code> for the readable side
of the stream. Has no effect if <code>highWaterMark</code> is provided.</li>
<li><code>writableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets <code>highWaterMark</code> for the writable side
of the stream. Has no effect if <code>highWaterMark</code> is provided.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDuplex</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Duplex</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-comment">// ...</span>
}
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyDuplex</span>(<span class="hljs-params">options</span>) {
<span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyDuplex</span>))
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyDuplex</span>(options);
<span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyDuplex</span>, <span class="hljs-title class_">Duplex</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myDuplex = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Duplex</span>({
<span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
<span class="hljs-comment">// ...</span>
},
<span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// ...</span>
},
});</code> <button class="copy-button">copy</button></pre>
<p>When using pipeline:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span>, pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-title function_">pipeline</span>(
fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'object.json'</span>)
.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>),
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
<span class="hljs-attr">decodeStrings</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// Accept string input rather than Buffers</span>
<span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>;
<span class="hljs-title function_">callback</span>();
},
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk;
<span class="hljs-title function_">callback</span>();
},
<span class="hljs-title function_">flush</span>(<span class="hljs-params">callback</span>) {
<span class="hljs-keyword">try</span> {
<span class="hljs-comment">// Make sure is valid json.</span>
<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span>);
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span>);
<span class="hljs-title function_">callback</span>();
} <span class="hljs-keyword">catch</span> (err) {
<span class="hljs-title function_">callback</span>(err);
}
},
}),
fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'valid-object.json'</span>),
<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'failed'</span>, err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'completed'</span>);
}
},
);</code> <button class="copy-button">copy</button></pre>
<h5>An example duplex stream<span><a class="mark" href="#an-example-duplex-stream" id="an-example-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_duplex_stream"></a></h5>
<p>The following illustrates a simple example of a <code>Duplex</code> 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 <code>Duplex</code> stream that buffers
incoming written data via the <a href="#class-streamwritable"><code>Writable</code></a> interface that is read back out
via the <a href="#class-streamreadable"><code>Readable</code></a> interface.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> kSource = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'source'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDuplex</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Duplex</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">source, options</span>) {
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-variable language_">this</span>[kSource] = source;
}
<span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// The underlying source only deals with strings.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(chunk))
chunk = chunk.<span class="hljs-title function_">toString</span>();
<span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">writeSomeData</span>(chunk);
<span class="hljs-title function_">callback</span>();
}
<span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) {
<span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">fetchSomeData</span>(size, <span class="hljs-function">(<span class="hljs-params">data, encoding</span>) =></span> {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data, encoding));
});
}
}</code> <button class="copy-button">copy</button></pre>
<p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and
<code>Writable</code> sides operate independently of one another despite co-existing within
a single object instance.</p>
<h5>Object mode duplex streams<span><a class="mark" href="#object-mode-duplex-streams" id="object-mode-duplex-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_object_mode_duplex_streams"></a></h5>
<p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the
<code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and
<code>writableObjectMode</code> options respectively.</p>
<p>In the following example, for instance, a new <code>Transform</code> stream (which is a
type of <a href="#class-streamduplex"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side
that accepts JavaScript numbers that are converted to hexadecimal strings on
the <code>Readable</code> side.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-comment">// All Transform streams are also Duplex Streams.</span>
<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
<span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>,
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// Coerce the chunk to a number if necessary.</span>
chunk |= <span class="hljs-number">0</span>;
<span class="hljs-comment">// Transform the chunk into something else.</span>
<span class="hljs-keyword">const</span> data = chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>);
<span class="hljs-comment">// Push the data onto the readable queue.</span>
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'0'</span>.<span class="hljs-title function_">repeat</span>(data.<span class="hljs-property">length</span> % <span class="hljs-number">2</span>) + data);
},
});
myTransform.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'ascii'</span>);
myTransform.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk));
myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Prints: 01</span>
myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Prints: 0a</span>
myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">100</span>);
<span class="hljs-comment">// Prints: 64</span></code> <button class="copy-button">copy</button></pre>
<h4>Implementing a transform stream<span><a class="mark" href="#implementing-a-transform-stream" id="implementing-a-transform-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_transform_stream"></a></h4>
<p>A <a href="#class-streamtransform"><code>Transform</code></a> stream is a <a href="#class-streamduplex"><code>Duplex</code></a> stream where the output is computed
in some way from the input. Examples include <a href="zlib.html">zlib</a> streams or <a href="crypto.html">crypto</a>
streams that compress, encrypt, or decrypt data.</p>
<p>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 <code>Hash</code> stream will
only ever have a single chunk of output which is provided when the input is
ended. A <code>zlib</code> stream will produce output that is either much smaller or much
larger than its input.</p>
<p>The <code>stream.Transform</code> class is extended to implement a <a href="#class-streamtransform"><code>Transform</code></a> stream.</p>
<p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and
implements its own versions of the <code>writable._write()</code> and
<a href="#readable_readsize"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em>
implement the <a href="#transform_transformchunk-encoding-callback"><code>transform._transform()</code></a> method and <em>may</em>
also implement the <a href="#transform_flushcallback"><code>transform._flush()</code></a> method.</p>
<p>Care must be taken when using <code>Transform</code> streams in that data written to the
stream can cause the <code>Writable</code> side of the stream to become paused if the
output on the <code>Readable</code> side is not consumed.</p>
<h5><code>new stream.Transform([options])</code><span><a class="mark" href="#new-streamtransformoptions" id="new-streamtransformoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_transform_options"></a></h5>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Passed to both <code>Writable</code> and <code>Readable</code>
constructors. Also has the following fields:
<ul>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the
<a href="#transform_transformchunk-encoding-callback"><code>stream._transform()</code></a> method.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#transform_flushcallback"><code>stream._flush()</code></a>
method.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyTransform</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Transform</span> {
<span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
<span class="hljs-variable language_">super</span>(options);
<span class="hljs-comment">// ...</span>
}
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyTransform</span>(<span class="hljs-params">options</span>) {
<span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyTransform</span>))
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyTransform</span>(options);
<span class="hljs-title class_">Transform</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyTransform</span>, <span class="hljs-title class_">Transform</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
<span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
<span class="hljs-comment">// ...</span>
},
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'end'</code><span><a class="mark" href="#event-end_1" id="event-end_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end_1"></a></h5>
<p>The <a href="#event-end"><code>'end'</code></a> event is from the <code>stream.Readable</code> class. The <code>'end'</code> event is
emitted after all data has been output, which occurs after the callback in
<a href="#transform_flushcallback"><code>transform._flush()</code></a> has been called. In the case of an error,
<code>'end'</code> should not be emitted.</p>
<h5>Event: <code>'finish'</code><span><a class="mark" href="#event-finish_1" id="event-finish_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish_1"></a></h5>
<p>The <a href="#event-finish"><code>'finish'</code></a> event is from the <code>stream.Writable</code> class. The <code>'finish'</code>
event is emitted after <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> is called and all chunks
have been processed by <a href="#transform_transformchunk-encoding-callback"><code>stream._transform()</code></a>. In the case
of an error, <code>'finish'</code> should not be emitted.</p>
<h5><code>transform._flush(callback)</code><span><a class="mark" href="#transform_flushcallback" id="transform_flushcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_flush_callback"></a></h5>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error
argument and data) to be called when remaining data has been flushed.</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Readable</code> class
methods only.</p>
<p>In some cases, a transform operation may need to emit an additional bit of
data at the end of the stream. For example, a <code>zlib</code> 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.</p>
<p>Custom <a href="#class-streamtransform"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code>
method. This will be called when there is no more written data to be consumed,
but before the <a href="#event-end"><code>'end'</code></a> event is emitted signaling the end of the
<a href="#class-streamreadable"><code>Readable</code></a> stream.</p>
<p>Within the <code>transform._flush()</code> implementation, the <code>transform.push()</code> method
may be called zero or more times, as appropriate. The <code>callback</code> function must
be called when the flush operation is complete.</p>
<p>The <code>transform._flush()</code> 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.</p>
<h5><code>transform._transform(chunk, encoding, callback)</code><span><a class="mark" href="#transform_transformchunk-encoding-callback" id="transform_transformchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_transform_chunk_encoding_callback"></a></h5>
<ul>
<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>Buffer</code> to be transformed, converted from
the <code>string</code> passed to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. If the stream's
<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode,
the chunk will not be converted & will be whatever was passed to
<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If the chunk is a string, then this is the
encoding type. If chunk is a buffer, then this is the special
value <code>'buffer'</code>. Ignore it in that case.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error
argument and data) to be called after the supplied <code>chunk</code> has been
processed.</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Readable</code> class
methods only.</p>
<p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code>
method to accept input and produce output. The <code>transform._transform()</code>
implementation handles the bytes being written, computes an output, then passes
that output off to the readable portion using the <code>transform.push()</code> method.</p>
<p>The <code>transform.push()</code> 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.</p>
<p>It is possible that no output is generated from any given chunk of input data.</p>
<p>The <code>callback</code> function must be called only when the current chunk is completely
consumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object
if an error occurred while processing the input or <code>null</code> otherwise. If a second
argument is passed to the <code>callback</code>, it will be forwarded on to the
<code>transform.push()</code> method, but only if the first argument is falsy. In other
words, the following are equivalent:</p>
<pre><code class="language-js">transform.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">_transform</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data, encoding, callback</span>) {
<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(data);
<span class="hljs-title function_">callback</span>();
};
transform.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">_transform</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data, encoding, callback</span>) {
<span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, data);
};</code> <button class="copy-button">copy</button></pre>
<p>The <code>transform._transform()</code> 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.</p>
<p><code>transform._transform()</code> is never called in parallel; streams implement a
queue mechanism, and to receive the next chunk, <code>callback</code> must be
called, either synchronously or asynchronously.</p>
<h5>Class: <code>stream.PassThrough</code><span><a class="mark" href="#class-streampassthrough" id="class-streampassthrough">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_passthrough"></a></h5>
<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#class-streamtransform"><code>Transform</code></a>
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
<code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p>
</section><section><h3>Additional notes<span><a class="mark" href="#additional-notes" id="additional-notes">#</a></span><a aria-hidden="true" class="legacy" id="stream_additional_notes"></a></h3>
<h4>Streams compatibility with async generators and async iterators<span><a class="mark" href="#streams-compatibility-with-async-generators-and-async-iterators" id="streams-compatibility-with-async-generators-and-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_streams_compatibility_with_async_generators_and_async_iterators"></a></h4>
<p>With the support of async generators and iterators in JavaScript, async
generators are effectively a first-class language-level stream construct at
this point.</p>
<p>Some common interop cases of using Node.js streams with async generators
and async iterators are provided below.</p>
<h5>Consuming readable streams with async iterators<span><a class="mark" href="#consuming-readable-streams-with-async-iterators" id="consuming-readable-streams-with-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_consuming_readable_streams_with_async_iterators"></a></h5>
<pre><code class="language-js">(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">for</span> <span class="hljs-title function_">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
}
})();</code> <button class="copy-button">copy</button></pre>
<p>Async iterators register a permanent error handler on the stream to prevent any
unhandled post-destroy errors.</p>
<h5>Creating readable streams with async generators<span><a class="mark" href="#creating-readable-streams-with-async-generators" id="creating-readable-streams-with-async-generators">#</a></span><a aria-hidden="true" class="legacy" id="stream_creating_readable_streams_with_async_generators"></a></h5>
<p>A Node.js readable stream can be created from an asynchronous generator using
the <code>Readable.from()</code> utility method:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningFn</span>({ signal });
<span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>;
<span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>;
}
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>());
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
ac.<span class="hljs-title function_">abort</span>();
});
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
});</code> <button class="copy-button">copy</button></pre>
<h5>Piping to writable streams from async iterators<span><a class="mark" href="#piping-to-writable-streams-from-async-iterators" id="piping-to-writable-streams-from-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_piping_to_writable_streams_from_async_iterators"></a></h5>
<p>When writing to a writable stream from an async iterator, ensure correct
handling of backpressure and errors. <a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a> abstracts away
the handling of backpressure and backpressure-related errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">pipeline</span>: pipelinePromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./file'</span>);
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;
<span class="hljs-keyword">const</span> iterator = <span class="hljs-title function_">createIterator</span>({ signal });
<span class="hljs-comment">// Callback Pattern</span>
<span class="hljs-title function_">pipeline</span>(iterator, writable, <span class="hljs-function">(<span class="hljs-params">err, value</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
} <span class="hljs-keyword">else</span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>);
}
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
ac.<span class="hljs-title function_">abort</span>();
});
<span class="hljs-comment">// Promise Pattern</span>
<span class="hljs-title function_">pipelinePromise</span>(iterator, writable)
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>);
})
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
ac.<span class="hljs-title function_">abort</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4>Compatibility with older Node.js versions<span><a class="mark" href="#compatibility-with-older-nodejs-versions" id="compatibility-with-older-nodejs-versions">#</a></span><a aria-hidden="true" class="legacy" id="stream_compatibility_with_older_node_js_versions"></a></h4>
<p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also
less powerful and less useful.</p>
<ul>
<li>Rather than waiting for calls to the <a href="#readablereadsize"><code>stream.read()</code></a> method,
<a href="#event-data"><code>'data'</code></a> 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.</li>
<li>The <a href="#readablepause"><code>stream.pause()</code></a> method was advisory, rather than
guaranteed. This meant that it was still necessary to be prepared to receive
<a href="#event-data"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li>
</ul>
<p>In Node.js 0.10, the <a href="#class-streamreadable"><code>Readable</code></a> class was added. For backward
compatibility with older Node.js programs, <code>Readable</code> streams switch into
"flowing mode" when a <a href="#event-data"><code>'data'</code></a> event handler is added, or when the
<a href="#readableresume"><code>stream.resume()</code></a> method is called. The effect is that, even
when not using the new <a href="#readablereadsize"><code>stream.read()</code></a> method and
<a href="#event-readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing
<a href="#event-data"><code>'data'</code></a> chunks.</p>
<p>While most applications will continue to function normally, this introduces an
edge case in the following conditions:</p>
<ul>
<li>No <a href="#event-data"><code>'data'</code></a> event listener is added.</li>
<li>The <a href="#readableresume"><code>stream.resume()</code></a> method is never called.</li>
<li>The stream is not piped to any writable destination.</li>
</ul>
<p>For example, consider the following code:</p>
<pre><code class="language-js"><span class="hljs-comment">// WARNING! BROKEN!</span>
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
<span class="hljs-comment">// We add an 'end' listener, but never consume the data.</span>
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// It will never get here.</span>
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>);
});
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre>
<p>Prior to Node.js 0.10, the incoming message data would be simply discarded.
However, in Node.js 0.10 and beyond, the socket remains paused forever.</p>
<p>The workaround in this situation is to call the
<a href="#readableresume"><code>stream.resume()</code></a> method to begin the flow of data:</p>
<pre><code class="language-js"><span class="hljs-comment">// Workaround.</span>
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>);
});
<span class="hljs-comment">// Start the flow of data, discarding it.</span>
socket.<span class="hljs-title function_">resume</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre>
<p>In addition to new <code>Readable</code> streams switching into flowing mode,
pre-0.10 style streams can be wrapped in a <code>Readable</code> class using the
<a href="#readablewrapstream"><code>readable.wrap()</code></a> method.</p>
<h4><code>readable.read(0)</code><span><a class="mark" href="#readableread0" id="readableread0">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_0"></a></h4>
<p>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 <code>readable.read(0)</code>, which will
always return <code>null</code>.</p>
<p>If the internal read buffer is below the <code>highWaterMark</code>, and the
stream is not currently reading, then calling <code>stream.read(0)</code> will trigger
a low-level <a href="#readable_readsize"><code>stream._read()</code></a> call.</p>
<p>While most applications will almost never need to do this, there are
situations within Node.js where this is done, particularly in the
<code>Readable</code> stream class internals.</p>
<h4><code>readable.push('')</code><span><a class="mark" href="#readablepush" id="readablepush">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_push"></a></h4>
<p>Use of <code>readable.push('')</code> is not recommended.</p>
<p>Pushing a zero-byte <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>, <a href="buffer.html#class-buffer" class="type"><Buffer></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> to a stream
that is not in object mode has an interesting side effect.
Because it <em>is</em> a call to
<a href="#readablepushchunk-encoding"><code>readable.push()</code></a>, 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.</p>
<h4><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code><span><a class="mark" href="#highwatermark-discrepancy-after-calling-readablesetencoding" id="highwatermark-discrepancy-after-calling-readablesetencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_highwatermark_discrepancy_after_calling_readable_setencoding"></a></h4>
<p>The use of <code>readable.setEncoding()</code> will change the behavior of how the
<code>highWaterMark</code> operates in non-object mode.</p>
<p>Typically, the size of the current buffer is measured against the
<code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the
comparison function will begin to measure the buffer's size in <em>characters</em>.</p>
<p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is
advised to be mindful about this behavior when working with strings that could
contain multi-byte characters.</p></section>
<!-- API END -->
</div>
</div>
</div>
</body>
</html>
|